code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, CApiFFI #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- 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 (requires POSIX)
--
-- 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)
--
-----------------------------------------------------------------------------
module System.Posix.Internals where
import System.Posix.Types
import Foreign
import Foreign.C
-- import Data.Bits
import Data.Maybe
#if !defined(HTYPE_TCFLAG_T)
import System.IO.Error
#endif
import GHC.Base
import GHC.Num
import GHC.Real
import GHC.IO
import GHC.IO.IOMode
import GHC.IO.Exception
import GHC.IO.Device
#ifndef mingw32_HOST_OS
import {-# SOURCE #-} GHC.IO.Encoding (getFileSystemEncoding)
import qualified GHC.Foreign as GHC
#endif
-- ---------------------------------------------------------------------------
-- Debugging the base package
puts :: String -> IO ()
puts s = withCAStringLen (s ++ "\n") $ \(p, len) -> do
-- In reality should be withCString, but assume ASCII to avoid loop
-- if this is called by GHC.Foreign
_ <- c_write undefined (castPtr p) (fromIntegral len)
-- _ <- c_write 1 (castPtr p) (fromIntegral len)
return ()
-- ---------------------------------------------------------------------------
-- Types
type CFLock = ()
data {-# CTYPE "struct group" #-} CGroup
type CLconv = ()
type CPasswd = ()
type CSigaction = ()
data {-# CTYPE "sigset_t" #-} CSigset
type CStat = ()
type CTermios = ()
type CTm = ()
type CTms = ()
type CUtimbuf = ()
type CUtsname = ()
type FD = CInt
-- ---------------------------------------------------------------------------
-- stat()-related stuff
fdFileSize :: FD -> IO Integer
fdFileSize fd =
allocaBytes sizeof_stat $ \ p_stat -> do
throwErrnoIfMinus1Retry_ "fileSize" $
c_fstat 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
return (fromIntegral c_size)
fileType :: FilePath -> IO IODeviceType
fileType file =
allocaBytes sizeof_stat $ \ p_stat -> do
withFilePath 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.
fdStat :: FD -> IO (IODeviceType, CDev, CIno)
fdStat fd =
allocaBytes sizeof_stat $ \ p_stat -> do
throwErrnoIfMinus1Retry_ "fdType" $
c_fstat fd p_stat
ty <- statGetType p_stat
dev <- st_dev p_stat
ino <- st_ino p_stat
return (ty,dev,ino)
fdType :: FD -> IO IODeviceType
fdType fd = do (ty,_,_) <- fdStat fd; return ty
statGetType :: Ptr CStat -> IO IODeviceType
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
-- Q: map char devices to RawDevice too?
| s_isblk c_mode -> return RawDevice
| otherwise -> ioError ioe_unknownfiletype
ioe_unknownfiletype :: IOException
ioe_unknownfiletype = IOError Nothing UnsupportedOperation "fdType"
"unknown file type"
Nothing
Nothing
fdGetMode :: FD -> IO IOMode
#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
fdGetMode _ = do
-- We don't have a way of finding out which flags are set on FDs
-- on Windows, so make a handle that thinks that anything goes.
let flags = o_RDWR
#else
fdGetMode fd = do
flags <- throwErrnoIfMinus1Retry "fdGetMode"
(c_fcntl_read fd const_f_getfl)
#endif
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
#ifdef mingw32_HOST_OS
withFilePath :: FilePath -> (CWString -> IO a) -> IO a
withFilePath = withCWString
newFilePath :: FilePath -> IO CWString
newFilePath = newCWString
peekFilePath :: CWString -> IO FilePath
peekFilePath = peekCWString
#else
withFilePath :: FilePath -> (CString -> IO a) -> IO a
newFilePath :: FilePath -> IO CString
peekFilePath :: CString -> IO FilePath
peekFilePathLen :: CStringLen -> IO FilePath
withFilePath fp f = getFileSystemEncoding >>= \enc -> GHC.withCString enc fp f
newFilePath fp = getFileSystemEncoding >>= \enc -> GHC.newCString enc fp
peekFilePath fp = getFileSystemEncoding >>= \enc -> GHC.peekCString enc fp
peekFilePathLen fp = getFileSystemEncoding >>= \enc -> GHC.peekCStringLen enc fp
#endif
-- ---------------------------------------------------------------------------
-- Terminal-related stuff
#if defined(HTYPE_TCFLAG_T)
setEcho :: FD -> Bool -> IO ()
setEcho fd on = do
tcSetAttr fd $ \ p_tios -> do
lflag <- c_lflag p_tios :: IO CTcflag
let new_lflag
| on = lflag .|. fromIntegral const_echo
| otherwise = lflag .&. complement (fromIntegral const_echo)
poke_c_lflag p_tios (new_lflag :: CTcflag)
getEcho :: FD -> IO Bool
getEcho fd = do
tcSetAttr fd $ \ p_tios -> do
lflag <- c_lflag p_tios :: IO CTcflag
return ((lflag .&. fromIntegral const_echo) /= 0)
setCooked :: FD -> Bool -> IO ()
setCooked fd cooked =
tcSetAttr fd $ \ p_tios -> do
-- turn on/off ICANON
lflag <- c_lflag p_tios :: IO CTcflag
let new_lflag | cooked = lflag .|. (fromIntegral const_icanon)
| otherwise = lflag .&. complement (fromIntegral const_icanon)
poke_c_lflag p_tios (new_lflag :: CTcflag)
-- set VMIN & VTIME to 1/0 respectively
when (not cooked) $ do
c_cc <- ptr_c_cc p_tios
let vmin = (c_cc `plusPtr` (fromIntegral const_vmin)) :: Ptr Word8
vtime = (c_cc `plusPtr` (fromIntegral const_vtime)) :: Ptr Word8
poke vmin 1
poke vtime 0
tcSetAttr :: FD -> (Ptr CTermios -> IO a) -> IO a
tcSetAttr fd fun = do
allocaBytes sizeof_termios $ \p_tios -> do
throwErrnoIfMinus1Retry_ "tcSetAttr"
(c_tcgetattr fd p_tios)
-- Save a copy of termios, if this is a standard file descriptor.
-- These terminal settings are restored in hs_exit().
when (fd <= 2) $ do
p <- get_saved_termios fd
when (p == nullPtr) $ do
saved_tios <- mallocBytes sizeof_termios
copyBytes saved_tios p_tios sizeof_termios
set_saved_termios fd saved_tios
-- tcsetattr() when invoked by a background process causes the process
-- to be sent SIGTTOU regardless of whether the process has TOSTOP set
-- in its terminal flags (try it...). This function provides a
-- wrapper which temporarily blocks SIGTTOU around the call, making it
-- transparent.
allocaBytes sizeof_sigset_t $ \ p_sigset -> do
allocaBytes sizeof_sigset_t $ \ p_old_sigset -> do
throwErrnoIfMinus1_ "sigemptyset" $
c_sigemptyset p_sigset
throwErrnoIfMinus1_ "sigaddset" $
c_sigaddset p_sigset const_sigttou
throwErrnoIfMinus1_ "sigprocmask" $
c_sigprocmask const_sig_block p_sigset p_old_sigset
r <- fun p_tios -- do the business
throwErrnoIfMinus1Retry_ "tcSetAttr" $
c_tcsetattr fd const_tcsanow p_tios
throwErrnoIfMinus1_ "sigprocmask" $
c_sigprocmask const_sig_setmask p_old_sigset nullPtr
return r
-- TODO: Implement
-- foreign import ccall unsafe "HsBase.h __hscore_get_saved_termios"
get_saved_termios :: CInt -> IO (Ptr CTermios)
get_saved_termios = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_set_saved_termios"
set_saved_termios :: CInt -> (Ptr CTermios) -> IO ()
set_saved_termios = undefined
#else
-- '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 :: FD -> Bool -> IO ()
setCooked fd cooked = do
x <- set_console_buffering fd (if cooked then 1 else 0)
if (x /= 0)
then ioError (ioe_unk_error "setCooked" "failed to set buffering")
else return ()
ioe_unk_error :: String -> String -> IOException
ioe_unk_error loc msg
= ioeSetErrorString (mkIOError OtherError loc Nothing Nothing) msg
-- 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 :: FD -> Bool -> IO ()
setEcho fd on = do
x <- set_console_echo fd (if on then 1 else 0)
if (x /= 0)
then ioError (ioe_unk_error "setEcho" "failed to set echoing")
else return ()
getEcho :: FD -> IO Bool
getEcho fd = do
r <- get_console_echo fd
if (r == (-1))
then ioError (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
set_console_buffering = undefined
-- foreign import ccall unsafe "consUtils.h set_console_echo__"
set_console_echo :: CInt -> CInt -> IO CInt
set_console_echo = undefined
-- foreign import ccall unsafe "consUtils.h get_console_echo__"
get_console_echo :: CInt -> IO CInt
get_console_echo = undefined
-- foreign import ccall unsafe "consUtils.h is_console__"
is_console :: CInt -> IO CInt
is_console = undefined
#endif
-- ---------------------------------------------------------------------------
-- Turning on non-blocking for a file descriptor
setNonBlockingFD :: FD -> Bool -> IO ()
#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
setNonBlockingFD fd set = do
flags <- throwErrnoIfMinus1Retry "setNonBlockingFD"
(c_fcntl_read fd const_f_getfl)
let flags' | set = flags .|. o_NONBLOCK
| otherwise = flags .&. complement o_NONBLOCK
when (flags /= flags') $ do
-- An error when setting O_NONBLOCK isn't fatal: on some systems
-- there are certain file handles on which this will fail (eg. /dev/null
-- on FreeBSD) so we throw away the return code from fcntl_write.
_ <- c_fcntl_write fd const_f_setfl (fromIntegral flags')
return ()
#else
-- bogus defns for win32
setNonBlockingFD _ _ = return ()
#endif
-- -----------------------------------------------------------------------------
-- Set close-on-exec for a file descriptor
#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
setCloseOnExec :: FD -> IO ()
setCloseOnExec fd = do
throwErrnoIfMinus1_ "setCloseOnExec" $
c_fcntl_write fd const_f_setfd const_fd_cloexec
#endif
-- -----------------------------------------------------------------------------
-- foreign imports
#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
type CFilePath = CString
#else
type CFilePath = CWString
#endif
-- foreign import ccall unsafe "HsBase.h access"
c_access :: CString -> CInt -> IO CInt
c_access = undefined
-- foreign import ccall unsafe "HsBase.h chmod"
c_chmod :: CString -> CMode -> IO CInt
c_chmod = undefined
-- foreign import ccall unsafe "HsBase.h close"
c_close :: CInt -> IO CInt
c_close = undefined
-- foreign import ccall unsafe "HsBase.h creat"
c_creat :: CString -> CMode -> IO CInt
c_creat = undefined
-- foreign import ccall unsafe "HsBase.h dup"
c_dup :: CInt -> IO CInt
c_dup = undefined
-- foreign import ccall unsafe "HsBase.h dup2"
c_dup2 :: CInt -> CInt -> IO CInt
c_dup2 = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_fstat"
c_fstat :: CInt -> Ptr CStat -> IO CInt
c_fstat = undefined
foreign import java unsafe "@static eta.base.Utils.c_isatty"
c_isatty :: CInt -> IO CInt
#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
-- foreign import ccall unsafe "io.h _lseeki64"
c_lseek :: CInt -> Int64 -> CInt -> IO Int64
c_lseek = undefined
#else
-- We use CAPI as on some OSs (eg. Linux) this is wrapped by a macro
-- which redirects to the 64-bit-off_t versions when large file
-- support is enabled.
-- foreign import capi unsafe "unistd.h lseek"
c_lseek :: CInt -> COff -> CInt -> IO COff
c_lseek = undefined
#endif
-- foreign import ccall unsafe "HsBase.h __hscore_lstat"
lstat :: CFilePath -> Ptr CStat -> IO CInt
lstat = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_open"
c_open :: CFilePath -> CInt -> CMode -> IO CInt
c_open = undefined
-- foreign import ccall safe "HsBase.h __hscore_open"
c_safe_open :: CFilePath -> CInt -> CMode -> IO CInt
c_safe_open = undefined
-- See Note: CSsize
foreign import java unsafe "@static eta.base.Utils.c_read"
c_read :: Channel -> Ptr Word8 -> CSize -> IO CSsize
-- See Note: CSsize
foreign import java safe "@static eta.base.Utils.c_read"
c_safe_read :: Channel -> Ptr Word8 -> CSize -> IO CSsize
-- foreign import ccall unsafe "HsBase.h __hscore_stat"
c_stat :: CFilePath -> Ptr CStat -> IO CInt
c_stat = undefined
-- foreign import ccall unsafe "HsBase.h umask"
c_umask :: CMode -> IO CMode
c_umask = undefined
-- See Note: CSsize
foreign import java unsafe "@static eta.base.Utils.c_write"
c_write :: Channel -> Ptr Word8 -> CSize -> IO CSsize
-- See Note: CSsize
foreign import java safe "@static eta.base.Utils.c_write"
c_safe_write :: Channel -> Ptr Word8 -> CSize -> IO CSsize
-- foreign import ccall unsafe "HsBase.h __hscore_ftruncate"
c_ftruncate :: CInt -> COff -> IO CInt
c_ftruncate = undefined
-- foreign import ccall unsafe "HsBase.h unlink"
c_unlink :: CString -> IO CInt
c_unlink = undefined
-- foreign import ccall unsafe "HsBase.h getpid"
c_getpid :: IO CPid
c_getpid = undefined
#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
-- foreign import capi unsafe "HsBase.h fcntl"
c_fcntl_read :: CInt -> CInt -> IO CInt
c_fcntl_read = undefined
-- foreign import capi unsafe "HsBase.h fcntl"
c_fcntl_write :: CInt -> CInt -> CLong -> IO CInt
c_fcntl_write = undefined
-- foreign import capi unsafe "HsBase.h fcntl"
c_fcntl_lock :: CInt -> CInt -> Ptr CFLock -> IO CInt
c_fcntl_lock = undefined
-- foreign import ccall unsafe "HsBase.h fork"
c_fork :: IO CPid
c_fork = undefined
-- foreign import ccall unsafe "HsBase.h link"
c_link :: CString -> CString -> IO CInt
c_link = undefined
-- capi is required at least on Android
-- foreign import capi unsafe "HsBase.h mkfifo"
c_mkfifo :: CString -> CMode -> IO CInt
c_mkfifo = undefined
-- foreign import ccall unsafe "HsBase.h pipe"
c_pipe :: Ptr CInt -> IO CInt
c_pipe = undefined
-- foreign import capi unsafe "signal.h sigemptyset"
c_sigemptyset :: Ptr CSigset -> IO CInt
c_sigemptyset = undefined
-- foreign import capi unsafe "signal.h sigaddset"
c_sigaddset :: Ptr CSigset -> CInt -> IO CInt
c_sigaddset = undefined
-- foreign import capi unsafe "signal.h sigprocmask"
c_sigprocmask :: CInt -> Ptr CSigset -> Ptr CSigset -> IO CInt
c_sigprocmask = undefined
-- capi is required at least on Android
-- foreign import capi unsafe "HsBase.h tcgetattr"
c_tcgetattr :: CInt -> Ptr CTermios -> IO CInt
c_tcgetattr = undefined
-- capi is required at least on Android
-- foreign import capi unsafe "HsBase.h tcsetattr"
c_tcsetattr :: CInt -> CInt -> Ptr CTermios -> IO CInt
c_tcsetattr = undefined
-- foreign import capi unsafe "HsBase.h utime"
c_utime :: CString -> Ptr CUtimbuf -> IO CInt
c_utime = undefined
-- foreign import ccall unsafe "HsBase.h waitpid"
c_waitpid :: CPid -> Ptr CInt -> CInt -> IO CPid
c_waitpid = undefined
#endif
-- POSIX flags only:
-- foreign import ccall unsafe "HsBase.h __hscore_o_rdonly"
o_RDONLY :: CInt
o_RDONLY = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_o_wronly"
o_WRONLY :: CInt
o_WRONLY = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_o_rdwr"
o_RDWR :: CInt
o_RDWR = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_o_append"
o_APPEND :: CInt
o_APPEND = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_o_creat"
o_CREAT :: CInt
o_CREAT = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_o_excl"
o_EXCL :: CInt
o_EXCL = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_o_trunc"
o_TRUNC :: CInt
o_TRUNC = undefined
-- non-POSIX flags.
-- foreign import ccall unsafe "HsBase.h __hscore_o_noctty"
o_NOCTTY :: CInt
o_NOCTTY = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_o_nonblock"
o_NONBLOCK :: CInt
o_NONBLOCK = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_o_binary"
o_BINARY :: CInt
o_BINARY = undefined
-- foreign import capi unsafe "sys/stat.h S_ISREG"
c_s_isreg :: CMode -> CInt
c_s_isreg = undefined
-- foreign import capi unsafe "sys/stat.h S_ISCHR"
c_s_ischr :: CMode -> CInt
c_s_ischr = undefined
-- foreign import capi unsafe "sys/stat.h S_ISBLK"
c_s_isblk :: CMode -> CInt
c_s_isblk = undefined
-- foreign import capi unsafe "sys/stat.h S_ISDIR"
c_s_isdir :: CMode -> CInt
c_s_isdir = undefined
-- foreign import capi unsafe "sys/stat.h S_ISFIFO"
c_s_isfifo :: CMode -> CInt
c_s_isfifo = undefined
s_isreg :: CMode -> Bool
s_isreg cm = c_s_isreg cm /= 0
s_ischr :: CMode -> Bool
s_ischr cm = c_s_ischr cm /= 0
s_isblk :: CMode -> Bool
s_isblk cm = c_s_isblk cm /= 0
s_isdir :: CMode -> Bool
s_isdir cm = c_s_isdir cm /= 0
s_isfifo :: CMode -> Bool
s_isfifo cm = c_s_isfifo cm /= 0
-- foreign import ccall unsafe "HsBase.h __hscore_sizeof_stat"
sizeof_stat :: Int
sizeof_stat = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_st_mtime"
st_mtime :: Ptr CStat -> IO CTime
st_mtime = undefined
#ifdef mingw32_HOST_OS
-- foreign import ccall unsafe "HsBase.h __hscore_st_size"
st_size :: Ptr CStat -> IO Int64
st_size = undefined
#else
-- foreign import ccall unsafe "HsBase.h __hscore_st_size"
st_size :: Ptr CStat -> IO COff
st_size = undefined
#endif
-- foreign import ccall unsafe "HsBase.h __hscore_st_mode"
st_mode :: Ptr CStat -> IO CMode
st_mode = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_st_dev"
st_dev :: Ptr CStat -> IO CDev
st_dev = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_st_ino"
st_ino :: Ptr CStat -> IO CIno
st_ino = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_echo"
const_echo :: CInt
const_echo = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_tcsanow"
const_tcsanow :: CInt
const_tcsanow = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_icanon"
const_icanon :: CInt
const_icanon = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_vmin"
const_vmin :: CInt
const_vmin = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_vtime"
const_vtime :: CInt
const_vtime = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_sigttou"
const_sigttou :: CInt
const_sigttou = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_sig_block"
const_sig_block :: CInt
const_sig_block = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_sig_setmask"
const_sig_setmask :: CInt
const_sig_setmask = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_f_getfl"
const_f_getfl :: CInt
const_f_getfl = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_f_setfl"
const_f_setfl :: CInt
const_f_setfl = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_f_setfd"
const_f_setfd :: CInt
const_f_setfd = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_fd_cloexec"
const_fd_cloexec :: CLong
const_fd_cloexec = undefined
#if defined(HTYPE_TCFLAG_T)
-- foreign import ccall unsafe "HsBase.h __hscore_sizeof_termios"
sizeof_termios :: Int
sizeof_termios = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_sizeof_sigset_t"
sizeof_sigset_t :: Int
sizeof_sigset_t = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_lflag"
c_lflag :: Ptr CTermios -> IO CTcflag
c_lflag = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_poke_lflag"
poke_c_lflag :: Ptr CTermios -> CTcflag -> IO ()
poke_c_lflag = undefined
-- foreign import ccall unsafe "HsBase.h __hscore_ptr_c_cc"
ptr_c_cc :: Ptr CTermios -> IO (Ptr Word8)
ptr_c_cc = undefined
#endif
s_issock :: CMode -> Bool
#if !defined(mingw32_HOST_OS) && !defined(__MINGW32__)
s_issock cmode = c_s_issock cmode /= 0
-- foreign import capi unsafe "sys/stat.h S_ISSOCK"
c_s_issock :: CMode -> CInt
c_s_issock = undefined
#else
s_issock _ = False
#endif
-- foreign import ccall unsafe "__hscore_bufsiz"
dEFAULT_BUFFER_SIZE :: Int
dEFAULT_BUFFER_SIZE = undefined
-- foreign import capi unsafe "stdio.h value SEEK_CUR"
sEEK_CUR :: CInt
sEEK_CUR = undefined
-- foreign import capi unsafe "stdio.h value SEEK_SET"
sEEK_SET :: CInt
sEEK_SET = undefined
-- foreign import capi unsafe "stdio.h value SEEK_END"
sEEK_END :: CInt
sEEK_END = undefined
{-
Note: CSsize
On Win64, ssize_t is 64 bit, but functions like read return 32 bit
ints. The CAPI wrapper means the C compiler takes care of doing all
the necessary casting.
When using ccall instead, when the functions failed with -1, we thought
they were returning with 4294967295, and so didn't throw an exception.
This lead to a segfault in echo001(ghci).
-}
| alexander-at-github/eta | libraries/base/System/Posix/Internals.hs | bsd-3-clause | 22,117 | 31 | 20 | 4,362 | 3,521 | 1,865 | 1,656 | -1 | -1 |
-- |
-- Module: Language.KURE
-- Copyright: (c) 2006-2008 Andy Gill
-- License: BSD3
--
-- Maintainer: Andy Gill <andygill@ku.edu>
-- Stability: unstable
-- Portability: ghc
--
-- This is the main import module for KURE, which exports all the major components.
--
--
module Language.KURE
( module Language.KURE.RewriteMonad
, module Language.KURE.Translate
, module Language.KURE.Rewrite
, module Language.KURE.Combinators
, module Language.KURE.Term
) where
import Language.KURE.RewriteMonad
import Language.KURE.Translate
import Language.KURE.Rewrite
import Language.KURE.Combinators
import Language.KURE.Term
| andygill/kure | Language/KURE.hs | bsd-3-clause | 621 | 4 | 5 | 82 | 89 | 64 | 25 | 11 | 0 |
module Text.Phidoc
( relink
, walk
, FileContent (..)
) where
import Text.Phidoc.Paths (relink)
import Text.Phidoc.Walk (FileContent (..), walk)
| Alxandr/Phidoc | src/Text/Phidoc.hs | bsd-3-clause | 175 | 0 | 6 | 49 | 50 | 33 | 17 | 6 | 0 |
{-# LANGUAGE OverloadedStrings,TemplateHaskell, QuasiQuotes #-}
module Text.Shakespeare.TemplateSpec (main, spec) where
import Text.Shakespeare.Template
import Test.Hspec
import Text.Hamlet
import Text.Blaze.Html.Renderer.Pretty
-- toStrict.renderHtml $ [shamlet|
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "hamToText" $ do
it "should translate an hamlet-template to text" $ do
(hamletToText $ testHamlet 3) `shouldBe` testResult
cowboy :: Maybe Int
cowboy = Just 3
testHamlet :: Int -> t -> Html
testHamlet i = [hamlet| a #{i}
|]
testHamletFile name myName = $(hamletFileWithSettings hamletRules grs "test_template.hamlet")
testResult = "a \n3\n \n"
testHamlet2 :: [Int] -> t -> Html
testHamlet2 names = [hamlet|
<h1> Here is an example string template
<h2> Thanks to the pretty printer in Blaze
<h3> We can do super fun stuff like
<h4> This
Hello::::
<table .table>
$forall name <- names
<tr>
<td> #{name}
|]
| plow-technologies/shakespeare-template | test/Text/Shakespeare/TemplateSpec.hs | bsd-3-clause | 979 | 0 | 16 | 184 | 203 | 114 | 89 | 21 | 1 |
-- {-# LANGUAGE FlexibleContexts #-}
module Main where
import qualified PatternRecogn.LinearRegression as LinearReg
import qualified AbstractTest as Test
import qualified LoadTestData as Load
import Utils( allPairs )
import Types
import PatternRecogn.Types
import Control.Monad.Random()
import Data.List( intercalate )
-----------------------------------------------------------------
-- IO stuff:
-----------------------------------------------------------------
main :: IO ()
main =
handleErrors $
forM_ (allPairs [3,5,7,8]) $ uncurry test
where
handleErrors x =
do
valOrErr <- runExceptT x
either
(\err -> putStrLn $ "ERROR: " ++ err)
return
valOrErr
test :: Label -> Label -> ErrT IO ()
test label1 label2 =
let
paths@[path1,path2] = map Load.pathFromLabel labels
labels = [label1, label2]
in
do
liftIO $ putStrLn $ concat $
["testing classification of ", intercalate ", " $ map show paths]
testData <- Load.readTestInputBin path1 path2 label1 label2
liftIO $ putStrLn $ "testing linear regression classification:"
testLinearRegression $ testData
testLinearRegression :: MonadIO m => TestDataBin -> m ()
testLinearRegression =
Test.testWithAlgBin
(\trainingData-> return $ LinearReg.calcClassificationParams trainingData)
(\param input -> return $ LinearReg.classify param input)
| EsGeh/pattern-recognition | test/LinearRegressionTest.hs | bsd-3-clause | 1,354 | 24 | 13 | 231 | 389 | 208 | 181 | 36 | 1 |
--This prime algorithm was taken from stack overflow. It's basically a sieve that is of O(1.5)
primes :: [Integer]
primes = 2: 3: sieve (tail primes) [5,7..]
where
sieve (p:ps) xs = h ++ sieve ps [x | x <- t, x `rem` p /= 0]
-- or: filter ((/=0).(`rem`p)) t
where (h,~(_:t)) = span (< p*p) xs
problem10 = sum $ takeWhile (<2000000) $ primes
| thomas-oo/projectEulerHaskell | src/Problem10.hs | bsd-3-clause | 397 | 0 | 12 | 121 | 149 | 81 | 68 | 5 | 1 |
{-# LANGUAGE InstanceTemplates, RebindableSyntax, MultiParamTypeClasses #-}
-- This is a sketch of what this code would look like with -XInstanceTemplates
import Prelude ( ($), (.), (>>), (>=) )
import qualified Prelude as P
class Addable a where (+) :: a -> a -> a
class Multiplicable a where (*) :: a -> a -> a
class Subtractable a where (-) :: a -> a -> a
class Negateable a where negate :: a -> a
class Absable a where abs :: a -> a
class Signumable a where signum :: a -> a
class FromIntegerable a where fromInteger :: P.Integer -> a
instance FromIntegerable P.Int where fromInteger = P.fromInteger
-- This instance template provides the same interface as the original Num class
-- (except for defaults, which should be supported)
deriving class Num a where
instance ( Addable a, Multiplicable a, Subtractable a, Negateable a
, Absable a, Signumable a, FromIntegerable a )
-- This instance template allows you to use a single declaration to generate
-- a
deriving class P.Num a => OldNum a where
instance Addable a where (+) = (P.+)
instance Multiplicable a where (*) = (P.*)
instance Subtractable a where (-) = (P.-)
instance Negateable a where negate = P.negate
instance Absable a where abs = P.abs
instance Signumable a where signum = P.signum
instance FromIntegerable a where fromInteger = P.fromInteger
-- This provides the boilerplate derivation of these numeric instances,
-- if you have a bijection from your type to a type that supports Num.
data Bij a b = Bij
{ fwd :: (a -> b)
, bwd :: (b -> a)
}
binBij :: Bij a b -> (a -> a -> a) -> (b -> b -> b)
binBij b f x y = fwd b $ f (bwd b x) (bwd b y)
inBij :: Bij a b -> (a -> a) -> (b -> b)
inBij b f = fwd b . f . bwd b
type BijNum a b = Num b
deriving class P.Num a => BijNum a b where
bij :: Bij a b
-- Note! This is invoking the template above.
instance Num a where
(+) = binBij bij (P.+)
(*) = binBij bij (P.*)
(-) = binBij bij (P.-)
negate = inBij bij P.negate
abs = inBij bij P.abs
signum = inBij bij P.signum
fromInteger = fwd bij . P.fromInteger
-- Usage
instance OldNum P.Double where
newtype Nat = Nat Int
deriving P.Show
instance BijNum P.Int Nat where
bij = Bij (Nat . P.max 0) (\(Nat i) -> i)
-- What if we had a more advanced, probably ill-founded, extension?
coercion class (c a) => BijCoerced c a b where
bij :: Bij a b
instance c a b using
fwd bij :: a -> b
bwd bij :: b -> a
instance BijCoerced Num P.Int Nat where
bij = Bij (Nat . P.max 0) (\(Nat i) -> i)
-- Could get even more convenience by being able to omit newtype wrapping:
instance Newtype Nat P.Int where
pack x = (Nat x)
unpack (Nat x) = x
coercion class BijCoerced2 cs a b where
bij :: Bij a b
instance cs using
fwd bij :: a -> b
bwd bij :: b -> a
unpack :: Newtype x y => x -> y
pack :: Newtype x y => y -> x
instance BijCoerced2 Num P.Int Nat where
bij = Bij (P.max 0) id
| mgsloan/instance-templates | tests/numeric/WithExt.hs | bsd-3-clause | 3,186 | 32 | 12 | 938 | 1,063 | 567 | 496 | -1 | -1 |
module PolyPaver.Subterms
(
addHashesInForm,
addHashesInTerm,
TermHash
)
where
import PolyPaver.Form
import qualified Data.IntMap as IMap
import Data.Hashable
--import Data.Data (Data, Typeable)
--import Data.List (intercalate, sortBy)
type TermHash = Int
addHashesInForm ::
(Hashable l, Eq l) =>
Form l -> Form TermHash
addHashesInForm form =
case form of
Not arg -> expOp1 Not arg
Or left right -> expOp2 Or left right
And left right -> expOp2 And left right
Implies left right -> expOp2 Implies left right
Le lab left right -> expT2 Le lab left right
Leq lab left right -> expT2 Leq lab left right
Ge lab left right -> expT2 Ge lab right left
Geq lab left right -> expT2 Geq lab right left
Eq lab left right -> expT2 Eq lab left right
Neq lab left right -> expT2 Neq lab left right
ContainedIn lab left right -> expT2 ContainedIn lab left right
IsRange lab t lower upper -> expT3 IsRange lab t lower upper
IsIntRange lab t lower upper -> expT3 IsIntRange lab t lower upper
IsInt lab t -> expT1 IsInt lab t
where
expOp1 op arg = op (addHashesInForm arg)
expOp2 op arg1 arg2 = op (addHashesInForm arg1) (addHashesInForm arg2)
expT1 op lab t = op lab (addHashesInTerm t)
expT2 op lab t1 t2 = op lab (addHashesInTerm t1) (addHashesInTerm t2)
expT3 op lab t1 t2 t3 = op lab (addHashesInTerm t1) (addHashesInTerm t2) (addHashesInTerm t3)
addHashesInTerm ::
(Hashable l, Eq l) =>
Term l -> Term TermHash
addHashesInTerm term =
fst $ addHashesInTermAux term
where
addHashesInTermAux (Term (term', _l)) =
(Term (termWithHashes, theHash), IMap.insert theHash term' termIndex)
where
theHash = hash term'
(termWithHashes, termIndex) = addHashesInTerm' term'
addHashesInTerm' term' =
case term' of
Lit r -> addHashes0 (Lit r)
MinusInfinity -> addHashes0 MinusInfinity
PlusInfinity -> addHashes0 PlusInfinity
Var n s -> addHashes0 (Var n s)
Hull t1 t2 -> addHashes2 Hull t1 t2
Plus t1 t2 -> addHashes2 Plus t1 t2
Minus t1 t2 -> addHashes2 Minus t1 t2
Neg t -> addHashes1 Neg t
Times t1 t2 -> addHashes2 Times t1 t2
Square t -> addHashes1 Square t
IntPower t1 t2 -> addHashes2 IntPower t1 t2
Recip t -> addHashes1 Recip t
Over t1 t2 -> addHashes2 Over t1 t2
Abs t -> addHashes1 Abs t
Min t1 t2 -> addHashes2 Min t1 t2
Max t1 t2 -> addHashes2 Max t1 t2
Pi -> addHashes0 Pi
Sqrt t -> addHashes1 Sqrt t
Exp t -> addHashes1 Exp t
Sin t -> addHashes1 Sin t
Cos t -> addHashes1 Cos t
Atan t -> addHashes1 Atan t
Integral ivarId ivarName lower upper integrand ->
addHashes3 (Integral ivarId ivarName) lower upper integrand
FEpsAbs a r -> addHashes0 $ FEpsAbs a r
FEpsRel a r -> addHashes0 $ FEpsRel a r
FEpsiAbs a r -> addHashes0 $ FEpsiAbs a r
FEpsiRel a r -> addHashes0 $ FEpsiRel a r
FRound a r t -> addHashes1 (FRound a r) t
FPlus a r t1 t2 -> addHashes2 (FPlus a r) t1 t2
FMinus a r t1 t2 -> addHashes2 (FMinus a r) t1 t2
FTimes a r t1 t2 -> addHashes2 (FTimes a r) t1 t2
FOver a r t1 t2 -> addHashes2 (FOver a r) t1 t2
FSquare a r t -> addHashes1 (FSquare a r) t
FSqrt a r t -> addHashes1 (FSqrt a r) t
FSin a r t -> addHashes1 (FSin a r) t
FCos a r t -> addHashes1 (FCos a r) t
FExp a r t -> addHashes1 (FExp a r) t
addHashes0 op =
(op, IMap.empty)
addHashes1 op t1 =
(op t1H, termIndex1)
where
(t1H, termIndex1) = addHashesInTermAux t1
addHashes2 op t1 t2 =
(op t1H t2H, termIndex)
where
(t1H, termIndex1) = addHashesInTermAux t1
(t2H, termIndex2) = addHashesInTermAux t2
termIndex = IMap.unionWith checkSame termIndex1 termIndex2
addHashes3 op t1 t2 t3 =
(op t1H t2H t3H, termIndex)
where
(t1H, termIndex1) = addHashesInTermAux t1
(t2H, termIndex2) = addHashesInTermAux t2
(t3H, termIndex3) = addHashesInTermAux t3
termIndex =
IMap.unionWith checkSame termIndex1 $
IMap.unionWith checkSame termIndex2 termIndex3
checkSame t1 t2
| t1 == t2 = t1
| otherwise =
error $ "A very rare internal error has occurred. Two different terms have the same hash."
| michalkonecny/polypaver | src/PolyPaver/Subterms.hs | bsd-3-clause | 4,751 | 0 | 12 | 1,604 | 1,634 | 778 | 856 | 104 | 37 |
{-# LANGUAGE RankNTypes, GADTs, TypeFamilies, TypeOperators, TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts, UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses, OverlappingInstances #-}
{-# LANGUAGE RecursiveDo #-}
-- {-# LANGUAGE NoMonomorphismRestriction #-}
module Hardware.HHDL.HHDL(
-- convenience exports.
module Data.Typeable
, module Hardware.HHDL.HDLPrelude
, module Prelude
, module Control.Monad.Fix
, module Hardware.HHDL.BitRepr
, module Hardware.HHDL.TyLeA
, module Hardware.HHDL.TH
-- This module exports.
, (:.)(..), Nil(Nil) -- our own HList.
, Wire -- abstract type.
, HDL(..) -- what kind of HDL you want to generate.
-- , WireOp(..) -- the means to extend operations.
, toBits -- a method to get bit vector from a type.
, WList
, WiresList -- a class that defines list of wires.
, NLM
, Clock(..), ClockAllowed
, Clocked -- the type constructor of clocked circuits.
, mkClockedNamed -- for top-level exported entities.
, mkClocked
, Comb -- the type constrictor of combinational (stateless) circuits.
, mkComb
, Mealy -- simple MEaly state machine.
, mkMealyNamed -- for top-level exported entities.
, mkMealy
, assignWire -- w <- assignWire (expression)
, assignFlattened
, register -- latched <- register defaultValue wireToLatch
, instantiate -- instantiate entity, literally. outputs <- instantiate entity inputs
, constant -- convert Haskell value (BitRepr one) into wire.
, extendZero
, extendOnes
, extendSign
, writeHDLText -- write HDL text of an entity.
, match -- match expression against list of patterns.
, (-->) -- combine pattern and netlists.
, pvar, pcst, pwild -- variable match, constant match, wildcard match.
, pJust, mkJust, pNothing, mkNothing -- generated for Maybe.
, pLeft, mkLeft, pRight, mkRight -- generated for Maybe.
) where
import Control.Monad.State
import Control.Monad
import Control.Monad.Fix
import qualified Data.Bits as B
import qualified Data.Bits
import Data.IORef
import Data.List (nub, intersperse, intercalate)
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Typeable
import Data.Word
import qualified Language.Haskell.TH as TH
import System.IO.Unsafe
import qualified Text.Printf
import Hardware.HHDL.BitRepr
import Hardware.HHDL.HDLPrelude
import Hardware.HHDL.TH
import Hardware.HHDL.TyLeA
-------------------------------------------------------------------------------
-- Our own HList.
infixr 5 :.
data a :. as = a :. as deriving Show
data Nil = Nil
-------------------------------------------------------------------------------
-- Unique index generation.
{-# NOINLINE uniqueCounterRef #-}
uniqueCounterRef :: IORef Int
uniqueCounterRef = unsafePerformIO (newIORef 0)
createUniqueIndex :: (String -> Int -> a) -> String -> a
createUniqueIndex mk n = unsafePerformIO $ do
atomicModifyIORef uniqueCounterRef (\x -> (x+1,()))
i <- readIORef uniqueCounterRef
return $ mk n i
-------------------------------------------------------------------------------
-- What is wire.
data WireE =
-- wire identifier. Is wire should be generated without index, does wire have name and what it is and unique index.
WIdent Bool (Maybe String) Int
| WConst Integer
| WConcat [SizedWireE]
-- for most operations size of result is equal to sizes of arguments.
-- for multiplication
| WBin BinOp SizedWireE SizedWireE
| WUn UnOp SizedWireE
| WSlice SizedWireE Int
| WSelect SizedWireE SizedWireE SizedWireE
deriving (Eq, Ord, Show)
data BinOp =
Plus
| Minus
| Mul
| ShiftRL
| ShiftRA
| ShiftL
| And
| Or
| Xor
| Equal
| NEqual
deriving (Eq, Ord, Show)
data UnOp =
Negate
| Complement
| Extend ExtOp
deriving (Eq, Ord, Show)
data ExtOp =
ExtZero | ExtSign | ExtOne
deriving (Eq, Ord, Show)
type SizedWireE = (Int, WireE)
data Wire clk ty where
Wire :: SizedWireE -> Wire clk ty
instance Show (Wire c ty) where
show (Wire sw) = show sw
data HDL = VHDL | Verilog
deriving (Prelude.Eq, Prelude.Ord, Show)
exprFlatten :: SizedWireE -> NLM clocks SizedWireE
exprFlatten sizedExpr@(size, expr) = case expr of
WIdent _ _ _ -> return sizedExpr
WConst _ -> return sizedExpr
WConcat concats -> do
concats' <- mapM exprFlatten concats
assign $ WConcat concats
WBin op a b -> liftM2 (WBin op) (exprFlatten a) (exprFlatten b) >>= assign
WUn op a -> liftM (WUn op) (exprFlatten a) >>= assign
WSlice e ofs -> liftM (flip WSlice ofs) (exprFlatten e) >>= assign
WSelect c t f -> liftM3 WSelect (exprFlatten c) (exprFlatten t) (exprFlatten f) >>= assign
where
assign expr = do
t <- mkIdentE Nothing
addNetlistOperation $ Assign (size, t) (size, expr)
return (size, t)
mkWireFromE :: BitRepr a => WireE -> Wire c a
mkWireFromE e = r
where
r = Wire (size, e)
size = wireBusSize r
{- DEL ME!!!
class BitRepr (WireOpType op) => WireOp op where
type WireOpType op
-- |Transformation to HDL.
opToHDL :: BitRepr (WireOpType op) => HDL -> op -> String
-- |Flattening transformation.
opFlatten :: op -> NLM clocks op
opType :: op -> WireOpType op
opType op = undefined
opTypeSize :: op -> Int
opTypeSize op = bitVectorSize (opType op)
-}
identName :: Bool -> Maybe String -> Int -> String
identName special name ix = case name of
Nothing -> "generated_hhdl_name_"++show ix
Just n
| special -> n
| otherwise -> n ++"_"++show ix
opToHDL :: HDL -> SizedWireE -> String
opToHDL hdl expr = exprHDL expr
where
bits n b
| n < 1 = ""
| otherwise = bits (n-1) (div b 2) ++ show (mod b 2)
exprHDL (size, e) = case e of
WIdent special name ix -> identName special name ix
WConst i -> case hdl of
Verilog -> error "wconst!"
VHDL -> (if size < 2 then ('\'':) . (++"'") . init . tail else id) $ show $ bits size i
WConcat exprs -> case hdl of
Verilog -> concat ["{", intercalate ", " $ map exprHDL exprs, "}"]
WBin op a b
| specialCase -> concat [funcName, "(", exprHDL a,", ", exprHDL b, ")"]
| otherwise -> unwords [exprHDL a, hdlOp, exprHDL b]
where
specialCase = (hdl, op) `elem` [(VHDL, Equal), (VHDL, NEqual)]
funcName = case op of
Equal -> "bit_equality"
NEqual -> "bit_inequality"
op -> error $ "internal error: not funcname for "++show op
hdlOp = case (hdl, op) of
(_,Plus) -> "+"
(_,Minus) -> "-"
(_,Mul) -> "*"
(VHDL, Or) -> "or"
(Verilog, Or) -> "|"
(VHDL, And) -> "and"
(Verilog, And) -> "&"
(VHDL, Equal) -> "="
(Verilog, Equal) -> "=="
(VHDL, NEqual) -> "/="
(Verilog, NEqual) -> "!="
e -> error $ "unhandled binary op "++show e
WUn op e -> case (hdl, op) of
(Verilog, Complement) -> "~"++exprHDL e
(VHDL, Complement) -> unwords ["not", exprHDL e]
(_, Negate) -> "-"++exprHDL e
(VHDL, Extend ExtZero) -> concat ["extend_zero(",exprHDL e, ", ", show size,")"]
(VHDL, Extend ExtSign) -> concat ["extend_sign(",exprHDL e, ", ", show size,")"]
(VHDL, Extend ExtOne) -> concat ["extend_one(",exprHDL e, ", ", show size,")"]
e -> error $ "unhandled extension combination "++show e
WSlice e@(len,_) from -> case hdl of
Verilog
| size < 2 -> concat [exprHDL e, "(",show from,")"]
| otherwise -> concat [exprHDL e, "[",show (from+size-1),":", show from,"]"]
VHDL
| size < 2 -> concat [exprHDL e, "(",show from,")"]
| otherwise -> concat [exprHDL e, "(",show (from+size-1)," downto ", show from,")"]
WSelect c t e -> case hdl of
Verilog -> unwords [exprHDL c,"?", exprHDL t,":", exprHDL e]
VHDL -> concat ["select_func(",exprHDL c,", ", exprHDL t,", ", exprHDL e,")"]
e -> error $ "Unknown expression "++show e
data SimpleOps c ty where
OpConst :: (BitRepr ty, Show ty) => ty -> SimpleOps c ty
OpSimpleBin :: (BitRepr res, BitRepr arg) =>
Wire c arg -> [(HDL,String)] -> Wire c arg -> SimpleOps c res
OpSimpleUn :: (BitRepr res, BitRepr arg) => [(HDL,String)] -> Wire c arg -> SimpleOps c res
toBits :: BitRepr ty => ty -> String
toBits x
| n > 1 = show bits
| otherwise = show $ head bits
where
i = toBitVector x
n = bitVectorSize x
bits = reverse $ concatMap show $ take n $ map snd $ tail $
iterate ((`Prelude.divMod` 2) . fst) (i,0)
constant :: BitRepr ty => ty -> Wire c ty
constant x = Wire (bitVectorSize x, WConst $ toBitVector x)
simpleBinAnyHDL a op b = (fst a, WBin op a b)
instance (BitRepr ty, Arith ty) => Arith (Wire c ty) where
fromIntegerLit l = constant $ fromBitVector l
Wire a .+ Wire b = Wire $ simpleBinAnyHDL a Plus b
Wire a .- Wire b = Wire $ simpleBinAnyHDL a Minus b
Wire a .* Wire b = Wire $ simpleBinAnyHDL a Mul b
instance Boolean (Wire c Bool) where
boolNot (Wire x) = mkWireFromE $ WUn Complement x
Wire a .&& Wire b = Wire $ simpleBinAnyHDL a And b
Wire a .|| Wire b = Wire $ simpleBinAnyHDL a Or b
type family WList c ts
type instance WList c Nil = Nil
type instance WList c (t :. ts) = Wire c t :. WList c ts
class WiresList a where
type WireNamesList a
mkWireList :: Maybe (WireNamesList a) -> NLM clocks a
copyWireList :: Maybe (WireNamesList a) -> a -> NLM clocks a
instance WiresList Nil where
type WireNamesList Nil = Nil
mkWireList _ = return Nil
copyWireList _ _ = return Nil
instance (BitRepr a, WiresList as) => WiresList (Wire c a :. as) where
type WireNamesList (Wire c a :. as) = String :. WireNamesList as
mkWireList names = do
let (n,ns) = case names of
Just (n :. ns) -> (Just n, Just ns)
Nothing -> (Nothing, Nothing)
a <- mkWire n
as <- mkWireList ns
return (a :. as)
copyWireList names ~(w :. ws) = do
let (n,ns) = case names of
Just (n :. ns) -> (Just n, Just ns)
Nothing -> (Nothing, Nothing)
w <- assignWithForcedCopy n w
ws <- copyWireList ns ws
return (w :. ws)
class RegisterWiresList a clocks where
type RegisterDefault a
registerWiresList :: RegisterDefault a -> a -> NLM clocks a
instance RegisterWiresList Nil clocks where
type RegisterDefault Nil = Nil
registerWiresList _ _ = return Nil
instance (Show a, BitRepr a, ClockAllowed c clocks, RegisterWiresList as clocks) => RegisterWiresList (Wire c a :. as) clocks where
type RegisterDefault (Wire c a :. as) = a :. RegisterDefault as
registerWiresList ~(a :. as) ~(w :. ws) = do
w' <- register a w
ws' <- registerWiresList as ws
return $ w' :. ws'
data SignalKind = BitSignal | BusSignal Int deriving Show
signalName :: SizedWireE -> String
signalName = fst . signalNameKind
signalKind :: SizedWireE -> SignalKind
signalKind = snd . signalNameKind
wireBusSize :: BitRepr a => Wire c a -> Int
wireBusSize wire = bitVectorSize (wireType wire)
where
wireType :: BitRepr a => Wire c a -> a
wireType _ = undefined
wireOpBusSize :: (BitRepr ty) => Wire c ty -> Int
wireOpBusSize op = bitVectorSize (projectType op)
where
projectType :: Wire c ty -> ty
projectType = undefined
signalNameKind :: SizedWireE -> (String, SignalKind)
signalNameKind (size, e) = (name,kind)
where
kind = if size == 1 then BitSignal else BusSignal size
name = case e of
WIdent special n i -> identName special n i
signalsWires :: [SizedWireE] -> [(String, SignalKind)]
signalsWires = map signalNameKind
class HDLOp op where
opArgs :: WiresList as => op clk ty -> as
opSize :: BitRepr ty => op clk ty -> Int
class (Typeable c, Typeable (ClkReset c)) => Clock c where
type ClkReset c
-- |Provide construction of clock value to carry around.
clockValue :: c
-- |Reset sensitivity.
clockResetPositive :: c -> Bool
-- |Front sensitivity.
clockFrontEdge :: c -> Bool
changeDotsToUnderscores :: Typeable t => t -> String
changeDotsToUnderscores = map (\c -> if c == '.' then '_' else c) . show . typeOf
clockName :: Clock c => c -> String
clockName c = changeDotsToUnderscores c
clockResetName :: Clock c => c -> String
clockResetName c = changeDotsToUnderscores $ clockReset c
where
clockReset :: Clock c => c -> ClkReset c
clockReset _ = undefined
class ClockList l where
clockListValue :: l
clockListClocks :: l -> [String]
clockListResets :: l -> [String]
instance ClockList Nil where
clockListValue = Nil
clockListClocks = const []
clockListResets = const []
instance (ClockList t, Clock h) => ClockList (h :. t) where
clockListValue = clockValue :. clockListValue
clockListClocks (c :. cs) = nub $ clockName c : clockListClocks cs
clockListResets (c :. cs) = nub $ clockResetName c : clockListResets cs
class (Clock c, ClockList cs) => ClockAllowed c cs
instance (Clock c, Clock c1, ClockAllowed c cs) => ClockAllowed c (c1 :. cs)
instance (Clock c, ClockList (c :. cs)) => ClockAllowed c (c :. cs)
class (ClockList clockSubset, ClockList clockSet) => ClockSubset clockSubset clockSet
instance ClockList clockSet => ClockSubset Nil clockSet
instance (Clock c, ClockAllowed c clockSet, ClockSubset css clockSet, ClockList clockSet) => ClockSubset (c :. css) clockSet
wireClock :: Clock c => Wire c a -> c
wireClock w = clockValue
-- |Basic netlist operations.
data NetlistOp domain where
-- Latching wires. First comes default
Register :: (ClockAllowed c clocks, BitRepr a, Show a) =>
c -> a -> SizedWireE -> SizedWireE -> NetlistOp clocks
-- Assign dest what
-- dest <= what;
Assign :: SizedWireE -> SizedWireE -> NetlistOp clocks
-- Instance ent
-- entity ent port map (...);
Instance :: Instantiable entity =>
entity -> [SizedWireE] -> [SizedWireE] -> NetlistOp clocks
-- |Netlist type.
data Netlist clocks = Netlist { netlistOperations :: [NetlistOp clocks] }
-- |State of netlist construction monad.
data NLMS domain = NLMS {
nlmsNetlist :: Netlist domain
, nlmsCounter :: Int
}
emptyNLMS :: NLMS clocked
emptyNLMS = NLMS (Netlist []) 0
type NLM clocked a = State (NLMS clocked) a
mkIdentE :: Maybe String -> NLM clocked WireE
mkIdentE name = do
n <- liftM nlmsCounter get
modify $ \nlms -> nlms { nlmsCounter = n+1 }
return $ WIdent False name n
mkWire :: BitRepr a => Maybe String -> NLM clocked (Wire c a)
mkWire name = do
liftM mkWireFromE $ mkIdentE name
tempWire :: BitRepr a => NLM clocked (Wire c a)
tempWire = mkWire Nothing
class HDLSignals a where
toSizedWireEList :: a -> [SizedWireE]
instance HDLSignals Nil where
toSizedWireEList _ = []
instance HDLSignals as => HDLSignals (Wire c ty :. as) where
toSizedWireEList (Wire se :. as) = se : toSizedWireEList as
class (ClockList (EntityClocks entity)
, HDLSignals (EntityIns entity)
, HDLSignals (EntityOuts entity)
, GenHDL entity) => Instantiable entity where
type EntityClocks entity
type EntityIns entity
type EntityOuts entity
getInputsOuputsClocks :: entity
-> (EntityIns entity, EntityOuts entity, EntityClocks entity)
data Comb ins outs where
Comb :: (HDLSignals ins, HDLSignals outs) =>
String -> Int -> ins -> outs -> Netlist Nil -> Comb ins outs
instance (HDLSignals ins
, HDLSignals outs
, GenHDL (Comb ins outs)) => Instantiable (Comb ins outs) where
type EntityClocks (Comb ins outs) = Nil
type EntityIns (Comb ins outs) = ins
type EntityOuts (Comb ins outs) = outs
getInputsOuputsClocks (Comb _ _ ins outs _) = (ins, outs, Nil)
runNetlistCreation :: (WiresList ins, WiresList outs, HDLSignals ins, HDLSignals outs)
=> Maybe (WireNamesList ins, WireNamesList outs)
-> (ins -> outs -> Netlist domain -> a) -> (ins -> NLM domain outs) -> a
runNetlistCreation names q f = mk $ do
ins <- mkWireList (fmap fst names)
outs <- f ins
outs <- copyWireList (fmap snd names) outs
return (ins,outs)
where
mk act = (\((ins,outs),nlms) -> q ins outs (nlmsNetlist nlms)) $
runState act emptyNLMS
-- |Create a combinational circut with named inputs and outputs from netlist description.
mkCombNamed :: (HDLSignals ins, HDLSignals outs, WiresList ins, WiresList outs)
=> Maybe (WireNamesList ins, WireNamesList outs) -> String -> (ins -> NLM Nil outs) -> Comb ins outs
mkCombNamed names n f = runNetlistCreation names (createUniqueIndex Comb n) f
-- |Create a combinational circut anonymous inputs and outputs from netlist description.
mkComb :: (HDLSignals ins, HDLSignals outs, WiresList ins, WiresList outs)
=> String -> (ins -> NLM Nil outs) -> Comb ins outs
mkComb n f = mkCombNamed Nothing n f
-- |Create a combinational circuit from pure function.
-- You can easily shoot your foot here by creating cyclic expressions like
-- 'f a = y where { x = a+y; y = x-a}.
-- Use with care.
mkCombPure :: (HDLSignals ins, HDLSignals outs, WiresList ins, WiresList outs) => String -> (ins -> outs) -> Comb ins outs
mkCombPure n f = mkComb n (\ins -> return (f ins))
data Clocked clks ins outs where
Clocked :: (HDLSignals ins, HDLSignals outs, ClockList clks) =>
clks -> String -> Int -> ins -> outs -> Netlist clks -> Clocked clks ins outs
instance (ClockList clks
, HDLSignals ins
, HDLSignals outs
, GenHDL (Clocked clks ins outs)) => Instantiable (Clocked clks ins outs) where
type EntityClocks (Clocked clks ins outs) = clks
type EntityIns (Clocked clks ins outs) = ins
type EntityOuts (Clocked clks ins outs) = outs
getInputsOuputsClocks (Clocked clks _ _ ins outs _) = (ins, outs, clks)
mkClockedNamed :: (ClockList clks, WiresList ins, WiresList outs, HDLSignals ins, HDLSignals outs)
=> Maybe (WireNamesList ins, WireNamesList outs) -> String
-> (ins -> NLM clks outs) -> Clocked clks ins outs
mkClockedNamed names n f = runNetlistCreation names (createUniqueIndex (Clocked clockListValue) n) f
mkClocked :: (ClockList clks, WiresList ins, WiresList outs, HDLSignals ins, HDLSignals outs)
=> String -> (ins -> NLM clks outs) -> Clocked clks ins outs
mkClocked n f = mkClockedNamed Nothing n f
data Mealy clk ins outs where
Mealy :: (HDLSignals ins, HDLSignals outs, Clock clk) =>
clk -> String -> Int -> ins -> outs -> Netlist (clk :. Nil) -> Mealy clk ins outs
instance (Clock clk
, HDLSignals ins
, HDLSignals outs
, GenHDL (Mealy clk ins outs)) => Instantiable (Mealy clk ins outs) where
type EntityClocks (Mealy clk ins outs) = clk :. Nil
type EntityIns (Mealy clk ins outs) = ins
type EntityOuts (Mealy clk ins outs) = outs
getInputsOuputsClocks (Mealy clk _ _ ins outs _) = (ins, outs, clk :. Nil)
mkMealyNamed :: (Clock clk, WiresList state, HDLSignals state, WiresList ins, WiresList outs, HDLSignals ins, HDLSignals outs, RegisterWiresList state (clk :. Nil))
=> Maybe (WireNamesList ins, WireNamesList outs)
-> RegisterDefault state -> String -> (state -> ins -> NLM (clk :. Nil) (state, outs))
-> Mealy clk ins outs
mkMealyNamed names defs n f = runNetlistCreation names (createUniqueIndex (Mealy clockValue) n) action
where
action ins = do
rec
state <- registerWiresList defs nextState
~(nextState, outs) <- f state ins
return outs
mkMealy:: (Clock clk, WiresList state, HDLSignals state, WiresList ins, WiresList outs, HDLSignals ins, HDLSignals outs, RegisterWiresList state (clk :. Nil))
=> RegisterDefault state -> String -> (state -> ins -> NLM (clk :. Nil) (state, outs))
-> Mealy clk ins outs
mkMealy defs n f = mkMealyNamed Nothing defs n f
-------------------------------------------------------------------------------
-- BitRepr instances.
instance BitRepr Int where
type BitVectorSize Int = $(tySize 32)
toBitVector x = fromIntegral x
fromBitVector x = fromIntegral x
bitVectorSize x = 32
instance BitRepr Word8 where
type BitVectorSize Word8 = $(tySize 8)
toBitVector x = fromIntegral x
fromBitVector x = fromIntegral x
bitVectorSize x = 8
instance BitRepr Nil where
type BitVectorSize Nil = $(tySize 0)
toBitVector x = 0
fromBitVector x = Nil
bitVectorSize x = 0
instance (BitRepr a, BitRepr as
, Nat (Plus (BitVectorSize a) (BitVectorSize as)))
=> BitRepr (a :. as) where
type BitVectorSize (a :. as) = Plus (BitVectorSize a) (BitVectorSize as)
toBitVector (a :. as) = B.shiftL (toBitVector a) (bitVectorSize as)
B..|. toBitVector as
fromBitVector x = a :. as
where
mask :: BitRepr a => a -> Integer
mask x = B.shiftL (1 :: Integer) (bitVectorSize x) - 1
ys = x B..&. mask as
y = B.shiftR x (bitVectorSize as) B..&. mask a
a = fromBitVector y
as = fromBitVector ys
bitVectorSize (a :. as) = bitVectorSize a + bitVectorSize as
instance BitRepr () where
type BitVectorSize () = $(tySize 0)
toBitVector = const 0
fromBitVector = const ()
-------------------------------------------------------------------------------
-- Dumping HDL.
data HDLGenState = HDLGenState {
-- errors, if we encounter any.
hdlgErrors :: [String]
-- Mapping from entities to their "real" names.
, hdlgGeneratedEntities :: Map.Map (String, Int) String
-- how deep we recurred?
, hdlgRecursionLevel :: Int
-- lines of generated text. In reverse order.
, hdlgTextLines :: [String]
-- nesting level.
, hdlgNestLevel :: Int
-- what kind of language we generate.
, hdlgLanguage :: HDL
-- set of defined names.
, hdlgDefinedNames :: Set.Set String
}
deriving (Prelude.Eq, Prelude.Ord, Show)
type HDLGen a = State HDLGenState a
emptyHDLGenState hdl = HDLGenState {
hdlgErrors = []
, hdlgGeneratedEntities = Map.empty
, hdlgRecursionLevel = 0
, hdlgTextLines = []
, hdlgNestLevel = 0
, hdlgLanguage = hdl
, hdlgDefinedNames = Set.empty
}
runHDLGeneration :: GenHDL a => HDL -> a -> (String, [String])
runHDLGeneration hdl entity = (text, errors)
where
errors = hdlgErrors state
text = unlines $ reverse $ hdlgTextLines state
(_,state) = runState (generateHDL entity) (emptyHDLGenState hdl)
generateLine :: String -> HDLGen ()
generateLine s = modify $ \hdlg -> hdlg {
hdlgTextLines = (replicate (hdlgNestLevel hdlg) ' '++s) : hdlgTextLines hdlg
}
generateEmptyLines :: Int -> HDLGen ()
generateEmptyLines n = modify $ \hdlg -> hdlg {
hdlgTextLines = (replicate n "") ++ hdlgTextLines hdlg
}
generateNest :: HDLGen a -> HDLGen a
generateNest act = do
nest <- liftM hdlgNestLevel get
modify $ \hdlg -> hdlg { hdlgNestLevel = nest + 4 }
x <- act
modify $ \hdlg -> hdlg { hdlgNestLevel = nest }
return x
generateDashes :: HDLGen ()
generateDashes = modify $ \hdlg -> hdlg {
hdlgTextLines = dashesLine (hdlgLanguage hdlg) (hdlgNestLevel hdlg)
: hdlgTextLines hdlg
}
where
dashesLine hdl n = concat [replicate n ' ',prefix hdl, replicate (79-n-2) '-']
prefix hdl = case hdl of
VHDL -> "--"
Verilog -> "//"
generateError :: String -> HDLGen ()
generateError err = modify $ \hdlg -> hdlg { hdlgErrors = err : hdlgErrors hdlg}
generateComment :: String -> HDLGen ()
generateComment c = do
hdl <- liftM hdlgLanguage get
let commentPrefix = case hdl of
VHDL -> "--"
Verilog -> "//"
generateLine $ unwords [commentPrefix,c]
generateDashesComment :: String -> HDLGen ()
generateDashesComment c = do
generateDashes
generateComment c
generateDefineName :: String -> HDLGen ()
generateDefineName name = modify $ \hdlg -> hdlg {
hdlgDefinedNames = Set.insert name $ hdlgDefinedNames hdlg
}
generateFilterDefined :: [a] -> (a -> String) -> HDLGen [a]
generateFilterDefined things nameProjection = do
defined <- liftM hdlgDefinedNames get
let things' = filter (not . flip Set.member defined . nameProjection) things
mapM (generateDefineName . nameProjection) things'
return things'
class GenHDL a where
generateHDL :: a -> HDLGen ()
names :: HDLSignals s => s -> [String]
names s = map fst $ signalsWires $ toSizedWireEList s
entityPortsList :: HDLSignals s => String -> s -> ([String],[(String, String)])
entityPortsList dir signals' = (
map fst wiresKinds
,map (\(name,kind) -> (name,unwords [name,":",dir,vhdlType kind])) wiresKinds)
where
signals = toSizedWireEList signals'
wiresKinds = signalsWires signals
vhdlType BitSignal = "bit"
vhdlType (BusSignal width) =
"unsigned ("++show (width-1)++" downto 0)"
generateHDLForEntity :: (HDLSignals ins, HDLSignals outs, ClockList clocks) =>
String -> Int -> ins -> outs -> clocks -> Netlist domain -> HDLGen ()
generateHDLForEntity name index ins outs clocks netlist = do
hdl <- liftM hdlgLanguage get
n <- liftM (Map.lookup key . hdlgGeneratedEntities) get
case n of
Nothing -> do
ourName <- registerOurEntity
mapM_ subEntity $ netlistOperations netlist
case hdl of
VHDL -> vhdlText ourName
Verilog -> verilogText ourName
Just _ -> return ()
where
key = (name, index)
registerOurEntity = do
names <- liftM (Set.fromList . Map.elems . hdlgGeneratedEntities) get
let newNames = map (name++) $
map ('_':) $ map show [(1::Int)..]
let ourName = head $ filter (not . (`Set.member` names)) newNames
modify $ \hdlgs -> hdlgs { hdlgGeneratedEntities = Map.insert key ourName $ hdlgGeneratedEntities hdlgs }
return ourName
subEntity :: NetlistOp domain -> HDLGen ()
subEntity (Instance entity ins outs) = do
generateHDL entity
subEntity _ = return ()
generateEntityClocksResets clks = map addTypeDir $ clocks ++ resets
where
addTypeDir name = name ++ ": in std_logic"
clocks = clockListClocks clks
resets = clockListResets clks
generateVHDLDeclarations ops' = do
ops <- generateFilterDefined ops' fst
forM ops $ \(name, kind) -> do
let ty = case kind of
BitSignal -> "bit"
BusSignal n -> "unsigned ("++show (n-1)++" downto 0)"
generateLine $ concat ["signal ", name, " : ", ty,";"]
return ()
declareOperationSignals :: NetlistOp domain -> HDLGen ()
declareOperationSignals op = generateVHDLDeclarations $ case op of
Register c _ wa wb -> signalsWires [wa]
Assign wa op -> signalsWires [wa]
Instance entity ins outs -> signalsWires outs
vhdlOperation :: NetlistOp domain -> HDLGen ()
vhdlOperation op = case op of
Register c def wa wb -> do
let cn = clockName c
let edge = (if clockFrontEdge c then "rising_edge" else "falling_edge")
++"("++cn++")"
let rn = clockResetName c
let resetFunc =
rn ++ " = "
++ (if clockResetPositive c then "'1'" else "'0'")
generateLine $ "process ("++cn++", "++rn++") is"
generateLine $ "begin"
generateNest $ do
generateLine $ unwords ["if",resetFunc, "then"]
generateNest $ vhdlOperation (Assign wa (bitVectorSize def, WConst $ toBitVector def))
generateLine $ unwords ["elsif",edge, "then"]
generateNest $ vhdlOperation (Assign wa wb)
generateLine "end if;"
generateLine $ "end process;"
Assign wa op -> do
generateLine $ concat
[signalName wa, " <= "
,opToHDL VHDL op, ";"]
Instance entity ins outs -> do
let (eins, eouts, eclks) = getInputsOuputsClocks entity
let insNames = map fst $ signalsWires ins
let outsNames = map fst $ signalsWires outs
let einsNames = map fst $ signalsWires $ toSizedWireEList eins
let eoutsNames = map fst $ signalsWires $ toSizedWireEList eouts
let clocks = nub $ clockListClocks eclks
let resets = nub $ clockListResets eclks
let connect a b = a ++" => " ++ b
let allNames = zipWith connect insNames einsNames
++ zipWith connect outsNames eoutsNames
++ map (\c -> connect c c) clocks
++ map (\c -> connect c c) resets
let withCommas = zipWith (++) (" ":repeat ", ") allNames
generateLine "entity ("
generateNest $ mapM generateLine withCommas
generateLine ");"
vhdlText name = do
generateEmptyLines 2
generateDashesComment $ "Entity declaration and architecture for "++name++"."
generateEmptyLines 1
generateLine "library ieee;"
generateLine "use ieee.std_logic_1164.all;"
generateLine "use ieee.numeric_bit.all;"
generateEmptyLines 1
generateLine $ "entity "++name++" is"
generateNest $ do
generateLine "port ("
let (inputsNames,inputs) =
entityPortsList "in" ins
let (outputsNames, outputs) =
entityPortsList "out" outs
let clockResets = generateEntityClocksResets clocks
let inouts = inputs ++ outputs
let allSignals = (map snd inouts) ++ clockResets
let signals = reverse $
zipWith (++) (reverse allSignals) ("" : repeat ";")
mapM generateDefineName $ map fst inouts
generateNest $ do
mapM generateLine signals
generateLine ");"
return $ inputsNames ++ outputsNames
generateLine $ "end entity "++name++";"
generateEmptyLines 2
generateLine $ "architecture hhdl_generated of "++name++" is"
generateNest $ do
addSupportFunctions
mapM declareOperationSignals $ netlistOperations netlist
generateLine $ "begin"
generateNest $ do
mapM vhdlOperation $ netlistOperations netlist
generateLine $ "end architecture hhdl_generated;"
return ()
verilogText name = do
generateLine $ "Verilog text for entity "++name
addSupportFunctions = mapM generateLine [
replicate 60 '-'
, "-- Supporting functions."
, ""
, "pure function select_func(s : in bit; t, f : in bit) return bit is"
, "begin"
, " if s = '1' then"
, " return t;"
, " else"
, " return f;"
, " end if;"
, "end function select_func;"
, ""
, "pure function select_func(s : in bit; t, f : in unsigned) return unsigned is"
, "begin"
, " if s = '1' then"
, " return t;"
, " else"
, " return f;"
, " end if;"
, "end function select_func;"
, ""
, "pure function bit_equality(a, b : in bit) return bit is"
, "begin"
, " if a = b then"
, " return '1';"
, " else"
, " return '0';"
, " end if;"
, "end function bit_equality;"
, ""
, "pure function bit_inequality(a, b : in unsigned) return bit is"
, "begin"
, " if a = b then"
, " return '0';"
, " else"
, " return '1';"
, " end if;"
, "end function bit_inequality;"
, ""
]
instance GenHDL (Comb ins outs) where
generateHDL (Comb name index ins outs netlist) = do
generateHDLForEntity name index ins outs Nil netlist
instance GenHDL (Clocked cs ins outs) where
generateHDL (Clocked clocks name index ins outs netlist) = do
generateHDLForEntity name index ins outs clocks netlist
instance GenHDL (Mealy c ins outs) where
generateHDL (Mealy c name index ins outs netlist) = do
generateHDLForEntity name index ins outs (c :. Nil) netlist
writeHDLText :: GenHDL a => HDL -> a -> (String -> IO ()) -> IO ()
writeHDLText hdl entity write = do
let (text, errors) = runHDLGeneration hdl entity
write text
case errors of
[] -> return ()
errs -> do
putStrLn $ "\n\n\nErrors:"
mapM putStrLn errs
putStrLn "------------------"
putStrLn $ "Total " ++ show (length errs) ++ " errors in HDL generation."
-------------------------------------------------------------------------------
-- Bit vectors.
data BV size = BV Integer
instance Nat size => BitRepr (BV size) where
type BitVectorSize (BV size) = size
toBitVector (BV i) = i
fromBitVector i = r
where
r = BV (i B..&. bitMask r)
instance Nat size => Num (BV size) where
fromInteger x = BV x
BV a + BV b = BV $ a + b
BV a - BV b = BV $ a - b
BV a * BV b = BV $ a * b
abs = error "no abs for BV"
signum = error "no signum for BV"
instance Nat size => Eq (BV size) where
BV a == BV b = a == b
BV a /= BV b = a /= b
instance Show (BV size) where
showsPrec n (BV i) = (concat [o,Text.Printf.printf "BV 0x%x" i,c]++)
where
(o,c)
| n > 10 = ("(",")")
| otherwise = ("","")
instance Nat size => Equal (BV size) where
type EqResult (BV size) = Bool
a .== b = toBitVector a .== toBitVector b
a ./= b = toBitVector a ./= toBitVector b
_toSelBusSizeBitVector :: AlgTypeBitEnc a => a -> BV (SelectorBusSize a)
_toSelBusSizeBitVector = undefined
_toSelBusSizeBitVectorWireExpr :: AlgTypeBitEnc a => Wire c a -> BV (SelectorBusSize a)
_toSelBusSizeBitVectorWireExpr = undefined
_toArgsBusSizeBitVector :: AlgTypeBitEnc a => Wire c a -> Wire c (BV (ArgsBusSize a))
_toArgsBusSizeBitVector = undefined
-------------------------------------------------------------------------------
-- Netlist operations.
addNetlistOperation op =
modify $ \nlms -> nlms {
nlmsNetlist = Netlist $ op : netlistOperations (nlmsNetlist nlms)
}
register :: (ClockAllowed c clocks, BitRepr a, Show a) => a -> Wire c a -> NLM clocks (Wire c a)
register resetValue inp@(~(Wire computedValue)) = do
w@(~(Wire se)) <- tempWire
modify $ \nlms -> nlms {
nlmsNetlist = Netlist (Register (wireClock inp) resetValue se computedValue : netlistOperations (nlmsNetlist nlms))
}
return w
instantiate :: (Instantiable entity, ClockSubset (EntityClocks entity) clocks
, WiresList (EntityIns entity), WiresList (EntityOuts entity), HDLSignals (EntityIns entity), HDLSignals (EntityOuts entity)) =>
entity -> EntityIns entity -> NLM clocks (EntityOuts entity)
instantiate entity ins = do
outs <- mkWireList Nothing
addNetlistOperation $ Instance entity (toSizedWireEList ins) (toSizedWireEList outs)
return outs
assignWire :: (BitRepr ty) => Wire c ty -> NLM registers (Wire c ty)
assignWire what = do
assignFlattened what
assignWithForcedCopy n ~(Wire se) = do
w@(~(Wire t)) <- mkWire n
addNetlistOperation $ Assign t se
return w
assignFlattened :: (BitRepr ty) => Wire c ty -> NLM registers (Wire c ty)
assignFlattened w@(Wire (sz, WIdent _ _ _)) = return w
assignFlattened w@(Wire e) = do
e <- exprFlatten e
assignWithForcedCopy Nothing (Wire e)
anyExtend :: (Nat src, Nat dest) => Maybe WireE -> Wire c (BV src) -> Wire c (BV dest)
anyExtend mbExt src@(Wire what@(sizeWhat, _))
| sizeWhat > sizeTo = mkWireFromE $ WSlice what 0
| sizeWhat == sizeTo = Wire what
| otherwise = res
where
(Wire (sizeTo, _)) = res
ext = case mbExt of
Nothing -> WSlice what (sizeWhat-1)
Just e -> e
extSize = sizeTo - sizeWhat
extension = (extSize, WConcat (replicate extSize (1,ext)))
res = mkWireFromE $ WConcat [extension, what]
extendZero :: (Nat src, Nat dest) => Wire c (BV src) -> Wire c (BV dest)
extendZero what = anyExtend (Just $ WConst 0) what
extendOnes :: (Nat src, Nat dest) => Wire c (BV src) -> Wire c (BV dest)
extendOnes what = anyExtend (Just $ WConst 1) what
extendSign :: (Nat src, Nat dest) => Wire c (BV src) -> Wire c (BV dest)
extendSign what = anyExtend Nothing what
castWires :: (BitRepr src, BitRepr res, BitVectorSize src ~ BitVectorSize res) =>
Wire c src -> Wire c res
castWires (Wire what) = Wire what
_runPureNetlist :: NLM Nil a -> NLM clocks a
_runPureNetlist action = do
s <- get
let (a,s') = runState action (copyNLMS s)
put (copyNLMSBack s' s)
return a
where
copyNLMS (NLMS (Netlist netlist) cntr) = NLMS (Netlist []) cntr
copyNLMSBack :: NLMS Nil -> NLMS clocks -> NLMS clocks
copyNLMSBack (NLMS (Netlist ops1) cntr) (NLMS (Netlist ops2) _)
= NLMS (Netlist $ copyOps ops1 ops2) cntr
copyOps :: [NetlistOp Nil] -> [NetlistOp clocks] -> [NetlistOp clocks]
copyOps [] ops2 = ops2
copyOps (Assign to what : ops1) ops2 = copyOps ops1 (ops2++[Assign to what])
copyOps (Instance ent ins outs : ops1) ops2 = copyOps ops1 (ops2++[Instance ent ins outs])
-------------------------------------------------------------------------------
-- Operations for expressions.
class BitRepr (WireOpListTypes a) => WireOpList a where
type WireOpListTypes a
-- type WireOpListClock a
opsToHDL :: HDL -> a -> [String]
instance WireOpList Nil where
type WireOpListTypes Nil = Nil
opsToHDL hdl = const []
instance (WireOpList xs, BitRepr x
, Nat (Plus (BitVectorSize x) (BitVectorSize (WireOpListTypes xs)))) => WireOpList (Wire c x :. xs) where
type WireOpListTypes (Wire c x :. xs) = x :. WireOpListTypes xs
opsToHDL hdl (Wire a :. as) = opToHDL hdl a : opsToHDL hdl as
type family SplitProjection c w
class BitRepr w => SplitWires w where
splitWires :: Wire c w -> SplitProjection c w
instance (BitRepr a, BitRepr b, Nat (Plus (BitVectorSize a) (BitVectorSize b)), Nat (BitVectorSize(a,b))) => BitRepr (a,b) where
type BitVectorSize (a,b) = Plus (BitVectorSize a) (BitVectorSize b)
toBitVector (x0,x1) = B.shiftL (toBitVector x0) (bitVectorSize x1) B..|. toBitVector x1
fromBitVector v = (x0,x1)
where
x1 = fromBitVector v
x0 = fromBitVector (B.shiftR v (bitVectorSize x1))
type instance SplitProjection c (a,b) = (Wire c a, Wire c b)
instance (BitRepr a, BitRepr b, BitRepr (a,b)) => SplitWires (a,b) where
splitWires (Wire wab) = (wa, wb)
where
wa = Wire (wireBusSize wa, WSlice wab $ wireBusSize wb)
wb = Wire (wireBusSize wb, WSlice wab 0)
splitWires2 :: (BitRepr a, BitRepr b, BitRepr (a,b)) => Wire clk (a,b) -> (Wire clk a, Wire clk b)
splitWires2 = splitWires
$(liftM concat $ forM [3..16] $ \n -> let
typeNames' = map (\i -> TH.mkName ("t_"++show i)) [1..n]
typeNames = map TH.VarT typeNames'
ty = foldl TH.AppT (TH.TupleT n) typeNames
clkN = TH.mkName "clk"
clk = TH.VarT clkN
wireTy ty = TH.ConT (TH.mkName "Wire") `TH.AppT` clk `TH.AppT` ty
wiresTy = foldl TH.AppT (TH.TupleT n) $ map wireTy typeNames
bitReprP ty = TH.ClassP (TH.mkName "BitRepr") [ty]
bitVectorSizeT ty = TH.ConT (TH.mkName "BitVectorSize") `TH.AppT` ty
commonCxt = map bitReprP typeNames
brCxt = TH.ClassP (TH.mkName "Nat") [bitVectorSizeT ty] : commonCxt
swCxt = bitReprP ty : commonCxt
argNames = map (\i -> TH.mkName ("x"++show i)) [1..n]
shiftNames = map (\i -> TH.mkName ("s"++show i)) [1..n]
argVars = map TH.VarE argNames
prevArgs = Prelude.scanr (:) [] argVars
sumWidths ws = foldr (\a b -> TH.InfixE (Just a) (TH.VarE $ TH.mkName "+") (Just b)) (TH.LitE $ TH.IntegerL 0) $ map (TH.AppE (TH.VarE (TH.mkName "wireBusSize"))) ws
def v widths = flip (TH.ValD (TH.VarP v)) [] $ TH.NormalB $
TH.VarE 'mkWireFromE `TH.AppE`
(TH.ConE 'WSlice
`TH.AppE` vV `TH.AppE` sumWidths widths)
defs = zipWith def argNames (tail prevArgs)
vN = TH.mkName "v"
vV = TH.VarE vN
bitVecSizeTy = TH.TySynInstD (TH.mkName "BitVectorSize") [ty] $
foldl1 (\a b -> TH.ConT (TH.mkName "Plus") `TH.AppT` a `TH.AppT` b) $ map bitVectorSizeT typeNames
defShift Nothing def arg = TH.ValD (TH.VarP def) (TH.NormalB $ TH.LitE $ TH.IntegerL 0) []
defShift (Just prev) def arg = TH.ValD (TH.VarP def) (TH.NormalB $ TH.InfixE (Just (TH.VarE prev)) (TH.VarE $ TH.mkName "+") (Just sz)) []
where
sz = TH.VarE (TH.mkName "bitVectorSize") `TH.AppE` TH.VarE arg
shiftDefs = Prelude.zipWith3 defShift (map Just (Prelude.init shiftNames) ++ [Nothing]) shiftNames argNames
toBVE = Prelude.foldr1 (\x y -> TH.InfixE (Just x) (TH.VarE $ TH.mkName "Data.Bits..|.") (Just y))
$ zipWith (\x s -> TH.VarE (TH.mkName "Data.Bits.shiftL")
`TH.AppE` (TH.VarE (TH.mkName "toBitVector") `TH.AppE` TH.VarE x)
`TH.AppE` TH.VarE s) argNames shiftNames
toBV = TH.FunD (TH.mkName "toBitVector")
[TH.Clause [TH.TupP $ map TH.VarP argNames] (TH.NormalB toBVE) shiftDefs]
fromBVEShiftDef x s pxs = [
TH.ValD (TH.VarP x) (TH.NormalB convertedX) []
, TH.ValD (TH.VarP s) (TH.NormalB shiftE) []
]
where
vx = TH.VarE x
convertedX = TH.VarE (TH.mkName "fromBitVector") `TH.AppE` shiftedV
shiftedV = TH.VarE (TH.mkName "Data.Bits.shiftR") `TH.AppE` vV `TH.AppE` TH.VarE s
shiftE = case pxs of
Nothing -> TH.LitE $ TH.IntegerL 0
Just (x,s) -> TH.InfixE
(Just $ TH.VarE (TH.mkName "bitVectorSize") `TH.AppE` TH.VarE x)
(TH.VarE $ TH.mkName "+")
(Just $ TH.VarE s)
shiftArgs as = map Just (tail as) ++ [Nothing]
fromBVEShiftDefs = concat $ zipWith3 fromBVEShiftDef argNames shiftNames (shiftArgs $ zip argNames shiftNames)
fromBVE = TH.TupE $ map TH.VarE argNames
fromBV = TH.FunD (TH.mkName "fromBitVector")
[TH.Clause [TH.VarP vN] (TH.NormalB fromBVE) fromBVEShiftDefs]
split = TH.FunD (TH.mkName "splitWires")
[TH.Clause [TH.ConP 'Wire [TH.VarP vN]] (TH.NormalB $ TH.TupE argVars) defs]
specializedSplitN = TH.mkName $ "splitWires"++show n
decls = [ TH.InstanceD swCxt (TH.ConT (TH.mkName "SplitWires") `TH.AppT` ty) [split]
, TH.TySynInstD (TH.mkName "SplitProjection") [clk,ty] wiresTy
, TH.InstanceD brCxt (TH.ConT (TH.mkName "BitRepr") `TH.AppT` ty) [bitVecSizeTy, toBV, fromBV]
, TH.SigD specializedSplitN $ TH.ForallT (map TH.PlainTV $ clkN : typeNames') brCxt $ (TH.AppT (TH.AppT TH.ArrowT $ wireTy ty) wiresTy)
, TH.FunD specializedSplitN [TH.Clause [] (TH.NormalB $ TH.VarE (TH.mkName "splitWires")) []]
]
in do
-- TH.runIO $ mapM (putStrLn . show . TH.ppr) decls
return decls
)
_castAlgTypeToPair :: (Nat (Plus (SelectorBusSize a) (ArgsBusSize a)), BitRepr a
, Plus (SelectorBusSize a) (ArgsBusSize a) ~ BitVectorSize a, AlgTypeBitEnc a) => Wire c a -> Wire c (BV (SelectorBusSize a), BV (ArgsBusSize a))
_castAlgTypeToPair w = castWires w
_splitAlgType :: (Plus (SelectorBusSize a) (ArgsBusSize a) ~ BitVectorSize a, Nat (Plus (SelectorBusSize a) (ArgsBusSize a)), AlgTypeBitEnc a, BitRepr a) => Wire c a -> (Wire c (BV (SelectorBusSize a)), Wire c (BV (ArgsBusSize a)))
_splitAlgType w = splitWires $ _castAlgTypeToPair w
_castArgsWires :: (Nat (ArgsBusSize a), AlgTypeBitEnc a, BitRepr a, BitRepr b) => Wire c a -> Wire c (BV (ArgsBusSize a)) -> Wire c b
_castArgsWires a w = r
where
r = castWires (extendZero w)
data Join c w where
Join :: (BitRepr a, BitRepr b) => Wire c a -> Wire c b -> Join c (a :. b)
infixr 5 &
(&) :: (BitRepr a, BitRepr b, Nat (Plus (BitVectorSize a) (BitVectorSize b))) => Wire c a -> Wire c b -> Wire c (a :. b)
(Wire a) & (Wire b) = Wire $ (fst a+fst b, WConcat [a,b])
instance (Eq w, EqResult w ~ Bool, BitRepr w) => Equal (Wire c w) where
type EqResult (Wire c w) = Wire c Bool
Wire a .== Wire b = mkWireFromE $ WBin Equal a b
Wire a ./= Wire b = mkWireFromE $ WBin NEqual a b
selectWires :: BitRepr a => Wire c Bool -> Wire c a -> Wire c a -> Wire c a
selectWires (Wire sel) (Wire true) (Wire false) = mkWireFromE $ WSelect sel true false
-------------------------------------------------------------------------------
-- Pattern matching.
-- We hardwire (pun intended) Wire(s) into Patterns because we can match
-- only on bit vectors. And those bit vectors get transferred by Wire(s).
type family ConcatPatList a b
type instance ConcatPatList a b = ConcatWiresList (a :. b)
--type instance ConcatPatList (x :. xs) ys = x :. (ConcatPatList xs ys)
class (WiresList (ConcatWiresList a)) => WiresListConcat a where
type ConcatWiresList a
concatWiresList :: a -> ConcatWiresList a
instance WiresListConcat Nil where
type ConcatWiresList Nil = Nil
concatWiresList Nil = Nil
instance WiresList as => WiresListConcat (Nil :. as) where
type ConcatWiresList (Nil :. as) = as
concatWiresList (Nil :. as) = as
instance (WiresListConcat (as :. bs), WiresList (a :. ConcatWiresList (as :. bs))) => WiresListConcat ((a :. as) :. bs) where
type ConcatWiresList ((a :. as) :. bs) = a :. ConcatWiresList (as :. bs)
concatWiresList ((a :. as) :. bs) = a :. concatWiresList (as :. bs)
data PatMatch v r where
PatMatch :: (Wire c v -> NLM Nil (Wire c Bool, Wire c result))
-> PatMatch (Wire c v) (Wire c result)
data Pattern w o where
Pattern :: {unPattern :: WiresList o => (Wire c w -> NLM Nil (o, Wire c Bool))} -> Pattern (Wire c w) o
match :: (ClockAllowed c registers, BitRepr v, BitRepr r) => Wire c v
-> [PatMatch (Wire c v) (Wire c r)] -> NLM registers (Wire c r)
match v ms = do
w <- assignWire v
_runPureNetlist $ reduceMatches w ms
where
reduceMatches :: BitRepr r => Wire c v -> [PatMatch (Wire c v) (Wire c r)] -> NLM Nil (Wire c r)
reduceMatches w [] = error "Empty list of pattern matches!"
reduceMatches w [PatMatch pm] = do
(_,r) <- pm w
return r
reduceMatches w pms = do
pms' <- reduceMatchesByTwo pms
reduceMatches w pms'
reduceMatchesByTwo :: BitRepr r => [PatMatch (Wire c v) (Wire c r)] -> NLM Nil [PatMatch (Wire c v) (Wire c r)]
reduceMatchesByTwo [] = return []
reduceMatchesByTwo [pm] = return [pm]
reduceMatchesByTwo (PatMatch pm1:PatMatch pm2:pms) = do
let pm = PatMatch $ \v -> do
(f1,r1) <- pm1 v
(f2,r2) <- pm2 v
fw <- assignWire $ f1 .|| f2
sw <- assignWire $ selectWires f1 r1 r2
return (fw, sw)
pms' <- reduceMatchesByTwo pms
return $ pm : pms'
infixl 8 -->
(-->) :: WiresList wires => Pattern (Wire c t) wires -> (wires -> NLM Nil (Wire c result))
-> PatMatch (Wire c t) (Wire c result)
(Pattern p) --> f = PatMatch $ \w -> do
(ws,flag) <- p w
r <- f ws
return (flag, r)
-- |Constant match.
pcst :: (Eq a, EqResult a ~ Bool, Eq (Wire c a), Show a, BitRepr a) => a -> Pattern (Wire c a) Nil
pcst c = Pattern $ \w -> return (Nil, w .== constant c)
pvar :: BitRepr a => Pattern (Wire c a) (Wire c a :. Nil)
pvar = Pattern $ \w -> return (w :. Nil, constant True)
pwild :: BitRepr a => Pattern (Wire c a) Nil
pwild = Pattern $ \w -> return (Nil, constant True)
-- Pattern matching for some Prelude types.
$(reifyGenerateMakeMatch [''Maybe, ''Either, ''Bool])
-- $(reifyGenerateMakeMatch [''Bool])
| thesz/hhdl | src/Hardware/HHDL/HHDL.hs | bsd-3-clause | 44,643 | 1,391 | 48 | 9,006 | 17,192 | 9,001 | 8,191 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main(main) where
import GHC.Driver.Session (getDynFlags)
import GHC.Driver.Monad (liftIO)
import GHC.Paths (libdir)
import GHC (runGhc, DynFlags)
import GHC.Utils.Outputable (Outputable)
import Test.Tasty
import Test.Tasty.HUnit
import GHC.SourceGen
import GhcVersion
data TestCase a = String :~ a
infixr 0 :~
testCases :: Outputable a => DynFlags -> String -> [TestCase a] -> TestTree
testCases dflags name cases = testGroup name $ map run cases
where
run (expected :~ x) =
testCase (takeWhile (/='\n') expected) $ expected @=? showPpr dflags x
testTypes :: DynFlags -> String -> [TestCase HsType'] -> TestTree
testTypes = testCases
testExprs :: DynFlags -> String -> [TestCase HsExpr'] -> TestTree
testExprs = testCases
testDecls :: DynFlags -> String -> [TestCase HsDecl'] -> TestTree
testDecls = testCases
testPats :: DynFlags -> String -> [TestCase Pat'] -> TestTree
testPats = testCases
testModule :: DynFlags -> String -> [TestCase HsModule'] -> TestTree
testModule = testCases
main :: IO ()
main = runGhc (Just libdir) $ do
dflags <- getDynFlags
liftIO $ defaultMain $ testGroup "Tests"
[ typesTest dflags
, exprsTest dflags
, declsTest dflags
, patsTest dflags
, modulesTest dflags
]
typesTest, exprsTest, declsTest, patsTest, modulesTest :: DynFlags -> TestTree
typesTest dflags = testGroup "Type"
[ test "var"
[ "A" :~ var "A"
, "x" :~ var "x"
, "A.x" :~ var "A.x"
, "x" :~ var (unqual "x")
, "A.x" :~ var (qual "A" "x")
]
, test "app"
[ "A x" :~ var "A" @@ var "x"
, "(+) x" :~ var "+" @@ var "x"
, "A (B x)" :~ var "A" @@ par (var "B" @@ var "x")
, "A (B x)" :~ var "A" @@ par (var "B" @@ var "x")
, "A ((B x))" :~ var "A" @@ par (par (var "B" @@ var "x"))
, "A x (B y z)" :~ var "A" @@ var "x" @@ (var "B" @@ var "y" @@ var "z")
, "A w (B x y) Z"
:~ var "A" @@ var "w" @@ (var "B" @@ var "x" @@ var "y") @@ var "Z"
]
, test "op"
[ "x + y" :~ op (var "x") "+" (var "y")
, "x `add` y" :~ op (var "x") "add" (var "y")
, "x * (y + z)" :~ op (var "x") "*" (op (var "y") "+" (var "z"))
, "(x * y) + z" :~ op (op (var "x") "*" (var "y")) "+" (var "z")
, "x `mult` (y `add` z)" :~ op (var "x") "mult" (op (var "y") "add" (var "z"))
, "A x * (B y + C z)" :~ op (var "A" @@ var "x") "*"
(op (var "B" @@ var "y") "+" (var "C" @@ var "z"))
, "(f . g) x" :~ op (var "f") "." (var "g") @@ var "x"
]
, test "function"
[ "a -> b" :~ var "a" --> var "b"
, "a -> b -> c" :~ var "a" --> var "b" --> var "c"
, "a -> b -> c" :~ var "a" --> (var "b" --> var "c")
, "(a -> b) -> c" :~ (var "a" --> var "b") --> var "c"
-- These tests also check that ==> and --> have compatible precedences:
, "A a => a -> b" :~ [var "A" @@ var "a"] ==> var "a" --> var "b"
, "(A a, B b) => a -> b" :~
[var "A" @@ var "a", var "B" @@ var "b"] ==> var "a" --> var "b"
-- It appears to be correct to *not* wrap `A => c` in parentheses;
-- GHC still parses it as a function between two HsQualTy.
, "(A => b) -> A => c" :~
([var "A"] ==> var "b") --> ([var "A"] ==> var "c")
, "(A => b) -> A => c" :~
([var "A"] ==> var "b") --> [var "A"] ==> var "c"
]
, test "literals"
[ "\"abc\"" :~ stringTy "abc"
, "123" :~ numTy 123
]
, test "unit"
[ "()" :~ unit
, "(# #)" :~ unboxedTuple []
]
, test "list"
[ "[x]" :~ listTy (var "x")
, "'[]" :~ listPromotedTy []
, "'[x]" :~ listPromotedTy [var "x"]
, "'[y, z]" :~ listPromotedTy [var "y", var "z"]
]
, test "tuple"
[ "(a, b)" :~ tuple [(var "a"), (var "b")]
, "(# a, b #)" :~ unboxedTuple [(var "a"), (var "b")]
, "'(a, b)" :~ tuplePromotedTy [(var "a"), (var "b")]
]
, test "tyPromotedVar"
-- For some reason, older GHC pretty-printed an extra space.
[ ifGhc88 "'Abc" " 'Abc" :~ tyPromotedVar "Abc"
, ifGhc88 "T 'Abc" "T 'Abc" :~ var "T" @@ tyPromotedVar "Abc"
]
]
where
test = testTypes dflags
exprsTest dflags = testGroup "Expr"
[ test "var"
[ "A" :~ var "A"
, "x" :~ var "x"
, "A.x" :~ var "A.x"
, "x" :~ var (unqual "x")
, "A.x" :~ var (qual "A" "x")
]
, test "app"
[ "A x" :~ var "A" @@ var "x"
, "(+) x" :~ var "+" @@ var "x"
, "(Prelude.+) x" :~ var "Prelude.+" @@ var "x"
, "A (B x)" :~ var "A" @@ (var "B" @@ var "x")
, "A (B x)" :~ var "A" @@ par (var "B" @@ var "x")
, "A ((B x))" :~ var "A" @@ par (par (var "B" @@ var "x"))
, "A x (B y z)" :~ var "A" @@ var "x" @@ (var "B" @@ var "y" @@ var "z")
, "A w (B x y) Z"
:~ var "A" @@ var "w" @@ (var "B" @@ var "x" @@ var "y") @@ var "Z"
, "A 3" :~ var "A" @@ int 3
, "A (-3)" :~ var "A" @@ int (-3)
, "A 3.0" :~ var "A" @@ frac 3.0
, "A (-3.0)" :~ var "A" @@ frac (-3.0)
, "A 'x'" :~ var "A" @@ char 'x'
, "A \"xyz\"" :~ var "A" @@ string "xyz"
, "(\\ x -> x) (\\ x -> x)" :~
let f = lambda [bvar "x"] (var "x")
in f @@ f
, "f x @t" :~ tyApp (var "f" @@ var "x") (var "t")
, "f (x @t)" :~ var "f" @@ (tyApp (var "x") (var "t"))
]
, test "op"
[ "x + y" :~ op (var "x") "+" (var "y")
, "x Prelude.+ y" :~ op (var "x") "Prelude.+" (var "y")
, "x `add` y" :~ op (var "x") "add" (var "y")
, "x * (y + z)" :~ op (var "x") "*" (op (var "y") "+" (var "z"))
, "(x * y) + z" :~ op (op (var "x") "*" (var "y")) "+" (var "z")
, "x `mult` (y `add` z)" :~ op (var "x") "mult" (op (var "y") "add" (var "z"))
, "A x * (B y + C z)" :~ op (var "A" @@ var "x") "*"
(op (var "B" @@ var "y") "+" (var "C" @@ var "z"))
, "(f . g) x" :~ op (var "f") "." (var "g") @@ var "x"
, "(\\ x -> x) . (\\ x -> x)" :~
let f = lambda [bvar "x"] (var "x")
in op f "." f
, "x @s + y @t" :~
op (var "x" `tyApp` var "s") "+" (var "y" `tyApp` var "t")
]
, test "period-op"
[ "(Prelude..) x" :~ var "Prelude.." @@ var "x"
, "x Prelude.. y" :~ op (var "x") "Prelude.." (var "y")
]
, test ":@@:"
-- TODO: GHC puts extra space here.
[ " e :: t" :~ var "e" @::@ var "t" ]
, test "unit"
[ "()" :~ unit ]
, test "list"
[ "[]" :~ list []
, "[]" :~ nil
, "[x]" :~ list [var "x"]
, "[y, z]" :~ list [var "y", var "z"]
, "(:)" :~ cons
, "(:) x y" :~ cons @@ var "x" @@ var "y"
]
, test "tyApp"
[ "x @a" :~ tyApp (var "x") (var "a")
, "x @a @b" :~ tyApp (tyApp (var "x") (var "a")) (var "b")
, "x @a b" :~ tyApp (var "x") (var "a") @@ var "b"
, "x @(a b)" :~ tyApp (var "x") (var "a" @@ var "b")
, "x @(a + b)" :~ tyApp (var "x") (op (var "a") "+" (var "b"))
, "f x @t" :~ (var "f" @@ var "x") `tyApp` var "t"
, "f (x @t)" :~ var "f" @@ (var "x" `tyApp` var "t")
]
, test "recordConE"
[ "A {}" :~ recordConE "A" []
, "A {x = 1, y = 2}" :~ recordConE "A" [("x", int 1), ("y", int 2)]
]
, test "recordUpd"
[ "r {b = x, c = y}"
:~ recordUpd (var "r") [("b", var "x"), ("c", var "y")]
, "(f x) {b = x}"
:~ recordUpd (var "f" @@ var "x") [("b", var "x")]
, "f x {b = x}"
:~ var "f" @@ recordUpd (var "x") [("b", var "x")]
, "(x + y) {b = x}"
:~ recordUpd (op (var "x") "+" (var "y")) [("b", var "x")]
, "x + y {b = x}"
:~ op (var "x") "+" (recordUpd (var "y") [("b", var "x")])
]
, test "let"
[ "let x = 1 in x" :~ let' [valBind "x" $ int 1] (var "x")
, "let f x = 1 in f" :~
let' [ funBind "f" $ match [bvar "x"] $ int 1] (var "f")
, "let f (A x) = 1 in f" :~
let' [ funBind "f" $ match [conP "A" [bvar "x"]] $ int 1] (var "f")
]
, test "do"
-- TODO: add more tests.
[ "do (let x = 1 in x)" :~ do' [stmt $ let' [valBind "x" (int 1)] (var "x")]
]
, test "arithSeq"
[ "[a .. ]" :~ from (var "a")
, "[a, b .. ]" :~ fromThen (var "a") (var "b")
, "[a .. b]" :~ fromTo (var "a") (var "b")
, "[a, b .. c]" :~ fromThenTo (var "a") (var "b") (var "c")
]
, test "list comprehension"
[ "[x | x <- [1 .. 10]]" :~
listComp (bvar "x") [bvar "x" <-- fromTo (int 1) (int 10)]
, "[x + y | x <- [1 .. 10], y <- [11 .. 20], even y]" :~
listComp (op (bvar "x") "+" (bvar "y"))
[ bvar "x" <-- fromTo (int 1) (int 10)
, bvar "y" <-- fromTo (int 11) (int 20)
, stmt $ var "even" @@ bvar "y"
]
]
]
where
test = testExprs dflags
declsTest dflags = testGroup "Decls"
[ test "patBind"
[ "x = x" :~ patBind (bvar "x") (var "x")
, "(x, y) = (y, x)" :~ patBind (tuple [bvar "x", bvar "y"])
(tuple [var "y", var "x"])
, "(x, y)\n | test = (1, 2)\n | otherwise = (2, 3)" :~
patBindGRHSs (tuple [bvar "x", bvar "y"])
$ guardedRhs
[ var "test" `guard` tuple [int 1, int 2]
, var "otherwise" `guard` tuple [int 2, int 3]
]
, "z | Just y <- x, y = ()" :~
patBindGRHSs (bvar "z")
$ guardedRhs
[guards
[ conP "Just" [bvar "y"] <-- var "x"
, stmt (var "y")
]
unit
]
]
, test "valBind"
[ "x = y" :~ valBindGRHSs "x" $ rhs $ var "y"
, "x = y" :~ valBind "x" $ var "y"
, "x | test = 1\n | otherwise = 2" :~
valBindGRHSs "x"
$ guardedRhs
[ var "test" `guard` int 1
, var "otherwise" `guard` int 2
]
, "x = (+)" :~ valBind "x" $ var "+"
]
, test "funBind"
[ "not True = False\nnot False = True" :~
funBinds "not"
[ match [bvar "True"] (var "False")
, match [bvar "False"] (var "True")
]
, "True && True = True\nTrue && False = False" :~
funBindsWithFixity Nothing "&&"
[ match [bvar "True", bvar "True"] (var "True")
, match [bvar "True", bvar "False"] (var "False")
]
, "not x\n | x = False\n | otherwise = True" :~
funBind "not"
$ matchGRHSs [bvar "x"] $ guardedRhs
[ guard (var "x") (var "False")
, guard (var "otherwise") (var "True")
]
, "f (A x) = 1" :~ funBind "f" $ match [conP "A" [bvar "x"]] (int 1)
]
, test "tyFamInst"
[ "type instance Elt String = Char"
:~ tyFamInst "Elt" [var "String"] (var "Char")
, "instance Container String where\n type Elt String = Char"
:~ instance' (var "Container" @@ var "String")
[tyFamInst "Elt" [var "String"] (var "Char")]
]
, test "patSynSigs"
[ "pattern F, G :: T" :~ patSynSigs ["F", "G"] $ var "T"
, "pattern F :: T" :~ patSynSig "F" $ var "T"
]
, test "patSynBind"
[ "pattern F a b = G b a"
:~ patSynBind "F" ["a", "b"] $ conP "G" [bvar "b", bvar "a"]
]
, test "dataDecl"
[ "data Either a b\n = Left a | Right b\n deriving Show"
:~ data' "Either" [bvar "a", bvar "b"]
[ prefixCon "Left" [field $ var "a"]
, prefixCon "Right" [field $ var "b"]
] $ [deriving' [var "Show"]]
, "data Either a (b :: Type)\n = Left a | Right b\n deriving Show"
:~ data' "Either" [bvar "a", kindedVar "b" (var "Type")]
[ prefixCon "Left" [field $ var "a"]
, prefixCon "Right" [field $ var "b"]
] $ [deriving' [var "Show"]]
]
, test "newtypeDecl"
[ "newtype Const a b\n = Const a\n deriving Show"
:~ newtype' "Const" [bvar "a", bvar "b"]
(prefixCon "Const" [field $ var "a"])
$ [deriving' [var "Show"]]
, "newtype Const a (b :: Type)\n = Const a\n deriving Show"
:~ newtype' "Const" [bvar "a", kindedVar "b" (var "Type")]
(prefixCon "Const" [field $ var "a"])
[deriving' [var "Show"]]
]
, test "standaloneDeriving"
[ "deriving instance Show Int"
:~ standaloneDeriving (var "Show" @@ var "Int")
, "deriving instance Show a => Show (Maybe a)"
:~ standaloneDeriving ([var "Show" @@ var "a"] ==> var "Show" @@ (var "Maybe" @@ var "a"))
, "deriving stock instance Show Int"
:~ standaloneDerivingStock (var "Show" @@ var "Int")
, "deriving newtype instance Show a => Show (Identity a)"
:~ standaloneDerivingNewtype ([var "Show" @@ var "a"] ==> var "Show" @@ (var "Identity" @@ var "a"))
, "deriving anyclass instance Show Person"
:~ standaloneDerivingAnyclass (var "Show" @@ var "Person")
]
]
where
test = testDecls dflags
patsTest dflags = testGroup "Pats"
[ test "app"
[ "A x y" :~ conP "A" [bvar "x", bvar "y"]
, "(:) x y" :~ conP ":" [bvar "x", bvar "y"]
, "(Prelude.:) x" :~ conP "Prelude.:" [bvar "x"]
, "A (B x)" :~ conP "A" [conP "B" [bvar "x"]]
, "A (B x)" :~ conP "A" [par $ conP "B" [bvar "x"]]
, "A ((B x))" :~ conP "A" [par $ par $ conP "B" [bvar "x"]]
, "A x (B y z)" :~ conP "A" [bvar "x", conP "B" [bvar "y", bvar "z"]]
, "A w (B x y) Z"
:~ conP "A" [bvar "w", conP "B" [bvar "x", bvar "y"], conP "Z" []]
, "A 3" :~ conP "A" [int 3]
, "A (-3)" :~ conP "A" [int (-3)]
, "A 3.0" :~ conP "A" [frac 3.0]
, "A (-3.0)" :~ conP "A" [frac (-3.0)]
, "A 'x'" :~ conP "A" [char 'x']
, "A \"xyz\"" :~ conP "A" [string "xyz"]
, "A B {x = C}"
:~ conP "A" [recordConP "B" [("x", conP "C" [])]]
]
, test "asP"
[ "x@B" :~ asP "x" $ conP "B" []
, "x@(B y)" :~ asP "x" $ conP "B" [bvar "y"]
, "x@_" :~ asP "x" wildP
]
, test "strictP"
[ "!x" :~ strictP $ bvar "x"
, "!B" :~ strictP $ conP "B" []
, "!(B y)" :~ strictP $ conP "B" [bvar "y"]
, "!_" :~ strictP wildP
]
, test "lazyP"
[ "~x" :~ lazyP $ bvar "x"
, "~B" :~ lazyP $ conP "B" []
, "~(B y)" :~ lazyP $ conP "B" [bvar "y"]
, "~_" :~ lazyP wildP
]
, test "sigPat"
[ "x :: A" :~ sigP (bvar "x") (bvar "A")
, "A x :: A x" :~ sigP (conP "A" [bvar "x"]) (bvar "A" @@ bvar "x")
]
, test "recordConP"
[ "A {x = Y}" :~ recordConP "A" [("x", conP "Y" [])]
]
]
where
test = testPats dflags
-- TODO: Add more test cases from pprint_examples.hs.
modulesTest dflags = testGroup "Modules"
[ test "import"
[ "import M" :~
module' Nothing Nothing [import' "M"] []
, "import {-# SOURCE #-} M" :~
module' Nothing Nothing
[source $ import' "M"] []
]
]
where
test = testModule dflags
| google/ghc-source-gen | tests/pprint_test.hs | bsd-3-clause | 15,950 | 0 | 18 | 6,034 | 5,748 | 2,869 | 2,879 | 326 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Define the column types used to represent our data. Here, we wish
-- to parse data captured as 'Data.Time.LocalTime.LocalTime' values
-- into the \"America/Chicago\" time zone.
module Frames.Time.Chicago.Columns (
MyColumns
, TimeIn(..)
, Chicago(..)
, colQ
, columnUniverse
, rowGen
-- , chicagoToZonedTime
-- , zonedTimeToChicago
, addSecondsChicago
) where
import Frames hiding ((:&))
import Data.Hashable
import Frames.CSV (colQ,columnUniverse,rowGen)
import Frames.ColumnTypeable (Parseable(..))
import Frames.Time.Chicago.TimeIn
import Data.Time
import Data.Time.Lens
import Data.Time.Clock
import Data.Time.Zones
import Data.Time.Zones.TH
import GHC.Generics
import Frames.Default
import qualified Data.Vector as VB
import Frames.InCore (RecVec, VectorFor(..))
import Data.String (IsString(..))
import Control.Monad.Primitive (PrimMonad)
import Pipes (Pipe,Producer, (>->), runEffect)
import qualified Pipes.Prelude as P
import qualified Pipes as P
-- | Define a 'Parseable' instance for @TimeIn "America/Chicago"@
timeIn "America/Chicago"
-- | We need this newtype because Template Haskell can not handle the
-- type @TimeIn "America/Chicago"@ as of @GHC-8.0.1@ and
-- @template-haskell-2.11.0.0@
newtype Chicago = Chicago (TimeIn "America/Chicago") deriving (Show)
instance Parseable Chicago where
parse = fmap (fmap Chicago) . parse
instance Eq Chicago where
(Chicago (TimeIn zndTm)) == (Chicago (TimeIn zndTm')) = zndTm == zndTm'
-- instance Eq ZonedTime where
-- a == b = zonedTimeToUTC a == zonedTimeToUTC b
deriving instance Hashable Chicago
-- | The column types we expect our data to conform to
type MyColumns = Chicago ': CommonColumns
-- TODO reconsider whether using the ord instance of the raw LocalTime with no timezone is okay or not
instance Ord Chicago where
(Chicago (TimeIn (ZonedTime lt1 _))) `compare` (Chicago (TimeIn (ZonedTime lt2 _))) = lt1 `compare` lt2
instance (IsString ZonedTime) where fromString = isStringZonedTime
instance Default (s :-> Chicago) where def = Col (Chicago (TimeIn "America/Chicago"))
type instance VectorFor Chicago = VB.Vector
-- | extracts the zoned time out of a Chicago type
chicagoToZoned = (\(Chicago (TimeIn zt)) -> zt)
tzChicago :: TZ
tzChicago = $(includeTZFromDB "America/Chicago")
-- chicagoToZonedTime :: Chicago -> ZonedTime
-- chicagoToZonedTime (Chicago timeIn) = go timeIn
-- where go (TimeIn utcTm) = do
-- let tz = timeZoneForUTCTime tzChicago utcTm
-- utcToZonedTime tz utcTm
-- zonedTimeToChicago :: ZonedTime -> Chicago
-- zonedTimeToChicago zt = do
-- let utcTm = zonedTimeToUTC zt
-- Chicago (TimeIn utcTm)
addSecondsChicago :: NominalDiffTime -> Chicago -> Chicago
addSecondsChicago seconds (Chicago timeIn) = go timeIn
where go (TimeIn zndTm) = Chicago (TimeIn zndTm')
where utcTm = zonedTimeToUTC (zndTm :: ZonedTime) :: UTCTime
tmZn = zonedTimeZone zndTm
zndTm' = utcToZonedTime tmZn (addUTCTime seconds utcTm) :: ZonedTime
-- λ> :t \r -> set birthday (chicagoToZonedTime (view birthday r))
-- TODO move these functions somewhere else that makes more sense
-- | Filters out records whose date isn't within the past N days
withinPastNDays
:: (forall f. Functor f => ((Chicago -> f Chicago) -> Record rs -> f (Record rs)))
-> Int
-> Pipe (Record rs) (Record rs) IO r
withinPastNDays targetLens n = P.filterM (\r -> do
now <- getCurrentTime
pure $ (getDateFromRec r) >= (modL day (subtract n) now)
)
where getDateFromRec = zonedTimeToUTC . chicagoToZoned . rget targetLens
-- | Returns records whose target date falls between beginning of start Day and before start of end Day
dateBetween :: (PrimMonad m1) =>
(forall f. Functor f => ((Chicago -> f Chicago) -> Record rs -> f (Record rs)))
-> Day
-> Day
-> Pipe (Record rs) (Record rs) m1 m
dateBetween target start end = P.filter (\r -> let targetDate = (rget target r) :: Chicago
targetDate' = chicagoToZoned targetDate :: ZonedTime
targetDay = localDay (zonedTimeToLocalTime targetDate') :: Day
in
targetDay >= start && targetDay < end
)
{-# INLINABLE dateBetween #-}
-- | dateBetween for a Frame such as the result of `inCoreAoS (producer)`
-- example:
-- λ> F.length <$> dateBetween' transactionDate (inCoreAoS transactions) (d 2014 4 1) (d 2014 4 5)
-- 40
dateBetween' :: (RecVec fr, PrimMonad m) =>
(forall f. Functor f => ((Chicago -> f Chicago) -> Record fr -> f (Record fr))) -- target lens
-> m (FrameRec fr) -- in frame
-> Day -- start
-> Day -- end
-> _ -- TODO can remove the monad wrapped FrameRec with runST I think, like: https://github.com/acowley/Frames/blob/122636432ab425f4cbf12fd400996eab78ef1462/src/Frames/InCore.hs#L215
dateBetween' target frame start end = do
frame' <- frame
-- ((dateBetween target start end) `onFrame` frame')
((dateBetween target start end) `onFrame` frame')
{-# INLINABLE dateBetween' #-}
onFrame :: (RecVec rs, PrimMonad m) => Pipe (Record rs) (Record rs) m () -> FrameRec rs -> m (FrameRec rs)
onFrame pipe f = inCoreAoS $ P.each f P.>-> pipe
{-# INLINABLE onFrame #-}
| codygman/frames-diff | Frames/Time/Chicago/Columns.hs | bsd-3-clause | 6,043 | 1 | 15 | 1,407 | 1,240 | 692 | 548 | 91 | 1 |
-- |
-- Module : Data.Vector.Unboxed.Parallel
-- Copyright : [2011] Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Trevor L. McDonell <tmcdonell@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable (GHC Extensions)
--
module Data.Vector.Unboxed.Parallel (
-- * Construction
enumFromN, enumFromStepN,
-- * Element-wise operations
map, imap, zip, zipWith,
-- * Reductions
fold, foldMap,
-- ** Specialised reductions
all, any, and, or, sum, product, maximum, minimum,
-- * Re-exported for convenience
module Data.Vector.Unboxed
) where
import Prelude ( Int, Bool, Num, Ord )
import Data.Vector.Unboxed hiding (
enumFromN, enumFromStepN,
map, imap, zip, zipWith,
all, any, and, or, sum, product, maximum, minimum )
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Generic.Parallel as G
-- Construction
-- ------------
-- | Yield a vector of the given length containing the values @x@, @x+1@ etc.
--
{-# INLINE enumFromN #-}
enumFromN :: (Unbox a, Num a) => a -> Int -> Vector a
enumFromN = G.enumFromN
-- | Yield a vector of the given values containing the values @x@, @x+y@,
-- @x+y+y@, etc.
--
{-# INLINE enumFromStepN #-}
enumFromStepN :: (Unbox a, Num a) => a -> a -> Int -> Vector a
enumFromStepN = G.enumFromStepN
-- Mapping
-- -------
-- | Map a function to each element of an array, in parallel.
--
{-# INLINE map #-}
map :: (Unbox a, Unbox b) => (a -> b) -> Vector a -> Vector b
map = G.map
-- | Map a function to each element of an array and its index.
--
{-# INLINE imap #-}
imap :: (Unbox a, Unbox b) => (Int -> a -> b) -> Vector a -> Vector b
imap = G.imap
-- Zipping
-- -------
-- | Zip two vectors
--
{-# INLINE zip #-}
zip :: (Unbox a, Unbox b) => Vector a -> Vector b -> Vector (a,b)
zip = U.zip
-- | Zip two vectors with the given function.
--
{-# INLINE zipWith #-}
zipWith :: (Unbox a, Unbox b, Unbox c)
=> (a -> b -> c) -> Vector a -> Vector b -> Vector c
zipWith = G.zipWith
-- Reductions
-- ----------
-- | Reduce an array to a single value. The combination function must be an
-- associative operation, and the stating element must be neutral with respect
-- to this operator; i.e. the pair must form a monoid. For example, @0@ is
-- neutral with respect to @(+)@, as @0 + a = a@.
--
-- These restrictions are required to support efficient parallel evaluation, as
-- the starting value may be used many times depending on the number of threads.
--
{-# INLINE fold #-}
fold :: Unbox a => (a -> a -> a) -> a -> Vector a -> a
fold = G.fold
-- | A combination of 'map' followed by 'fold'. The same restrictions apply to
-- the reduction operator and neutral element.
--
{-# INLINE foldMap #-}
foldMap :: Unbox a => (a -> b) -> (b -> b -> b) -> b -> Vector a -> b
foldMap = G.foldMap
-- Specialised reductions
-- ----------------------
-- | Check if all elements satisfy the predicate
--
{-# INLINE all #-}
all :: Unbox a => (a -> Bool) -> Vector a -> Bool
all = G.all
-- | Check if any element satisfies the predicate
--
{-# INLINE any #-}
any :: Unbox a => (a -> Bool) -> Vector a -> Bool
any = G.any
-- | Check if all elements are True
--
{-# INLINE and #-}
and :: Vector Bool -> Bool
and = G.and
-- | Check if any element is True
--
{-# INLINE or #-}
or :: Vector Bool -> Bool
or = G.or
-- | Compute the sum of the elements
--
{-# INLINE sum #-}
sum :: (Unbox a, Num a) => Vector a -> a
sum = G.sum
-- | Compute the product of the elements
--
{-# INLINE product #-}
product :: (Unbox a, Num a) => Vector a -> a
product = G.product
-- | Yield the maximum element of a non-empty vector
--
{-# INLINE maximum #-}
maximum :: (Unbox a, Ord a) => Vector a -> a
maximum = G.maximum
-- | Yield the minimum element of a non-empty vector
--
{-# INLINE minimum #-}
minimum :: (Unbox a, Ord a) => Vector a -> a
minimum = G.minimum
| tmcdonell/vector-parallel | Data/Vector/Unboxed/Parallel.hs | bsd-3-clause | 3,941 | 0 | 10 | 879 | 876 | 519 | 357 | 62 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Pact.Server.History.Persistence
( createDB
, insertCompletedCommand
, queryForExisting
, selectCompletedCommands
, selectAllCommands
, closeDB
) where
import Control.Monad
import qualified Data.Text as T
import qualified Data.Aeson as A
import Data.Text.Encoding (encodeUtf8)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BSL
import Data.List (sortBy)
import Data.HashSet (HashSet)
import qualified Data.HashSet as HashSet
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.Maybe
import Database.SQLite3.Direct
import Pact.Types.Command
import Pact.Types.Runtime
import Pact.Types.SQLite
import Pact.Server.History.Types
hashToField :: Hash -> SType
hashToField h = SText $ Utf8 $ BSL.toStrict $ A.encode h
hashFromField :: ByteString -> Hash
hashFromField h = case A.eitherDecodeStrict' h of
Left err -> error $ "hashFromField: unable to decode Hash from database! " ++ show err ++ " => " ++ show h
Right v -> v
crToField :: CommandResult Hash -> SType
crToField r = SText $ Utf8 $ BSL.toStrict $ A.encode $ A.toJSON r
crFromField :: ByteString -> CommandResult Hash
crFromField cr = case A.eitherDecodeStrict' cr of
Left err -> error $ "crFromField: unable to decode CommandResult from database! " ++ show err ++ "\n" ++ show cr
Right v' -> v'
userSigsToField :: [UserSig] -> SType
userSigsToField us = SText $ Utf8 $ BSL.toStrict $ A.encode us
userSigsFromField :: ByteString -> [UserSig]
userSigsFromField us = case A.eitherDecodeStrict' us of
Left err -> error $ "userSigsFromField: unable to decode [UserSigs] from database! " ++ show err ++ "\n" ++ show us
Right v -> v
gasToField :: Gas -> SType
gasToField (Gas g) = SInt g
sqlDbSchema :: Utf8
sqlDbSchema =
"CREATE TABLE IF NOT EXISTS 'main'.'pactCommands' \
\( 'hash' TEXT PRIMARY KEY NOT NULL UNIQUE\
\, 'txid' INTEGER NOT NULL\
\, 'command' TEXT NOT NULL\
\, 'result' TEXT NOT NULL\
\, 'userSigs' TEXT NOT NULL\
\, 'gas' INTEGER NOT NULL\
\)"
eitherToError :: Show e => String -> Either e a -> a
eitherToError _ (Right v) = v
eitherToError s (Left e) = error $ "SQLite Error in History exec: " ++ s ++ "\nWith Error: "++ show e
createDB :: FilePath -> IO DbEnv
createDB f = do
conn' <- eitherToError "OpenDB" <$> open (Utf8 $ encodeUtf8 $ T.pack f)
eitherToError "CreateTable" <$> exec conn' sqlDbSchema
-- eitherToError "pragmas" <$> exec conn "PRAGMA locking_mode = EXCLUSIVE"
DbEnv <$> pure conn'
<*> prepStmt conn' sqlInsertHistoryRow
<*> prepStmt conn' sqlQueryForExisting
<*> prepStmt conn' sqlSelectCompletedCommands
<*> prepStmt conn' sqlSelectAllCommands
closeDB :: DbEnv -> IO ()
closeDB DbEnv{..} = do
liftEither $ closeStmt _insertStatement
liftEither $ closeStmt _qryExistingStmt
liftEither $ closeStmt _qryCompletedStmt
liftEither $ closeStmt _qrySelectAllCmds
liftEither $ close _conn
sqlInsertHistoryRow :: Utf8
sqlInsertHistoryRow =
"INSERT INTO 'main'.'pactCommands' \
\( 'hash'\
\, 'txid' \
\, 'command'\
\, 'result'\
\, 'userSigs'\
\, 'gas'\
\) VALUES (?,?,?,?,?,?)"
insertRow :: Statement -> (Command ByteString, CommandResult Hash) -> IO ()
insertRow s (Command{..},cr@CommandResult {..}) =
execs s [hashToField (toUntypedHash _cmdHash)
,SInt $ fromIntegral (fromMaybe (-1) _crTxId)
,SText $ Utf8 _cmdPayload
,crToField cr
,userSigsToField _cmdSigs
,gasToField _crGas]
insertCompletedCommand :: DbEnv -> [(Command ByteString, CommandResult Hash)] -> IO ()
insertCompletedCommand DbEnv{..} v = do
let sortCmds (_,cr1) (_,cr2) = compare (_crTxId cr1) (_crTxId cr2)
eitherToError "start insert transaction" <$> exec _conn "BEGIN TRANSACTION"
mapM_ (insertRow _insertStatement) $ sortBy sortCmds v
eitherToError "end insert transaction" <$> exec _conn "END TRANSACTION"
sqlQueryForExisting :: Utf8
sqlQueryForExisting = "SELECT EXISTS(SELECT 1 FROM 'main'.'pactCommands' WHERE hash=:hash LIMIT 1)"
queryForExisting :: DbEnv -> HashSet RequestKey -> IO (HashSet RequestKey)
queryForExisting e v = foldM f v v
where
f s rk = do
r <- qrys (_qryExistingStmt e) [hashToField $ unRequestKey rk] [RInt]
case r of
[[SInt 1]] -> return s
_ -> return $ HashSet.delete rk s
sqlSelectCompletedCommands :: Utf8
sqlSelectCompletedCommands =
"SELECT result,txid FROM 'main'.'pactCommands' WHERE hash=:hash LIMIT 1"
selectCompletedCommands :: DbEnv -> HashSet RequestKey -> IO (HashMap RequestKey (CommandResult Hash))
selectCompletedCommands e v = foldM f HashMap.empty v
where
f m rk = do
rs <- qrys (_qryCompletedStmt e) [hashToField $ unRequestKey rk] [RText,RInt,RInt]
if null rs
then return m
else case head rs of
[SText (Utf8 cr),SInt _, SInt _] ->
return $ HashMap.insert rk (crFromField cr) m
r -> dbError $ "Invalid result from query: " ++ show r
sqlSelectAllCommands :: Utf8
sqlSelectAllCommands = "SELECT hash,command,userSigs FROM 'main'.'pactCommands' ORDER BY txid ASC"
selectAllCommands :: DbEnv -> IO [Command ByteString]
selectAllCommands e = do
let rowToCmd [SText (Utf8 hash'),SText (Utf8 cmd'),SText (Utf8 userSigs')] =
Command { _cmdPayload = cmd'
, _cmdSigs = userSigsFromField userSigs'
, _cmdHash = fromUntypedHash $ hashFromField hash'}
rowToCmd err = error $ "selectAllCommands: unexpected result schema: " ++ show err
fmap rowToCmd <$> qrys_ (_qrySelectAllCmds e) [RText,RText,RText]
| kadena-io/pact | src-ghc/Pact/Server/History/Persistence.hs | bsd-3-clause | 5,800 | 0 | 16 | 1,165 | 1,583 | 803 | 780 | 119 | 3 |
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
module Morra where
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.State
import qualified Data.List as L
import Data.Maybe (fromMaybe)
import System.Random
type Guess = Int
type Fingers = Int
data Scores =
Scores {
player :: Int
, computer :: Int
} deriving Show
data GameState =
GameState {
scores :: Scores
, allPlayerGuesses :: [Guess]
} deriving Show
getPreviousPlayerGuess :: [Guess] -> Maybe Guess
getPreviousPlayerGuess guesses =
go pat guesses'
where
pat = reverse . take 2 $ guesses
guesses' = reverse . drop 1 $ guesses
go [x, y] (x':rest@(y':z:_))
| x == x' && y == y' = Just z
| otherwise = go pat (L.dropWhile (/=x) rest)
go _ _ = Nothing
getComputerGuess :: StateT GameState IO Guess
getComputerGuess = do
playerGuesses <- allPlayerGuesses <$> get
case getPreviousPlayerGuess playerGuesses of
Just guess -> return guess
Nothing -> liftIO $ randomRIO (0, 10)
getComputerFingers :: IO Fingers
getComputerFingers = randomRIO (0, 5)
askPlayerForGuess :: StateT GameState IO Guess
askPlayerForGuess = do
liftIO $ putStr "\nYour guess: "
guess <- liftIO readLn
state @ GameState { allPlayerGuesses } <- get
put $ state { allPlayerGuesses = guess : allPlayerGuesses }
return guess
askPlayerForFingers :: IO Fingers
askPlayerForFingers = putStr "How many fingers? : " >> readLn :: IO Fingers
writeln :: MonadIO m => String -> StateT a m ()
writeln = liftIO . putStrLn
gameLoop :: StateT GameState IO ()
gameLoop = do
playerGuess <- askPlayerForGuess
computerGuess <- getComputerGuess
writeln $ "Computer guess: " ++ show computerGuess
playerFingers <- liftIO askPlayerForFingers
computerFingers <- liftIO getComputerFingers
writeln $ "Computer showed " ++ show computerFingers ++ " fingers."
let totalFingers = playerFingers + computerFingers
writeln $ "Total fingers = " ++ show totalFingers
state @ GameState { scores = scores @ Scores {..} } <- get
newScores <-
if | totalFingers == playerFingers && totalFingers == computerFingers -> do
writeln "Both guess right!"
return $ Scores (player + 1) (computer + 1)
| totalFingers == playerGuess -> do
writeln "Your guess was right!"
return $ scores { player = player + 1 }
| totalFingers == computerGuess -> do
writeln "Computer guess was right, sorry."
return $ scores { computer = computer + 1 }
| otherwise -> do
writeln "Nobody guessed."
return scores
let newState = state { scores = newScores }
writeln $ "Current state: " ++ show newState
put newState
case newScores of
Scores { player = 3 } -> writeln "You win!"
Scores { computer = 3 } -> writeln "Computer wins, sorry."
_ -> gameLoop
main :: IO ()
main = do
(_, s) <- runStateT gameLoop (GameState (Scores 0 0) [])
print . scores $ s
| vasily-kirichenko/haskell-book | src/Transformers/Morra.hs | bsd-3-clause | 3,136 | 2 | 15 | 807 | 949 | 477 | 472 | 85 | 6 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Main where
import Data.Monoid ((<>))
import Data.Proxy (Proxy(..))
import qualified Data.ByteString.Lazy as BL
import SampleAPI (Shoppe1)
import Servant.StateGraph
import Servant.API
api :: Proxy Shoppe1
api = Proxy
main :: IO ()
main = stateGraph' api
| corajr/servant-state-graph | app/Main.hs | bsd-3-clause | 356 | 0 | 6 | 51 | 91 | 57 | 34 | 14 | 1 |
{-|
Module : Data.Algorithm.PPattern.Perm.Enumerate
Description : Short description
Copyright : (c) Laurent Bulteau, Romeo Rizzi, Stéphane Vialette, 2016-2017
License : MIT
Maintainer : vialette@gmaiList.com
Stability : experimental
Here is a longer description of this module, containing some
commentary with @some markup@.
-}
module Data.Algorithm.PPattern.Perm.Enumerate
(
perms
, perms'
, perms''
)
where
import Data.List as List
import Data.Foldable as Foldable
import Data.Algorithm.PPattern.Perm as Perm
{-|
Enumerate all permutations of length 'n'.
>>> Perm.Enumerate.perms 0
[[]]
>>> Perm.Enumerate.perms 1
[[1]]
>>> Perm.Enumerate.perms 2
[[1,2],[2,1]]
>>> Perm.Enumerate.perms 3
[[1,2,3],[2,1,3],[3,2,1],[2,3,1],[3,1,2],[1,3,2]]
-}
perms :: (Enum a, Num a, Ord a) => a -> [Perm]
perms n = [Perm.mk ys | ys <- List.permutations [1..n]]
{-|
Enumerate all permutations of a given list.
>>> Perm.Enumerate.perms' ""
[[]]
>>> Perm.Enumerate.perms' "a"
[[1]]
>>> Perm.Enumerate.perms' "ab"
[[1,2],[2,1]]
>>> Perm.Enumerate.perms' "abc"
[[1,2,3],[2,1,3],[3,2,1],[2,3,1],[3,1,2],[1,3,2]]
-}
perms' :: (Ord a) => [a] -> [Perm.Perm]
perms' xs = [Perm.mk xs' | xs' <- List.permutations xs]
{-|
Enumerate all permutations of a given foldable instance.
>>> Perm.Enumerate.perms'' $ Perm.mk ""
[[]]
>>> Perm.Enumerate.perms'' $ Perm.mk "a"
[[1]]
>>> Perm.Enumerate.perms'' $ Perm.mk "ab"
[[1,2],[2,1]]
>>> Perm.Enumerate.perms'' $ Perm.mk "abc"
[[1,2,3],[2,1,3],[3,2,1],[2,3,1],[3,1,2],[1,3,2]]
-}
perms'' :: (Foldable f, Ord a) => f a -> [Perm.Perm]
perms'' = perms' . Foldable.toList
| vialette/ppattern | src/Data/Algorithm/PPattern/Perm/Enumerate.hs | mit | 1,834 | 0 | 9 | 453 | 212 | 122 | 90 | 14 | 1 |
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..))
import System.Exit (ExitCode(..), exitWith)
import BankAccount ( BankAccount, openAccount, closeAccount
, getBalance, incrementBalance )
import Control.Concurrent
import Control.Monad (void, replicateM)
{-
The BankAccount module should support four calls:
openAccount
Called at the start of each test. Returns a BankAccount.
closeAccount account
Called at the end of each test.
getBalance account
Get the balance of the bank account.
updateBalance account amount
Increment the balance of the bank account by the given amount.
The amount may be negative for a withdrawal.
The initial balance of the bank account should be 0.
-}
exitProperly :: IO Counts -> IO ()
exitProperly m = do
counts <- m
exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
main :: IO ()
main = exitProperly $ runTestTT $ TestList
[ withBank "initial balance is 0" $
checkReturn (Just 0) . getBalance
, withBank "incrementing and checking balance" $ \acct -> do
checkReturn (Just 0) $ getBalance acct
checkReturn (Just 10) $ incrementBalance acct 10
checkReturn (Just 10) $ getBalance acct
, withBank "incrementing balance from other processes then checking it\
\from test process" $ \acct -> do
replicateM 20 (incrementProc acct) >>= mapM_ (void . takeMVar)
checkReturn (Just 20) (getBalance acct)
]
incrementProc :: BankAccount -> IO (MVar ())
incrementProc acct = do
v <- newEmptyMVar
void . forkIO $ do
void (incrementBalance acct 1)
putMVar v ()
return v
checkReturn :: (Show a, Eq a) => a -> IO a -> IO ()
checkReturn expect test = do
v <- test
expect @=? v
withBank :: String -> (BankAccount -> Assertion) -> Test
withBank label f = testCase label $ do
acct <- openAccount
f acct
closeAccount acct
| tfausak/exercism-solutions | haskell/bank-account/bank-account_test.hs | mit | 2,006 | 0 | 15 | 418 | 569 | 283 | 286 | 40 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Database.Persist.Sql.Util (
parseEntityValues
, entityColumnNames
, keyAndEntityColumnNames
, entityColumnCount
, isIdField
, hasCompositeKey
, dbIdColumns
, dbIdColumnsEsc
, dbColumns
, updateFieldDef
, updatePersistValue
, mkUpdateText
, mkUpdateText'
, commaSeparated
, parenWrapped
) where
import Data.Maybe (isJust)
import Data.Monoid ((<>))
import qualified Data.Text as T
import Data.Text (Text, pack)
import Database.Persist (
Entity(Entity), EntityDef, EntityField, HaskellName(HaskellName)
, PersistEntity, PersistValue
, keyFromValues, fromPersistValues, fieldDB, entityId, entityPrimary
, entityFields, entityKeyFields, fieldHaskell, compositeFields, persistFieldDef
, keyAndEntityFields, toPersistValue, DBName, Update(..), PersistUpdate(..)
, FieldDef
)
import Database.Persist.Sql.Types (Sql, SqlBackend, connEscapeName)
entityColumnNames :: EntityDef -> SqlBackend -> [Sql]
entityColumnNames ent conn =
(if hasCompositeKey ent
then [] else [connEscapeName conn $ fieldDB (entityId ent)])
<> map (connEscapeName conn . fieldDB) (entityFields ent)
keyAndEntityColumnNames :: EntityDef -> SqlBackend -> [Sql]
keyAndEntityColumnNames ent conn = map (connEscapeName conn . fieldDB) (keyAndEntityFields ent)
entityColumnCount :: EntityDef -> Int
entityColumnCount e = length (entityFields e)
+ if hasCompositeKey e then 0 else 1
hasCompositeKey :: EntityDef -> Bool
hasCompositeKey = isJust . entityPrimary
dbIdColumns :: SqlBackend -> EntityDef -> [Text]
dbIdColumns conn = dbIdColumnsEsc (connEscapeName conn)
dbIdColumnsEsc :: (DBName -> Text) -> EntityDef -> [Text]
dbIdColumnsEsc esc t = map (esc . fieldDB) $ entityKeyFields t
dbColumns :: SqlBackend -> EntityDef -> [Text]
dbColumns conn t = case entityPrimary t of
Just _ -> flds
Nothing -> escapeDB (entityId t) : flds
where
escapeDB = connEscapeName conn . fieldDB
flds = map escapeDB (entityFields t)
parseEntityValues :: PersistEntity record
=> EntityDef -> [PersistValue] -> Either Text (Entity record)
parseEntityValues t vals =
case entityPrimary t of
Just pdef ->
let pks = map fieldHaskell $ compositeFields pdef
keyvals = map snd . filter ((`elem` pks) . fst)
$ zip (map fieldHaskell $ entityFields t) vals
in fromPersistValuesComposite' keyvals vals
Nothing -> fromPersistValues' vals
where
fromPersistValues' (kpv:xs) = -- oracle returns Double
case fromPersistValues xs of
Left e -> Left e
Right xs' ->
case keyFromValues [kpv] of
Left _ -> error $ "fromPersistValues': keyFromValues failed on " ++ show kpv
Right k -> Right (Entity k xs')
fromPersistValues' xs = Left $ pack ("error in fromPersistValues' xs=" ++ show xs)
fromPersistValuesComposite' keyvals xs =
case fromPersistValues xs of
Left e -> Left e
Right xs' -> case keyFromValues keyvals of
Left _ -> error "fromPersistValuesComposite': keyFromValues failed"
Right key -> Right (Entity key xs')
isIdField :: PersistEntity record => EntityField record typ -> Bool
isIdField f = fieldHaskell (persistFieldDef f) == HaskellName "Id"
-- | Gets the 'FieldDef' for an 'Update'.
updateFieldDef :: PersistEntity v => Update v -> FieldDef
updateFieldDef (Update f _ _) = persistFieldDef f
updateFieldDef BackendUpdate {} = error "updateFieldDef: did not expect BackendUpdate"
updatePersistValue :: Update v -> PersistValue
updatePersistValue (Update _ v _) = toPersistValue v
updatePersistValue (BackendUpdate{}) =
error "updatePersistValue: did not expect BackendUpdate"
commaSeparated :: [Text] -> Text
commaSeparated = T.intercalate ", "
mkUpdateText :: PersistEntity record => SqlBackend -> Update record -> Text
mkUpdateText conn = mkUpdateText' (connEscapeName conn) id
mkUpdateText' :: PersistEntity record => (DBName -> Text) -> (Text -> Text) -> Update record -> Text
mkUpdateText' escapeName refColumn x =
case updateUpdate x of
Assign -> n <> "=?"
Add -> T.concat [n, "=", refColumn n, "+?"]
Subtract -> T.concat [n, "=", refColumn n, "-?"]
Multiply -> T.concat [n, "=", refColumn n, "*?"]
Divide -> T.concat [n, "=", refColumn n, "/?"]
BackendSpecificUpdate up ->
error . T.unpack $ "mkUpdateText: BackendSpecificUpdate " <> up <> " not supported"
where
n = escapeName . fieldDB . updateFieldDef $ x
parenWrapped :: Text -> Text
parenWrapped t = T.concat ["(", t, ")"] | plow-technologies/persistent | persistent/Database/Persist/Sql/Util.hs | mit | 4,682 | 0 | 17 | 1,019 | 1,382 | 722 | 660 | 101 | 7 |
{-# LANGUAGE TemplateHaskell #-}
--------------------------------------------------------------------------------
-- |
-- Module : Data.Comp.Multi.Derive.HFunctor
-- Copyright : (c) 2011 Patrick Bahr
-- License : BSD3
-- Maintainer : Patrick Bahr <paba@diku.dk>
-- Stability : experimental
-- Portability : non-portable (GHC Extensions)
--
-- Automatically derive instances of @HFunctor@.
--
--------------------------------------------------------------------------------
module Data.Comp.Multi.Derive.HFunctor
(
HFunctor,
makeHFunctor
) where
import Control.Monad
import Data.Comp.Derive.Utils
import Data.Comp.Multi.HFunctor
import Data.Maybe
import Language.Haskell.TH
import Prelude hiding (mapM)
import qualified Prelude as P (mapM)
iter 0 _ e = e
iter n f e = iter (n-1) f (f `appE` e)
{-| Derive an instance of 'HFunctor' for a type constructor of any higher-order
kind taking at least two arguments. -}
makeHFunctor :: Name -> Q [Dec]
makeHFunctor fname = do
TyConI (DataD _cxt name args constrs _deriving) <- abstractNewtypeQ $ reify fname
let args' = init args
fArg = VarT . tyVarBndrName $ last args'
argNames = map (VarT . tyVarBndrName) (init args')
complType = foldl AppT (ConT name) argNames
classType = AppT (ConT ''HFunctor) complType
constrs' <- P.mapM (mkPatAndVars . isFarg fArg <=< normalConExp) constrs
hfmapDecl <- funD 'hfmap (map hfmapClause constrs')
return [InstanceD [] classType [hfmapDecl]]
where isFarg fArg (constr, args) = (constr, map (`containsType'` fArg) args)
filterVar _ nonFarg [] x = nonFarg x
filterVar farg _ [depth] x = farg depth x
filterVar _ _ _ _ = error "functor variable occurring twice in argument type"
filterVars args varNs farg nonFarg = zipWith (filterVar farg nonFarg) args varNs
mkCPat constr varNs = ConP constr $ map mkPat varNs
mkPat = VarP
mkPatAndVars (constr, args) =
do varNs <- newNames (length args) "x"
return (conE constr, mkCPat constr varNs,
\ f g -> filterVars args varNs (\ d x -> f d (varE x)) (g . varE),
any (not . null) args, map varE varNs, catMaybes $ filterVars args varNs (curry Just) (const Nothing))
hfmapClause (con, pat,vars',hasFargs,_,_) =
do fn <- newName "f"
let f = varE fn
fp = if hasFargs then VarP fn else WildP
vars = vars' (\d x -> iter d [|fmap|] f `appE` x) id
body <- foldl appE con vars
return $ Clause [fp, pat] (NormalB body) []
| spacekitteh/compdata | src/Data/Comp/Multi/Derive/HFunctor.hs | bsd-3-clause | 2,719 | 0 | 17 | 747 | 780 | 414 | 366 | -1 | -1 |
-- GSoC 2013 - Communicating with mobile devices.
{-# LANGUAGE OverloadedStrings #-}
-- | This Module define the main contants for sending Push Notifications through Apple Push Notification Service.
module Network.PushNotify.Apns.Constants where
import Data.Text
cLOCAL_URL :: String
cLOCAL_URL = "localhost"
cLOCAL_PORT :: Integer
cLOCAL_PORT = 2195
cLOCAL_FEEDBACK_URL :: String
cLOCAL_FEEDBACK_URL = "localhost"
cLOCAL_FEEDBACK_PORT :: Integer
cLOCAL_FEEDBACK_PORT = 2196
cDEVELOPMENT_URL :: String
cDEVELOPMENT_URL = "gateway.sandbox.push.apple.com"
cDEVELOPMENT_PORT :: Integer
cDEVELOPMENT_PORT = 2195
cDEVELOPMENT_FEEDBACK_URL :: String
cDEVELOPMENT_FEEDBACK_URL = "feedback.sandbox.push.apple.com"
cDEVELOPMENT_FEEDBACK_PORT :: Integer
cDEVELOPMENT_FEEDBACK_PORT = 2196
cPRODUCTION_URL :: String
cPRODUCTION_URL = "gateway.push.apple.com"
cPRODUCTION_PORT :: Integer
cPRODUCTION_PORT = 2195
cPRODUCTION_FEEDBACK_URL :: String
cPRODUCTION_FEEDBACK_URL = "feedback.push.apple.com"
cPRODUCTION_FEEDBACK_PORT :: Integer
cPRODUCTION_FEEDBACK_PORT = 2196
-- Fields for JSON object to be sent to APNS servers.
cAPPS :: Text
cAPPS = "aps"
cALERT :: Text
cALERT = "alert"
cBADGE :: Text
cBADGE = "badge"
cSOUND :: Text
cSOUND = "sound"
cBODY :: Text
cBODY = "body"
cACTION_LOC_KEY :: Text
cACTION_LOC_KEY = "action-loc-key"
cLOC_KEY :: Text
cLOC_KEY = "loc-key"
cLOC_ARGS :: Text
cLOC_ARGS = "loc-args"
cLAUNCH_IMAGE :: Text
cLAUNCH_IMAGE = "launch-image"
| MarcosPividori/GSoC-Communicating-with-mobile-devices | push-notify/Network/PushNotify/Apns/Constants.hs | mit | 1,481 | 0 | 4 | 197 | 227 | 139 | 88 | 45 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module CrawlPackage where
import Control.Arrow (second)
import Control.Monad.Except (MonadError, MonadIO, liftIO, throwError)
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import System.Directory (doesFileExist, getCurrentDirectory, setCurrentDirectory)
import System.FilePath ((</>), (<.>))
import qualified Elm.Compiler as Compiler
import qualified Elm.Compiler.Module as Module
import qualified Elm.Package.Description as Desc
import qualified Elm.Package.Name as Pkg
import qualified Elm.Package.Paths as Path
import qualified Elm.Package.Solution as Solution
import qualified Elm.Package.Version as V
import qualified Utils.File as File
import qualified TheMasterPlan as TMP
import TheMasterPlan ( PackageSummary(..), PackageData(..) )
-- STATE and ENVIRONMENT
data Env = Env
{ sourceDirs :: [FilePath]
, availableForeignModules :: Map.Map Module.Name [(Pkg.Name, V.Version)]
}
initEnv
:: (MonadIO m, MonadError String m)
=> FilePath
-> Desc.Description
-> Solution.Solution
-> m Env
initEnv root desc solution =
do availableForeignModules <- readAvailableForeignModules desc solution
let sourceDirs = map (root </>) (Desc.sourceDirs desc)
return (Env sourceDirs availableForeignModules)
-- GENERIC CRAWLER
dfsFromFiles
:: (MonadIO m, MonadError String m)
=> FilePath
-> Solution.Solution
-> Desc.Description
-> [FilePath]
-> m ([Module.Name], PackageSummary)
dfsFromFiles root solution desc filePaths =
do env <- initEnv root desc solution
let pkgName = Desc.name desc
info <- mapM (readPackageData pkgName Nothing) filePaths
let names = map fst info
let unvisited = concatMap (snd . snd) info
let pkgData = Map.fromList (map (second fst) info)
let initialSummary = PackageSummary pkgData Map.empty Map.empty
summary <-
dfs (Desc.natives desc) pkgName unvisited env initialSummary
return (names, summary)
dfsFromExposedModules
:: (MonadIO m, MonadError String m)
=> FilePath
-> Solution.Solution
-> Desc.Description
-> m PackageSummary
dfsFromExposedModules root solution desc =
do env <- initEnv root desc solution
let unvisited = addParent Nothing (Desc.exposed desc)
let summary = PackageSummary Map.empty Map.empty Map.empty
dfs (Desc.natives desc) (Desc.name desc) unvisited env summary
-- DEPTH FIRST SEARCH
dfs :: (MonadIO m, MonadError String m)
=> Bool
-> Pkg.Name
-> [(Module.Name, Maybe Module.Name)]
-> Env
-> PackageSummary
-> m PackageSummary
dfs _allowNatives _pkgName [] _env summary =
return summary
dfs allowNatives pkgName ((name,_) : unvisited) env summary
| Map.member name (packageData summary) =
dfs allowNatives pkgName unvisited env summary
dfs allowNatives pkgName ((name,maybeParent) : unvisited) env summary =
do filePaths <- find allowNatives name (sourceDirs env)
case (filePaths, Map.lookup name (availableForeignModules env)) of
([Elm filePath], Nothing) ->
do (name, (pkgData, newUnvisited)) <-
readPackageData pkgName (Just name) filePath
dfs allowNatives pkgName (newUnvisited ++ unvisited) env $ summary {
packageData = Map.insert name pkgData (packageData summary)
}
([JS filePath], Nothing) ->
dfs allowNatives pkgName unvisited env $ summary {
packageNatives = Map.insert name filePath (packageNatives summary)
}
([], Just [pkg]) ->
dfs allowNatives pkgName unvisited env $ summary {
packageForeignDependencies =
Map.insert name pkg (packageForeignDependencies summary)
}
([], Nothing) ->
throwError (errorNotFound name maybeParent)
(_, maybePkgs) ->
throwError (errorTooMany name maybeParent filePaths maybePkgs)
-- FIND LOCAL FILE PATH
data CodePath = Elm FilePath | JS FilePath
find :: (MonadIO m) => Bool -> Module.Name -> [FilePath] -> m [CodePath]
find allowNatives moduleName sourceDirs =
findHelp allowNatives [] moduleName sourceDirs
findHelp
:: (MonadIO m)
=> Bool
-> [CodePath]
-> Module.Name
-> [FilePath]
-> m [CodePath]
findHelp _allowNatives locations _moduleName [] =
return locations
findHelp allowNatives locations moduleName (dir:srcDirs) =
do locations' <- addElmPath locations
updatedLocations <-
if allowNatives then addJsPath locations' else return locations'
findHelp allowNatives updatedLocations moduleName srcDirs
where
consIf bool x xs =
if bool then x:xs else xs
addElmPath locs =
do let elmPath = dir </> Module.nameToPath moduleName <.> "elm"
elmExists <- liftIO (doesFileExist elmPath)
return (consIf elmExists (Elm elmPath) locs)
addJsPath locs =
do let jsPath = dir </> Module.nameToPath moduleName <.> "js"
jsExists <-
case moduleName of
Module.Name ("Native" : _) -> liftIO (doesFileExist jsPath)
_ -> return False
return (consIf jsExists (JS jsPath) locs)
-- READ and VALIDATE PACKAGE DATA for a file
readPackageData
:: (MonadIO m, MonadError String m)
=> Pkg.Name
-> Maybe Module.Name
-> FilePath
-> m (Module.Name, (PackageData, [(Module.Name, Maybe Module.Name)]))
readPackageData pkgName maybeName filePath =
do sourceCode <- liftIO (File.readStringUtf8 filePath)
(name, rawDeps) <-
case Compiler.parseDependencies sourceCode of
Right result ->
return result
Left msgs ->
throwError (concatMap (format sourceCode) msgs)
checkName filePath name maybeName
let deps =
if pkgName == TMP.core
then rawDeps
else Module.defaultImports ++ rawDeps
return (name, (PackageData filePath deps, addParent (Just name) deps))
where
format src msg =
Compiler.errorToString Compiler.dummyDealiaser filePath src msg
checkName
:: (MonadError String m)
=> FilePath -> Module.Name -> Maybe Module.Name -> m ()
checkName path nameFromSource maybeName =
case maybeName of
Nothing -> return ()
Just nameFromPath
| nameFromSource == nameFromPath -> return ()
| otherwise ->
throwError (errorNameMismatch path nameFromPath nameFromSource)
addParent :: Maybe Module.Name -> [Module.Name] -> [(Module.Name, Maybe Module.Name)]
addParent maybeParent names =
map (\name -> (name, maybeParent)) names
-- FOREIGN MODULES -- which ones are available, who exposes them?
readAvailableForeignModules
:: (MonadIO m, MonadError String m)
=> Desc.Description
-> Solution.Solution
-> m (Map.Map Module.Name [(Pkg.Name, V.Version)])
readAvailableForeignModules desc solution =
do visiblePackages <- allVisible desc solution
rawLocations <- mapM exposedModules visiblePackages
return (Map.unionsWith (++) rawLocations)
allVisible
:: (MonadError String m)
=> Desc.Description
-> Solution.Solution
-> m [(Pkg.Name, V.Version)]
allVisible desc solution =
mapM getVersion visible
where
visible = map fst (Desc.dependencies desc)
getVersion name =
case Map.lookup name solution of
Just version -> return (name, version)
Nothing ->
throwError $
unlines
[ "your " ++ Path.description ++ " file says you depend on package " ++ Pkg.toString name ++ ","
, "but it looks like it is not properly installed. Try running 'elm-package install'."
]
exposedModules
:: (MonadIO m, MonadError String m)
=> (Pkg.Name, V.Version)
-> m (Map.Map Module.Name [(Pkg.Name, V.Version)])
exposedModules packageID@(pkgName, version) =
within (Path.package pkgName version) $ do
description <- Desc.read Path.description
let exposed = Desc.exposed description
return (foldr insert Map.empty exposed)
where
insert moduleName dict =
Map.insert moduleName [packageID] dict
within :: (MonadIO m) => FilePath -> m a -> m a
within directory command =
do root <- liftIO getCurrentDirectory
liftIO (setCurrentDirectory directory)
result <- command
liftIO (setCurrentDirectory root)
return result
-- ERROR MESSAGES
errorNotFound :: Module.Name -> Maybe Module.Name -> String
errorNotFound name maybeParent =
unlines
[ "Error when searching for modules" ++ context ++ ":"
, " Could not find module '" ++ Module.nameToString name ++ "'"
, ""
, "Potential problems could be:"
, " * Misspelled the module name"
, " * Need to add a source directory or new dependency to " ++ Path.description
]
where
context =
case maybeParent of
Nothing -> " exposed by " ++ Path.description
Just parent -> " imported by module '" ++ Module.nameToString parent ++ "'"
errorTooMany :: Module.Name -> Maybe Module.Name -> [CodePath] -> Maybe [(Pkg.Name,V.Version)] -> String
errorTooMany name maybeParent filePaths maybePkgs =
"Error when searching for modules" ++ context ++ ".\n" ++
"Found multiple modules named '" ++ Module.nameToString name ++ "'\n" ++
"Modules with that name were found in the following locations:\n\n" ++
concatMap (\str -> " " ++ str ++ "\n") (paths ++ packages)
where
context =
case maybeParent of
Nothing -> " exposed by " ++ Path.description
Just parent -> " imported by module '" ++ Module.nameToString parent ++ "'"
packages =
map ("package " ++) (Maybe.maybe [] (map (Pkg.toString . fst)) maybePkgs)
paths =
map ("directory " ++) (map extract filePaths)
extract codePath =
case codePath of
Elm path -> path
JS path -> path
errorNameMismatch :: FilePath -> Module.Name -> Module.Name -> String
errorNameMismatch path nameFromPath nameFromSource =
unlines
[ "The module name is messed up for " ++ path
, " According to the file's name it should be " ++ Module.nameToString nameFromPath
, " According to the source code it should be " ++ Module.nameToString nameFromSource
, "Which is it?"
]
| JoeyEremondi/elm-make | src/CrawlPackage.hs | bsd-3-clause | 10,449 | 0 | 17 | 2,647 | 3,013 | 1,547 | 1,466 | 238 | 5 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module InsertDuplicateUpdate where
import Data.List (sort)
import Database.Persist.MySQL
import MyInit
share [mkPersist sqlSettings, mkMigrate "duplicateMigrate"] [persistUpperCase|
Item
name Text sqltype=varchar(80)
description Text
price Double Maybe
quantity Int Maybe
Primary name
deriving Eq Show Ord
|]
specs :: Spec
specs = describe "DuplicateKeyUpdate" $ do
let item1 = Item "item1" "" (Just 3) Nothing
item2 = Item "item2" "hello world" Nothing (Just 2)
items = [item1, item2]
describe "insertOnDuplicateKeyUpdate" $ do
it "inserts appropriately" $ db $ do
deleteWhere ([] :: [Filter Item])
insertOnDuplicateKeyUpdate item1 [ItemDescription =. "i am item 1"]
Just item <- get (ItemKey "item1")
item @== item1
it "performs only updates given if record already exists" $ db $ do
deleteWhere ([] :: [Filter Item])
let newDescription = "I am a new description"
_ <- insert item1
insertOnDuplicateKeyUpdate
(Item "item1" "i am inserted description" (Just 1) (Just 2))
[ItemDescription =. newDescription]
Just item <- get (ItemKey "item1")
item @== item1 { itemDescription = newDescription }
describe "insertManyOnDuplicateKeyUpdate" $ do
it "inserts fresh records" $ db $ do
deleteWhere ([] :: [Filter Item])
insertMany_ items
let newItem = Item "item3" "fresh" Nothing Nothing
insertManyOnDuplicateKeyUpdate
(newItem : items)
[copyField ItemDescription]
[]
dbItems <- map entityVal <$> selectList [] []
sort dbItems @== sort (newItem : items)
it "updates existing records" $ db $ do
deleteWhere ([] :: [Filter Item])
insertMany_ items
insertManyOnDuplicateKeyUpdate
items
[]
[ItemQuantity +=. Just 1]
it "only copies passing values" $ db $ do
deleteWhere ([] :: [Filter Item])
insertMany_ items
let newItems = map (\i -> i { itemQuantity = Just 0, itemPrice = fmap (*2) (itemPrice i) }) items
postUpdate = map (\i -> i { itemPrice = fmap (*2) (itemPrice i) }) items
insertManyOnDuplicateKeyUpdate
newItems
[ copyUnlessEq ItemQuantity (Just 0)
, copyField ItemPrice
]
[]
dbItems <- sort . fmap entityVal <$> selectList [] []
dbItems @== sort postUpdate
it "inserts without modifying existing records if no updates specified" $ db $ do
let newItem = Item "item3" "hi friends!" Nothing Nothing
deleteWhere ([] :: [Filter Item])
insertMany_ items
insertManyOnDuplicateKeyUpdate
(newItem : items)
[]
[]
dbItems <- sort . fmap entityVal <$> selectList [] []
dbItems @== sort (newItem : items)
| gbwey/persistent | persistent-mysql/test/InsertDuplicateUpdate.hs | mit | 3,080 | 0 | 24 | 821 | 862 | 415 | 447 | 72 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.PrettyUtils
-- Copyright : (c) The University of Glasgow 2004
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- Utilities for pretty printing.
{-# OPTIONS_HADDOCK hide #-}
module Distribution.PrettyUtils (
Separator,
-- * Internal
showFilePath,
showToken,
showTestedWith,
showFreeText,
indentWith,
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Compiler (CompilerFlavor)
import Distribution.Version (VersionRange)
import Distribution.Text (disp)
import Text.PrettyPrint (Doc, text, vcat, (<+>))
type Separator = ([Doc] -> Doc)
showFilePath :: FilePath -> Doc
showFilePath "" = mempty
showFilePath x = showToken x
showToken :: String -> Doc
showToken str
| not (any dodgy str) && not (null str) = text str
| otherwise = text (show str)
where
dodgy c = isSpace c || c == ','
showTestedWith :: (CompilerFlavor, VersionRange) -> Doc
showTestedWith (compiler, vr) = text (show compiler) <+> disp vr
-- | Pretty-print free-format text, ensuring that it is vertically aligned,
-- and with blank lines replaced by dots for correct re-parsing.
showFreeText :: String -> Doc
showFreeText "" = mempty
showFreeText s = vcat [text (if null l then "." else l) | l <- lines_ s]
-- | 'lines_' breaks a string up into a list of strings at newline
-- characters. The resulting strings do not contain newlines.
lines_ :: String -> [String]
lines_ [] = [""]
lines_ s = let (l, s') = break (== '\n') s
in l : case s' of
[] -> []
(_:s'') -> lines_ s''
-- | the indentation used for pretty printing
indentWith :: Int
indentWith = 4
| mydaum/cabal | Cabal/Distribution/PrettyUtils.hs | bsd-3-clause | 1,973 | 0 | 12 | 541 | 448 | 249 | 199 | 36 | 2 |
import StackTest
main :: IO ()
main = do
stackErr ["build", "--stack-yaml", "as-extra-dep.yaml", "--dry-run"]
stack ["build", "--stack-yaml", "as-snapshot.yaml", "--dry-run"]
| juhp/stack | test/integration/tests/stackage-3185-ignore-bounds-in-snapshot/Main.hs | bsd-3-clause | 180 | 0 | 8 | 24 | 55 | 30 | 25 | 5 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Some fields spiced up with jQuery UI.
module Yesod.Form.Jquery
( YesodJquery (..)
, jqueryDayField
, jqueryDatePickerDayField
, jqueryAutocompleteField
, jqueryAutocompleteField'
, googleHostedJqueryUiCss
, JqueryDaySettings (..)
, Default (..)
) where
import Yesod.Core
import Yesod.Form
import Data.Time (Day)
import Data.Default
import Text.Hamlet (shamlet)
import Text.Julius (julius, rawJS)
import Data.Text (Text, pack, unpack)
import Data.Monoid (mconcat)
-- | Gets the Google hosted jQuery UI 1.8 CSS file with the given theme.
googleHostedJqueryUiCss :: Text -> Text
googleHostedJqueryUiCss theme = mconcat
[ "//ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/"
, theme
, "/jquery-ui.css"
]
class YesodJquery a where
-- | The jQuery Javascript file. Note that in upgrades to this library, the
-- version of jQuery referenced, or where it is downloaded from, may be
-- changed without warning. If you are relying on a specific version of
-- jQuery, you should give an explicit URL instead of relying on the
-- default value.
--
-- Currently, the default value is jQuery 1.7 from Google\'s CDN.
urlJqueryJs :: a -> Either (Route a) Text
urlJqueryJs _ = Right "//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"
-- | The jQuery UI 1.8 Javascript file.
urlJqueryUiJs :: a -> Either (Route a) Text
urlJqueryUiJs _ = Right "//ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
-- | The jQuery UI 1.8 CSS file; defaults to cupertino theme.
urlJqueryUiCss :: a -> Either (Route a) Text
urlJqueryUiCss _ = Right $ googleHostedJqueryUiCss "cupertino"
-- | jQuery UI time picker add-on.
urlJqueryUiDateTimePicker :: a -> Either (Route a) Text
urlJqueryUiDateTimePicker _ = Right "http://github.com/gregwebs/jquery.ui.datetimepicker/raw/master/jquery.ui.datetimepicker.js"
jqueryDayField :: (RenderMessage site FormMessage, YesodJquery site) => JqueryDaySettings -> Field (HandlerT site IO) Day
jqueryDayField = flip jqueryDayField' "date"
-- | Use jQuery's datepicker as the underlying implementation.
--
-- Since 1.4.3
jqueryDatePickerDayField :: (RenderMessage site FormMessage, YesodJquery site) => JqueryDaySettings -> Field (HandlerT site IO) Day
jqueryDatePickerDayField = flip jqueryDayField' "text"
jqueryDayField' :: (RenderMessage site FormMessage, YesodJquery site) => JqueryDaySettings -> Text -> Field (HandlerT site IO) Day
jqueryDayField' jds inputType = Field
{ fieldParse = parseHelper $ maybe
(Left MsgInvalidDay)
Right
. readMay
. unpack
, fieldView = \theId name attrs val isReq -> do
toWidget [shamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="#{inputType}" :isReq:required="" value="#{showVal val}">
|]
addScript' urlJqueryJs
addScript' urlJqueryUiJs
addStylesheet' urlJqueryUiCss
toWidget [julius|
$(function(){
var i = document.getElementById("#{rawJS theId}");
if (i.type != "date") {
$(i).datepicker({
dateFormat:'yy-mm-dd',
changeMonth:#{jsBool $ jdsChangeMonth jds},
changeYear:#{jsBool $ jdsChangeYear jds},
numberOfMonths:#{rawJS $ mos $ jdsNumberOfMonths jds},
yearRange:#{toJSON $ jdsYearRange jds}
});
}
});
|]
, fieldEnctype = UrlEncoded
}
where
showVal = either id (pack . show)
jsBool True = toJSON True
jsBool False = toJSON False
mos (Left i) = show i
mos (Right (x, y)) = concat
[ "["
, show x
, ","
, show y
, "]"
]
jqueryAutocompleteField :: (RenderMessage site FormMessage, YesodJquery site)
=> Route site -> Field (HandlerT site IO) Text
jqueryAutocompleteField = jqueryAutocompleteField' 2
jqueryAutocompleteField' :: (RenderMessage site FormMessage, YesodJquery site)
=> Int -- ^ autocomplete minimum length
-> Route site
-> Field (HandlerT site IO) Text
jqueryAutocompleteField' minLen src = Field
{ fieldParse = parseHelper $ Right
, fieldView = \theId name attrs val isReq -> do
toWidget [shamlet|
$newline never
<input id="#{theId}" name="#{name}" *{attrs} type="text" :isReq:required="" value="#{either id id val}" .autocomplete>
|]
addScript' urlJqueryJs
addScript' urlJqueryUiJs
addStylesheet' urlJqueryUiCss
toWidget [julius|
$(function(){$("##{rawJS theId}").autocomplete({source:"@{src}",minLength:#{toJSON minLen}})});
|]
, fieldEnctype = UrlEncoded
}
addScript' :: (HandlerSite m ~ site, MonadWidget m) => (site -> Either (Route site) Text) -> m ()
addScript' f = do
y <- getYesod
addScriptEither $ f y
addStylesheet' :: (MonadWidget m, HandlerSite m ~ site)
=> (site -> Either (Route site) Text)
-> m ()
addStylesheet' f = do
y <- getYesod
addStylesheetEither $ f y
readMay :: Read a => String -> Maybe a
readMay s = case reads s of
(x, _):_ -> Just x
[] -> Nothing
data JqueryDaySettings = JqueryDaySettings
{ jdsChangeMonth :: Bool
, jdsChangeYear :: Bool
, jdsYearRange :: String
, jdsNumberOfMonths :: Either Int (Int, Int)
}
instance Default JqueryDaySettings where
def = JqueryDaySettings
{ jdsChangeMonth = False
, jdsChangeYear = False
, jdsYearRange = "c-10:c+10"
, jdsNumberOfMonths = Left 1
}
| pikajude/yesod | yesod-form/Yesod/Form/Jquery.hs | mit | 5,752 | 0 | 12 | 1,401 | 1,134 | 605 | 529 | 104 | 3 |
{-# LANGUAGE GADTs, KindSignatures #-}
-- See Trac #301
-- This particular one doesn't use GADTs per se,
-- but it does use dictionaries in constructors
module Expr1 where
data Expr :: * -> * where -- Not a GADT at all
Const :: Show a => a -> Expr a
-- Note the Show constraint here
Var :: Var a -> Expr a
newtype Var a = V String
instance Show (Var a) where show (V s) = s
--------------------------
e1 :: Expr Int
e1 = Const 42
e2 :: Expr Bool
e2 = Const True
e3 :: Expr Integer
e3 = Var (V "mersenne100")
--------------------------
eval :: Expr a -> a
eval (Const c) = c
eval (Var v) = error ("free variable `" ++ shows v "'")
{-
Up to here, everything works nicely:
\begin{verbatim}
*Expr0> eval e1
42
*Expr0> eval e2
True
*Expr1> eval e3
*** Exception: free variable `mersenne100'
\end{verbatim}
But let us now try to define a |shows| function.
In the following, without the type signature we get:
\begin{verbatim}
*Expr1> :t showsExpr
showsExpr :: forall a. (Show a) => Expr a -> String -> String
*Expr1> showsExpr e1 ""
"42"
*Expr1> showsExpr e2 ""
"True"
*Expr1> showsExpr e3 ""
"mersenne100"
\end{verbatim}
However, in the last case, the instance |Show Integer| was not used,
so should not have been required.
Therefore I would expect it to work as it is now, i.e.,
with the type signature:
-}
showsExpr :: Expr a -> ShowS
showsExpr (Const c) = shows c
showsExpr (Var v) = shows v
{-
We used to get a complaint about the |Const| alternative (then line
63) that documents that the constraint in the type of |Const| must
have been ignored:
No instance for (Show a)
arising from use of `shows' at Expr1.lhs:63:22-26
Probable fix: add (Show a) to the type signature(s) for `showsExpr'
In the definition of `showsExpr': showsExpr (Const c) = shows c
-}
| hferreiro/replay | testsuite/tests/gadt/karl1.hs | bsd-3-clause | 1,983 | 0 | 8 | 549 | 251 | 132 | 119 | 19 | 1 |
-- Crashed GHC 6.12
module T4165 where
import Language.Haskell.TH
class Numeric a where
fromIntegerNum :: a
fromIntegerNum = undefined
ast :: Q [Dec]
ast = [d|
instance Numeric Int
|]
| ezyang/ghc | testsuite/tests/quotes/T4169.hs | bsd-3-clause | 203 | 0 | 6 | 49 | 50 | 31 | 19 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module DB.Model.Internal.TypeCast where
import Data.Aeson
import Database.HDBC
import Data.Scientific as S (scientific, floatingOrInteger)
import Data.Text as T (pack, unpack)
import Data.ByteString.Char8 as B (pack, unpack)
sql2aeson :: SqlValue -> Value
sql2aeson (SqlString v) = toJSON v
sql2aeson (SqlInteger v) = toJSON v
sql2aeson (SqlByteString v) = toJSON $ B.unpack v
sql2aeson (SqlBool v) = toJSON v
sql2aeson (SqlInt64 v) = toJSON v
sql2aeson SqlNull = Null
sql2aeson v = error $ "TypeCast.hs: " ++ show v
aeson2sql :: Value -> SqlValue
aeson2sql (String v) = toSql $ B.pack $ T.unpack v
aeson2sql (Number v) =
case floatingOrInteger v of
Left float -> toSql $ (float :: Double)
Right int -> toSql $ (int :: Integer)
aeson2sql (Bool v) = toSql v
aeson2sql Null = SqlNull
aeson2sql v = error $ "TypeCast.hs: " ++ show v
| YLiLarry/db-model | src/DB/Model/Internal/TypeCast.hs | mit | 953 | 0 | 9 | 223 | 333 | 175 | 158 | 24 | 2 |
-- Ben Eggers <ben.eggers36@gmail.com>
-- Problems 31-41
module Arithmetic where
import Data.Numbers.Primes (primes)
-- Problem 31
isPrime :: Int -> Bool
isPrime n = null [x | x <- [2..floor $ sqrt $ fromIntegral n], n `mod` x == 0]
-- Problem 32
gcd' :: Int -> Int -> Int
gcd' n m = if n == m then n else gcd (max n m `mod` min n m) (min n m)
-- Problem 33
coprime :: Int -> Int -> Bool
coprime n m = gcd n m == 1
-- Problem 34
totient :: Int -> Int
totient n = length [x | x <- [1..n], coprime x n]
-- Problem 35
primeFactors :: Int -> [Int]
primeFactors n = helper n []
where helper 1 acc = reverse acc
helper n acc = let x = head [q | q <- [2..n], isPrime q && n `mod` q == 0]
in helper (quot n x) (x : acc)
-- Problem 36
primeFactorsMult :: Int -> [(Int, Int)]
primeFactorsMult n = helper (primeFactors n) []
where helper [] acc = reverse acc
helper (x:xs) acc = helper
(dropWhile (==x) xs)
((x, (length (takeWhile (==x) xs) + 1)):acc)
-- Problem 37
totientImproved :: Int -> Int
totientImproved n = helper (primeFactorsMult n) 1
where helper [] acc = acc
helper ((f, m):facs) acc = helper facs (acc * (f - 1) * f ^ (m - 1))
-- Problem 39
primesR :: Int -> Int -> [Int]
primesR b t = takeWhile (<=t) . dropWhile (<b) $ primes
-- Problem 40
goldbach :: Int -> (Int, Int)
goldbach n
| n `mod` 2 == 1 = error "What the hell man, give me an even integer."
| otherwise = helper n primes
where helper n (p:ps) = if isPrime $ n - p
then (p, n - p)
else helper n ps | BenedictEggers/99problems | src/Arithmetic.hs | mit | 1,657 | 0 | 17 | 507 | 732 | 389 | 343 | 34 | 2 |
module Handler.BuildPlan where
import Import
--import Stackage.Types
--import Stackage.Database
getBuildPlanR :: SnapName -> Handler TypedContent
getBuildPlanR _slug = track "Handler.BuildPlan.getBuildPlanR" $ do
error "temporarily disabled, please open on issue on https://github.com/fpco/stackage-server/issues/ if you need it"
{-
fullDeps <- (== Just "true") <$> lookupGetParam "full-deps"
spec <- parseSnapshotSpec $ toPathPiece slug
let set = setShellCommands simpleCommands
$ setSnapshot spec
$ setFullDeps fullDeps
defaultSettings
packages <- lookupGetParams "package" >>= mapM simpleParse
when (null packages) $ invalidArgs ["Must provide at least one package"]
toInstall <- liftIO $ getBuildPlan set packages
selectRep $ do
provideRep $ return $ toSimpleText toInstall
provideRep $ return $ toJSON toInstall
provideRepType "application/x-sh" $ return $ toShellScript set toInstall
-}
| fpco/stackage-server | src/Handler/BuildPlan.hs | mit | 997 | 0 | 8 | 215 | 45 | 24 | 21 | 5 | 1 |
-- | Tutorial01 from open-tutorials.org adapted ported to Haskell.
module Main where
import Common.Window (untilClosed)
import Graphics.Rendering.OpenGL
import qualified Graphics.UI.GLFW as GLFW
main :: IO ()
main = do
True <- GLFW.init
GLFW.windowHint $ GLFW.WindowHint'Samples 4
GLFW.windowHint $ GLFW.WindowHint'ContextVersionMajor 3
GLFW.windowHint $ GLFW.WindowHint'ContextVersionMinor 3
GLFW.windowHint $ GLFW.WindowHint'OpenGLForwardCompat True
GLFW.windowHint $ GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core
-- Open a window and create its OpenGL context
w@(Just window) <- GLFW.createWindow 1024 768 "Tutorial 01" Nothing Nothing
GLFW.makeContextCurrent w
-- Ensure we can capture the escape key being pressed below
GLFW.setStickyKeysInputMode window GLFW.StickyKeysInputMode'Enabled
-- Dark blue background
clearColor $= Color4 0 0 0.4 0
window `untilClosed` (\_ -> do
clear [ ColorBuffer ]
GLFW.swapBuffers window)
GLFW.terminate
| kosmoskatten/opengl-tutorial | src/Tutorial01/Tutorial01.hs | mit | 996 | 0 | 13 | 157 | 233 | 115 | 118 | 20 | 1 |
{-# OPTIONS_GHC -freduction-depth=50 #-}
{- | This module defines the functions necessary to transform an 'AST'
into a 'String' containing output for the Coq proof assistant.
Definitions are encoded using a locally nameless representation. -}
module CoqLNOutput ( coqOfAST ) where
import Data.Graph ( SCC(..), stronglyConnComp )
import Text.Printf ( printf )
import AST
import ASTAnalysis
import ComputationMonad
import CoqLNOutputCommon
import CoqLNOutputDefinitions
import CoqLNOutputThmDegree
import CoqLNOutputThmFv
import CoqLNOutputThmLc
import CoqLNOutputThmOpenClose
import CoqLNOutputThmOpenClose2
import CoqLNOutputThmSize
import CoqLNOutputThmSwap
import CoqLNOutputThmSubst
import MyLibrary ( nmap )
{- ----------------------------------------------------------------------- -}
{- * Exported functionality -}
{- | Generates Coq output for the given 'AST'. The first argument is
the name of the library for the output generated by Ott. The
second is the directory name for a @LoadPath@ declaration. -}
coqOfAST :: Maybe String -> Maybe String -> AST -> M String
coqOfAST ott loadpath ast =
do { bodyStrs <- mapM (local . processBody aa) nts
; closeStrs <- mapM (local . processClose aa) nts
; degreeStrs <- mapM (local . processDegree aa) nts
; lcStrs <- mapM (local . processLc aa) nts
; ntStrs <- mapM (local . processNt aa) nts
; sizeStrs <- mapM (local . processSize aa) nts
; _swapStrs <- mapM (local . processSwap aa) nts
; tacticStrs <- local $ processTactics aa
; degree_thms <- degreeThms aa nts
; fv_thms <- fvThms aa nts
; lc_thms <- lcThms aa nts
; open_close_thms <- openCloseThms aa nts
; open_close_thms2 <- openCloseThms2 aa nts
; size_thms <- sizeThms aa nts
; _swap_thms <- swapThms aa nts
; subst_thms <- substThms aa nts
; return $ (case loadpath of
Nothing -> ""
Just s -> "Add LoadPath \"" ++ s ++ "\".\n") ++
"Require Import Coq.Arith.Wf_nat.\n\
\Require Import Coq.Logic.FunctionalExtensionality.\n\
\Require Import Coq.Program.Equality.\n\
\\n\
\Require Export Metalib.Metatheory.\n\
\Require Export Metalib.LibLNgen.\n" ++
(case ott of
Nothing -> ""
Just s -> "\nRequire Export " ++ s ++ ".\n") ++
"\n\
\(** NOTE: Auxiliary theorems are hidden in generated documentation.\n\
\ In general, there is a [_rec] version of every lemma involving\n\
\ [open] and [close]. *)\n\
\\n\
\\n" ++
coqSep ++ "(** * Induction principles for nonterminals *)\n\n" ++
concat ntStrs ++ "\n" ++
coqSep ++ "(** * Close *)\n\n" ++
concat closeStrs ++ "\n" ++
coqSep ++ "(** * Size *)\n\n" ++
concat sizeStrs ++ "\n" ++
coqSep ++ "(** * Degree *)\n\
\\n\
\(** These define only an upper bound, not a strict upper bound. *)\n\
\\n" ++
concat degreeStrs ++ "\n" ++
coqSep ++ "(** * Local closure (version in [Set], induction principles) *)\n\n" ++
concat lcStrs ++ "\n" ++
coqSep ++ "(** * Body *)\n\n" ++
concat bodyStrs ++ "\n" ++
-- coqSep ++ "(** * Swapping *)\n\n" ++
-- concat swapStrs ++ "\n" ++
coqSep ++ "(** * Tactic support *)\n\n" ++
tacticStrs ++ "\n" ++
coqSep ++ "(** * Theorems about [size] *)\n\n" ++
size_thms ++
coqSep ++ "(** * Theorems about [degree] *)\n\n" ++
degree_thms ++
coqSep ++ "(** * Theorems about [open] and [close] *)\n\n" ++
open_close_thms ++
coqSep ++ "(** * Theorems about [lc] *)\n\n" ++
lc_thms ++
coqSep ++ "(** * More theorems about [open] and [close] *)\n\n" ++
open_close_thms2 ++
coqSep ++ "(** * Theorems about [fv] *)\n\n" ++
fv_thms ++
coqSep ++ "(** * Theorems about [subst] *)\n\n" ++
subst_thms ++
-- coqSep ++ "(** * Theorems about [swap] *)\n\n" ++
-- swap_thms ++
coqSep ++ printf "(** * \"Restore\" tactics *)\n\
\\n\
\Ltac %s ::= auto; tauto.\n\
\Ltac %s ::= fail.\n"
defaultAuto
defaultAutoRewr
}
where
fixSCC (AcyclicSCC n) = [canon n]
fixSCC (CyclicSCC ns) = nmap canon ns
aa = analyzeAST ast
canon = canonRoot aa
nts = reverse $ nmap fixSCC $ stronglyConnComp $ ntGraph aa
| plclub/lngen | src/CoqLNOutput.hs | mit | 5,275 | 0 | 67 | 2,047 | 800 | 404 | 396 | 83 | 4 |
-- | Basic conversions and conversionals. Just enough to embed a Sequent calculus.
module BootstrapConversions where
import Control.Monad
import Data.Maybe
import Bootstrap hiding (matchMP, matchMPInst)
import Utils
-- | Given ⊦ P → Q and ⊦ R, attempt to match P and R, and then apply MP using an
-- instantiation for the other variables.
matchMPInst :: (Eq a, Eq b, Show b) =>
(a -> Term b) -> Theorem a -> Theorem b -> [Theorem b]
matchMPInst inst imp ant =
case (termOfTheorem imp, termOfTheorem ant) of
(p :=>: q, p') ->
maybeToList (fmap (\is -> mp (instM inst is imp) ant) (match p p'))
_ -> []
-- | Conversions wrap functions which take terms and derive equations. Each
-- equation has an lhs which is the original term.
newtype Conv a = Conv { applyC :: Term a -> [Theorem a] }
-- | Use a conversion to rewrite a theorem.
convMP :: (Eq a, Show a) => Conv a -> Theorem a -> [Theorem a]
convMP c thm = do eq <- applyC c (termOfTheorem thm)
let (l,r) = destEq (termOfTheorem eq)
pure (mp (mp (inst2 l r eqMP) eq) thm)
-- | Apply a conversion to the consequent of a conditional.
conclC :: (Eq a, Show a) => Conv a -> Conv a
conclC (Conv c) = Conv f
where f (p :=>: q) = c q >>= matchMPInst (const p) substRight
f _ = []
-- | Apply one conversion after another.
thenC :: (Eq a, Show a) => Conv a -> Conv a -> Conv a
thenC c c' = Conv f
where f t = do thm <- applyC c t
let (x,y) = destEq (termOfTheorem thm)
thm' <- applyC c' y
let (y',z) = destEq (termOfTheorem thm')
unless (y == y') (error "thenC")
pure (mp (mp (inst3 x y z trans) thm) thm')
-- | The zero for orConv and identity for thenConv: always succeeds.
allC :: Conv a
allC = Conv (\t -> return $ inst1 t reflEq)
-- | The identity for orConv and zero for thenConv: always fails.
failC :: Conv a
failC = Conv (const [])
-- | Apply all conversions in a sequence.
everyC :: (Eq a, Show a) => [Conv a] -> Conv a
everyC = foldl thenC allC
-- | Swap the first two hypotheses of a conditional.
swapC :: Conv a
swapC = Conv c
where c (p :=>: q :=>: r) = return $ inst3 p q r swapT
c _ = []
-- | Uncurry the first two hypotheses of a conditional
uncurry2 :: Conv a
uncurry2 = Conv c
where c (p :=>: q :=>: r) = return $ inst3 p q r Bootstrap.uncurry
c _ = []
-- | A conversion to switch the lhs and rhs of an equation.
symC :: Eq a => Conv a
symC = Conv c
where c (Not ((p :=>: q) :=>: Not (r :=>: s))) | p == s && q == r =
return $ inst2 p q symEq
c _ = []
-- | Curry the first hypothesis
curry2 :: Conv a
curry2 = Conv c
where c (Not (p :=>: Not q) :=>: r) =
return $ inst3 p q r (head $ convMP symC Bootstrap.uncurry)
c _ = []
| Chattered/proplcf | BootstrapConversions.hs | mit | 2,943 | 0 | 15 | 903 | 1,038 | 525 | 513 | 53 | 2 |
-- Persistent Bugger.
-- http://www.codewars.com/kata/55bf01e5a717a0d57e0000ec/
module Codewars.G.Persistence where
import Data.Char (digitToInt)
persistence :: Int -> Int
persistence n | 10 < n = 0
| otherwise = (+1) . persistence . product . map digitToInt . show $ n
| gafiatulin/codewars | src/6 kyu/Persistence.hs | mit | 287 | 0 | 11 | 56 | 82 | 44 | 38 | 5 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UnicodeSyntax #-}
module Data.BEncode.Types
( Value (..)
, Dict
, Parser
, parse
, FromBEncode (..)
, (.:)
, (.:?)
, (.!=)
, ToBEncode (..)
)
where
import Control.Applicative (Alternative (..))
import Control.Monad (MonadPlus (..))
import Data.ByteString (ByteString)
import qualified Data.ByteString.UTF8 as BSU8
import Data.Int
import Data.Map (Map)
import qualified Data.Map as Map (lookup)
import Data.Word
--------------------------------------------------------------------------------
data Value
= String ByteString
| Integer Integer
| List [Value]
| Dict Dict
deriving
(Eq, Show)
type Dict = Map ByteString Value
--------------------------------------------------------------------------------
data Parser α
= Parser
{ runParser ∷ ∀r. (String → r) → (α → r) → r
}
instance Functor Parser where
fmap g p = Parser $ \fK sK → runParser p fK (sK . g)
instance Applicative Parser where
pure x = Parser $ \_ sK → sK x
pG <*> pX = Parser $ \fK sK → runParser pG fK (\g → runParser pX fK (sK . g))
instance Monad Parser where
return = pure
pX >>= gP = Parser $ \fK sK → runParser pX fK (\x → runParser (gP x) fK sK)
fail s = Parser $ \fK _ → fK s
instance Alternative Parser where
empty = fail "empty"
pX <|> pY = Parser $ \fK sK → runParser pX (const $ runParser pY fK sK) sK
instance MonadPlus Parser where
mzero = fail "mzero"
mplus = (<|>)
parse ∷ Parser α → Either String α
parse p = runParser p Left Right
--------------------------------------------------------------------------------
class FromBEncode α where
parseBEncode ∷ Value → Parser α
instance FromBEncode Value where
parseBEncode = pure
instance FromBEncode ByteString where
parseBEncode (String s) = Parser $ \_ sK → sK s
parseBEncode _ = fail "Expected a String"
instance {-# OVERLAPPING #-} FromBEncode [Char] where
parseBEncode = fmap BSU8.toString . parseBEncode
instance FromBEncode Int where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Int8 where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Int16 where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Int32 where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Int64 where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Word where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Word8 where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Word16 where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Word32 where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Word64 where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Integer where
parseBEncode (Integer i) = Parser $ \_ sK → sK i
parseBEncode _ = fail "Expected an Integer"
instance FromBEncode Float where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode Double where
parseBEncode = fmap fromInteger . parseBEncode
instance FromBEncode α ⇒ FromBEncode [α] where
parseBEncode (List vs) = traverse parseBEncode vs
parseBEncode _ = fail "Expected a List"
instance FromBEncode α ⇒ FromBEncode (Map ByteString α) where
parseBEncode (Dict d) = traverse parseBEncode d
(.:) ∷ FromBEncode α ⇒ Dict → ByteString → Parser α
d .: x = maybe (fail $ "Missing key " ++ show x) parseBEncode $ Map.lookup x d
(.:?) ∷ FromBEncode α ⇒ Dict → ByteString → Parser (Maybe α)
d .:? x = maybe (pure Nothing) (fmap Just . parseBEncode) $ Map.lookup x d
(.!=) ∷ Parser (Maybe α) → α → Parser α
(.!=) p x = p >>= maybe (pure x) pure
--------------------------------------------------------------------------------
class ToBEncode α where
toBEncode ∷ α → Value
instance ToBEncode Value where
toBEncode = id
instance ToBEncode ByteString where
toBEncode = String
instance {-# OVERLAPPING #-} ToBEncode [Char] where
toBEncode = String . BSU8.fromString
instance ToBEncode Int where
toBEncode = Integer . fromIntegral
instance ToBEncode Int8 where
toBEncode = Integer . fromIntegral
instance ToBEncode Int16 where
toBEncode = Integer . fromIntegral
instance ToBEncode Int32 where
toBEncode = Integer . fromIntegral
instance ToBEncode Int64 where
toBEncode = Integer . fromIntegral
instance ToBEncode Word where
toBEncode = Integer . fromIntegral
instance ToBEncode Word8 where
toBEncode = Integer . fromIntegral
instance ToBEncode Word16 where
toBEncode = Integer . fromIntegral
instance ToBEncode Word32 where
toBEncode = Integer . fromIntegral
instance ToBEncode Word64 where
toBEncode = Integer . fromIntegral
instance ToBEncode Integer where
toBEncode = Integer
instance ToBEncode α ⇒ ToBEncode [α] where
toBEncode = List . map toBEncode
instance ToBEncode α ⇒ ToBEncode (Map ByteString α) where
toBEncode = Dict . fmap toBEncode
| drdo/swarm-bencode | Data/BEncode/Types.hs | mit | 5,064 | 0 | 13 | 899 | 1,549 | 815 | 734 | 130 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE QuasiQuotes #-}
module Graphics.Urho3D.UI.UIBatch(
UIBatch(..)
, PODVectorUIBatch
, HasElement(..)
, HasBlendMode(..)
, HasScissor(..)
, HasTexture(..)
, HasInvTextureSize(..)
, HasColor(..)
, HasVertexData(..)
, HasVertexStart(..)
, HasVertexEnd(..)
, HasUseGradient(..)
, uiBatchContext
, uiBatchPosAdjust
, uiBatchSetColor
, uiBatchSetDefaultColor
, uiBatchAddQuad
, uiBatchAddQuadMatrix
, uiBatchAddQuadTexture
, uiBatchAddQuadFreeform
, uiBatchAddQuadFreeformMatrix
, uiBatchMerge
, batchMerge
, uiBatchGetInterpolatedColor
, uiBatchAddOrMerge
, batchAddOrMerge
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import qualified Data.Vector.Unboxed as V
import Data.Monoid
import Foreign
import GHC.Generics
import Graphics.Urho3D.Container.ForeignVector
import Graphics.Urho3D.Container.Vector
import Graphics.Urho3D.Creatable
import Graphics.Urho3D.Monad
import Graphics.Urho3D.UI.Internal.UIBatch
import System.IO.Unsafe (unsafePerformIO)
import Text.RawString.QQ
import Graphics.Urho3D.Container.Vector.Common
import Graphics.Urho3D.Graphics.Texture
import Graphics.Urho3D.Graphics.Defs
import Graphics.Urho3D.Math.Color
import Graphics.Urho3D.Math.Matrix3x4
import Graphics.Urho3D.Math.Rect
import Graphics.Urho3D.Math.Vector2
import Graphics.Urho3D.Math.Vector3
import Graphics.Urho3D.UI.Element
C.context (C.cppCtx
<> uiBatchCntx
<> colorContext
<> matrix3x4Context
<> rectContext
<> textureContext
<> uiElementContext
<> vector2Context
<> vector3Context
<> vectorContext
)
C.include "<Urho3D/Container/Ptr.h>"
C.include "<Urho3D/UI/UIBatch.h>"
C.using "namespace Urho3D"
C.verbatim "typedef PODVector<float> PODVectorFloat;"
C.verbatim "typedef PODVector<UIBatch> PODVectorUIBatch;"
C.verbatim [r|
template <class T>
class Traits
{
public:
struct AlignmentFinder
{
char a;
T b;
};
enum {AlignmentOf = sizeof(AlignmentFinder) - sizeof(T)};
};
|]
simplePODVector "UIBatch"
uiBatchContext :: C.Context
uiBatchContext = uiBatchCntx
-- | Construction options for 'UIBatch'
data UIBatchCreate = UIBatchDefault -- ^ Construct with defaults
-- | Construct
| UIBatchConstruct {
_uiBatchConstructElement :: !(Ptr UIElement)
, _uiBatchConstructBlendMode :: !BlendMode
, _uiBatchConstructScissor :: !IntRect
, _uiBatchConstructTexture :: !(Ptr Texture)
, _uiBatchConstructVertexData :: !(V.Vector Float)
}
deriving (Show, Generic)
-- | Note that vertex data vector is copied when 'UIBatchConstruct' is used. The
-- vector is freed in 'deleteObject', so the deleteObject implementation might be
-- unsafe to use on non-haskell created 'UIBatch'.
instance Creatable (Ptr UIBatch) where
type CreationOptions (Ptr UIBatch) = UIBatchCreate
newObject UIBatchDefault = liftIO $ [C.exp| UIBatch* { new UIBatch() } |]
newObject UIBatchConstruct{..} = liftIO $
with _uiBatchConstructScissor $ \_uiBatchConstructScissor' ->
withForeignVector () _uiBatchConstructVertexData $ \_uiBatchConstructVertexData' -> do
let _uiBatchConstructBlendMode' = fromIntegral . fromEnum $ _uiBatchConstructBlendMode
[C.exp| UIBatch* { new UIBatch(
$(UIElement* _uiBatchConstructElement)
, (BlendMode)$(int _uiBatchConstructBlendMode')
, *$(IntRect* _uiBatchConstructScissor')
, $(Texture* _uiBatchConstructTexture)
, new PODVectorFloat(*$(PODVectorFloat* _uiBatchConstructVertexData'))
) } |]
deleteObject ptr = liftIO $ [C.block| void {
delete $(UIBatch* ptr)->vertexData_;
delete $(UIBatch* ptr);
} |]
-- | Note that vertex data vector is copied when poked. Use 'deleteObject' to free memory
-- including the copied data.
instance Storable UIBatch where
sizeOf _ = fromIntegral $ [C.pure| int { (int)sizeof(UIBatch) } |]
alignment _ = fromIntegral $ [C.pure| int { (int)Traits<UIBatch>::AlignmentOf } |]
peek ptr = do
_uIBatchElement <- [C.exp| UIElement* {$(UIBatch* ptr)->element_} |]
_uIBatchBlendMode <- toEnum . fromIntegral <$> [C.exp| int {(int)$(UIBatch* ptr)->blendMode_} |]
_uIBatchScissor <- peek =<< [C.exp| IntRect* {&$(UIBatch* ptr)->scissor_} |]
_uIBatchTexture <- [C.exp| Texture* {$(UIBatch* ptr)->texture_} |]
_uIBatchInvTextureSize <- peek =<< [C.exp| Vector2* {&$(UIBatch* ptr)->invTextureSize_} |]
_uIBatchColor <- fromIntegral <$> [C.exp| unsigned int {$(UIBatch* ptr)->color_} |]
_uIBatchVertexData <- peekForeignVectorAs =<< [C.exp| PODVectorFloat* {$(UIBatch* ptr)->vertexData_} |]
_uIBatchVertexStart <- fromIntegral <$> [C.exp| unsigned int {$(UIBatch* ptr)->vertexStart_} |]
_uIBatchVertexEnd <- fromIntegral <$> [C.exp| unsigned int {$(UIBatch* ptr)->vertexEnd_} |]
_uIBatchUseGradient <- toBool <$> [C.exp| int {(int)$(UIBatch* ptr)->useGradient_} |]
return UIBatch{..}
poke ptr UIBatch{..} =
with _uIBatchScissor $ \_uIBatchScissor' ->
with _uIBatchInvTextureSize $ \_uIBatchInvTextureSize' ->
withForeignVector () _uIBatchVertexData $ \_uIBatchVertexData' -> do
let _uIBatchBlendMode' = fromIntegral . fromEnum $ _uIBatchBlendMode
_uIBatchColor' = fromIntegral _uIBatchColor
_uIBatchVertexStart' = fromIntegral _uIBatchVertexStart
_uIBatchVertexEnd' = fromIntegral _uIBatchVertexEnd
_uIBatchUseGradient' = fromBool _uIBatchUseGradient
[C.block| void {
$(UIBatch* ptr)->element_ = $(UIElement* _uIBatchElement);
$(UIBatch* ptr)->blendMode_ = (BlendMode)$(int _uIBatchBlendMode');
$(UIBatch* ptr)->scissor_ = *$(IntRect* _uIBatchScissor');
$(UIBatch* ptr)->texture_ = $(Texture* _uIBatchTexture);
$(UIBatch* ptr)->invTextureSize_ = *$(Vector2* _uIBatchInvTextureSize');
$(UIBatch* ptr)->color_ = $(unsigned int _uIBatchColor');
$(UIBatch* ptr)->vertexData_ = new PODVectorFloat(*$(PODVectorFloat* _uIBatchVertexData'));
$(UIBatch* ptr)->vertexStart_ = $(unsigned int _uIBatchVertexStart');
$(UIBatch* ptr)->vertexEnd_ = $(unsigned int _uIBatchVertexEnd');
$(UIBatch* ptr)->useGradient_ = $(int _uIBatchUseGradient') != 0;
} |]
-- | Position adjustment vector for pixel-perfect rendering. Initialized by UI.
uiBatchPosAdjust :: MonadIO m => m Vector3
uiBatchPosAdjust = liftIO $ peek =<< [C.exp| Vector3* { &UIBatch::posAdjust } |]
-- | Set new color for the batch. Overrides gradient.
-- void SetColor(const Color& color, bool overrideAlpha = false);
uiBatchSetColor :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> Color -- ^ color
-> Bool -- ^ override alpha (default false)
-> m ()
uiBatchSetColor p c a = liftIO $ with c $ \c' -> do
let ptr = parentPointer p
a' = fromBool a
[C.exp| void {$(UIBatch* ptr)->SetColor(*$(Color* c'), $(int a') != 0)} |]
-- | Restore UI element's default color.
-- void SetDefaultColor();
uiBatchSetDefaultColor :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> m ()
uiBatchSetDefaultColor p = liftIO $ do
let ptr = parentPointer p
[C.exp| void {$(UIBatch* ptr)->SetDefaultColor()} |]
-- | Add a quad.
-- void AddQuad(int x, int y, int width, int height, int texOffsetX, int texOffsetY, int texWidth = 0, int texHeight = 0);
uiBatchAddQuad :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> Int -- ^ x
-> Int -- ^ y
-> Int -- ^ width
-> Int -- ^ height
-> Int -- ^ texOffsetX
-> Int -- ^ texOffsetY
-> Int -- ^ texWidth (default 0)
-> Int -- ^ texHeight (default 0)
-> m ()
uiBatchAddQuad p xv yv widthv heightv texOffsetX texOffsetY texWidth texHeight = liftIO $ do
let ptr = parentPointer p
xv' = fromIntegral xv
yv' = fromIntegral yv
widthv' = fromIntegral widthv
heightv' = fromIntegral heightv
texOffsetX' = fromIntegral texOffsetX
texOffsetY' = fromIntegral texOffsetY
texWidth' = fromIntegral texWidth
texHeight' = fromIntegral texHeight
[C.exp| void {$(UIBatch* ptr)->AddQuad(
$(int xv')
, $(int yv')
, $(int widthv')
, $(int heightv')
, $(int texOffsetX')
, $(int texOffsetY')
, $(int texWidth')
, $(int texHeight')
)} |]
-- | Add a quad using a transform matrix.
-- void AddQuad(const Matrix3x4& transform, int x, int y, int width, int height, int texOffsetX, int texOffsetY, int texWidth = 0,
-- int texHeight = 0);
uiBatchAddQuadMatrix :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> Matrix3x4 -- ^ transform
-> Int -- ^ x
-> Int -- ^ y
-> Int -- ^ width
-> Int -- ^ height
-> Int -- ^ texOffsetX
-> Int -- ^ texOffsetY
-> Int -- ^ texWidth (default 0)
-> Int -- ^ texHeight (default 0)
-> m ()
uiBatchAddQuadMatrix p m xv yv widthv heightv texOffsetX texOffsetY texWidth texHeight = liftIO $ with m $ \m' -> do
let ptr = parentPointer p
xv' = fromIntegral xv
yv' = fromIntegral yv
widthv' = fromIntegral widthv
heightv' = fromIntegral heightv
texOffsetX' = fromIntegral texOffsetX
texOffsetY' = fromIntegral texOffsetY
texWidth' = fromIntegral texWidth
texHeight' = fromIntegral texHeight
[C.exp| void {$(UIBatch* ptr)->AddQuad(
*$(Matrix3x4* m')
, $(int xv')
, $(int yv')
, $(int widthv')
, $(int heightv')
, $(int texOffsetX')
, $(int texOffsetY')
, $(int texWidth')
, $(int texHeight')
)} |]
-- | Add a quad with tiled texture.
-- void AddQuad(int x, int y, int width, int height, int texOffsetX, int texOffsetY, int texWidth, int texHeight, bool tiled);
uiBatchAddQuadTexture :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> Int -- ^ x
-> Int -- ^ y
-> Int -- ^ width
-> Int -- ^ height
-> Int -- ^ texOffsetX
-> Int -- ^ texOffsetY
-> Int -- ^ texWidth
-> Int -- ^ texHeight
-> Bool -- ^ tiled
-> m ()
uiBatchAddQuadTexture p xv yv widthv heightv texOffsetX texOffsetY texWidth texHeight tiled = liftIO $ do
let ptr = parentPointer p
xv' = fromIntegral xv
yv' = fromIntegral yv
widthv' = fromIntegral widthv
heightv' = fromIntegral heightv
texOffsetX' = fromIntegral texOffsetX
texOffsetY' = fromIntegral texOffsetY
texWidth' = fromIntegral texWidth
texHeight' = fromIntegral texHeight
tiled' = fromBool tiled
[C.exp| void {$(UIBatch* ptr)->AddQuad(
$(int xv')
, $(int yv')
, $(int widthv')
, $(int heightv')
, $(int texOffsetX')
, $(int texOffsetY')
, $(int texWidth')
, $(int texHeight')
, $(int tiled') != 0
)} |]
-- | Add a quad with freeform points and UVs. Uses the current color, not gradient. Points should be specified in clockwise order.
-- void AddQuad(const Matrix3x4& transform, const IntVector2& a, const IntVector2& b, const IntVector2& c, const IntVector2& d,
-- const IntVector2& texA, const IntVector2& texB, const IntVector2& texC, const IntVector2& texD);
uiBatchAddQuadFreeform :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> Matrix3x4 -- ^ transform
-> IntVector2 -- ^ a
-> IntVector2 -- ^ b
-> IntVector2 -- ^ c
-> IntVector2 -- ^ d
-> IntVector2 -- ^ texA
-> IntVector2 -- ^ texB
-> IntVector2 -- ^ texC
-> IntVector2 -- ^ texD
-> m ()
uiBatchAddQuadFreeform p m av bv cv dv texA texB texC texD = liftIO $
with m $ \m' ->
with av $ \av' ->
with bv $ \bv' ->
with cv $ \cv' ->
with dv $ \dv' ->
with texA $ \texA' ->
with texB $ \texB' ->
with texC $ \texC' ->
with texD $ \texD' -> do
let ptr = parentPointer p
[C.exp| void {$(UIBatch* ptr)->AddQuad(
*$(Matrix3x4* m')
, *$(IntVector2* av')
, *$(IntVector2* bv')
, *$(IntVector2* cv')
, *$(IntVector2* dv')
, *$(IntVector2* texA')
, *$(IntVector2* texB')
, *$(IntVector2* texC')
, *$(IntVector2* texD')
)} |]
-- | Add a quad with freeform points, UVs and colors. Points should be specified in clockwise order.
-- void AddQuad(const Matrix3x4& transform, const IntVector2& a, const IntVector2& b, const IntVector2& c, const IntVector2& d,
-- const IntVector2& texA, const IntVector2& texB, const IntVector2& texC, const IntVector2& texD, const Color& colA,
-- const Color& colB, const Color& colC, const Color& colD);
uiBatchAddQuadFreeformMatrix :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> Matrix3x4 -- ^ transform
-> IntVector2 -- ^ a
-> IntVector2 -- ^ b
-> IntVector2 -- ^ c
-> IntVector2 -- ^ d
-> IntVector2 -- ^ texA
-> IntVector2 -- ^ texB
-> IntVector2 -- ^ texC
-> IntVector2 -- ^ texD
-> Color -- ^ colA
-> Color -- ^ colB
-> Color -- ^ colC
-> Color -- ^ colD
-> m ()
uiBatchAddQuadFreeformMatrix p m av bv cv dv texA texB texC texD colA colB colC colD = liftIO $
with m $ \m' ->
with av $ \av' ->
with bv $ \bv' ->
with cv $ \cv' ->
with dv $ \dv' ->
with texA $ \texA' ->
with texB $ \texB' ->
with texC $ \texC' ->
with texD $ \texD' ->
with colA $ \colA' ->
with colB $ \colB' ->
with colC $ \colC' ->
with colD $ \colD' -> do
let ptr = parentPointer p
[C.exp| void {$(UIBatch* ptr)->AddQuad(
*$(Matrix3x4* m')
, *$(IntVector2* av')
, *$(IntVector2* bv')
, *$(IntVector2* cv')
, *$(IntVector2* dv')
, *$(IntVector2* texA')
, *$(IntVector2* texB')
, *$(IntVector2* texC')
, *$(IntVector2* texD')
, *$(Color* colA')
, *$(Color* colB')
, *$(Color* colC')
, *$(Color* colD')
)} |]
-- | Merge with another batch.
-- bool Merge(const UIBatch& batch);
uiBatchMerge :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> Ptr UIBatch -- ^ batch
-> m Bool
uiBatchMerge p b = liftIO $ do
let ptr = parentPointer p
toBool <$> [C.exp| int {(int)$(UIBatch* ptr)->Merge(*$(UIBatch* b))} |]
-- | Merge with another batch. Pure version.
batchMerge :: UIBatch -> UIBatch -> Maybe UIBatch
batchMerge b1 b2 = unsafePerformIO $ with b1 $ \b1' -> with b2 $ \b2' -> do
res <- uiBatchMerge b1' b2'
if res then Just <$> peek b1' else pure Nothing
-- | Return an interpolated color for the UI element.
-- unsigned GetInterpolatedColor(int x, int y);
uiBatchGetInterpolatedColor :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> Int -- ^ x
-> Int -- ^ y
-> m Word
uiBatchGetInterpolatedColor p xv yv = liftIO $ do
let ptr = parentPointer p
xv' = fromIntegral xv
yv' = fromIntegral yv
fromIntegral <$> [C.exp| unsigned int {$(UIBatch* ptr)->GetInterpolatedColor($(int xv'), $(int yv'))} |]
-- | Add or merge a batch.
-- static void AddOrMerge(const UIBatch& batch, PODVector<UIBatch>& batches);
uiBatchAddOrMerge :: (Parent UIBatch a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to uiBatch or ascentor
-> Ptr PODVectorUIBatch
-> m ()
uiBatchAddOrMerge p pv = liftIO $ do
let ptr = parentPointer p
[C.exp| void {UIBatch::AddOrMerge(*$(UIBatch* ptr), *$(PODVectorUIBatch* pv))} |]
-- | Add or merge a batch. Pure version
-- static void AddOrMerge(const UIBatch& batch, PODVector<UIBatch>& batches);
batchAddOrMerge :: ForeignVector v UIBatch
=> UIBatch -- ^ batch
-> v UIBatch -- ^ batches
-> v UIBatch
batchAddOrMerge b bs = unsafePerformIO $ with b $ \b' -> withForeignVector () bs $ \bs' -> do
[C.exp| void {UIBatch::AddOrMerge(*$(UIBatch* b'), *$(PODVectorUIBatch* bs'))} |]
peekForeignVectorAs bs'
| Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/UI/UIBatch.hs | mit | 15,719 | 0 | 36 | 3,233 | 2,840 | 1,564 | 1,276 | -1 | -1 |
module Y2020.M07.D28.Solution where
{--
Father: Once, long ago, there was a development environment called 'netbeans'
where you didn't write any code at all, ever, you dragged and dropped components
and connected the-...
Mother: Hush, dear! You're scaring the children!
So, that has nothing to do with anything ...
... except, more than 10 years later, I had to debug a netbeans 'Enterprise'
app, and the only way anything would work was to download netbeans itself, and
view the system in the IDE.
Ugh.
Anyway: the 'code without coding!'-crowd? that show up every six years or so?
Yeah. Don't listen to them.
So, like yesterday, let's say you have an external app that you don't want to
rewrite, you just want to use, let's say it's even a netbeans app, but, unlike
yesterday, this app takes arguments, and we need to verify:
1. that it returned successfully; and,
2. that we get back expected results.
Your mission, should you decide to accept it, is to call this external
application, and do the above verifications.
--}
import System.Process
import GHC.IO.Exception -- .ExitCode
exerciseDir :: FilePath
exerciseDir = "Y2020/M07/D28/"
app :: FilePath
app = "summer.py"
callUndVerify :: FilePath -> String -> IO String
callUndVerify exe arg =
readProcessWithExitCode exe [arg] "" >>= \(code, ans, _) ->
return (let errOut = "Whazzamattahfur you? I can't do no sum o' no " ++ arg
answer = chomp ans
in verify code arg answer)
verify :: ExitCode -> String -> String -> String
verify ExitSuccess "10" ans@"45" = ans
verify _ arg _ =
"Whazzamattahfur you? I can't do no sum o' no " ++ arg
chomp :: String -> String
chomp str = let (h:t) = reverse str
in if h == '\n' then reverse t else str
{--
So: verify that calling the app with 10 returns 45, and calling the app with
123 returns an error from the external app.
p.s.: Also, since you know this is a python-app, you can either rely on the
script's designation of what python is, or you can specify python from your
execution of the app here. Your choice.
>>> callUndVerify (exerciseDir ++ app) "10"
"45"
>>> callUndVerify (exerciseDir ++ app) "101"
"Whazzamattahfur you? I can't do no sum o' no 101"
>>> callUndVerify (exerciseDir ++ app) "frankenfurters"
"Whazzamattahfur you? I can't do no sum o' no frankenfurters"
--}
| geophf/1HaskellADay | exercises/HAD/Y2020/M07/D28/Solution.hs | mit | 2,365 | 0 | 13 | 484 | 234 | 126 | 108 | 20 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE PackageImports #-}
module Main
( main -- :: IO ()
) where
import Data.Int
import System.IO
import Control.Monad (liftM)
import Criterion.Main hiding (run)
import Data.ByteString.Char8 as S hiding (take, readFile)
import System.IO
import Data.LargeWord
import Control.DeepSeq
import "cityhash-old" Data.Digest.CityHash as Old
import "cityhash" Data.Digest.CityHash as New
instance NFData ByteString where
instance (NFData a, NFData b) => NFData (LargeKey a b) where
rnf (LargeKey a b) = a `seq` b `seq` ()
main :: IO ()
main = do
h <- openFile "/dev/urandom" ReadMode
str <- S.hGet h 1024
hClose h
defaultMain [ bench "old cityHash128, 1k string" $ nf Old.cityHash128 str
, bench "sse4.2 cityHash128, 1k string" $ nf New.cityHash128 str
]
| thoughtpolice/hs-cityhash | bench/sse.hs | mit | 819 | 2 | 11 | 156 | 251 | 140 | 111 | 24 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
import Actor
import ActorRef
import ActorRefFactory
import ActorSystem
import Control.Concurrent
import Control.Monad
import Control.Monad.Reader
import Control.Monad.State
import Control.Concurrent.STM
import Data.Dynamic
import qualified Data.Foldable as F
import qualified Data.Vector as V
import Data.Typeable
import System.IO.Unsafe
import System.Random
import System.Exit
simple :: Actor
simple = Actor . const $ return ()
echo :: Actor
echo = Actor $ liftIO . print
gossip :: Int -> MVar (V.Vector ActorRef) -> Actor
gossip factor t = Actor $ \msg -> liftIO $ do
rands <- replicateM factor $ randomRIO (0, size - 1)
peers <- readMVar t
mapM_ (\i -> peers `V.unsafeIndex` i ! i) rands
size :: Int
size = 100000
test :: Actor
test = Actor $ \dyn ->
F.forM_ (fromDynamic dyn :: Maybe Bool) $ \b ->
become $ if b then intRecv else strRecv
where intRecv msg = liftIO (F.forM_ (fromDynamic msg :: Maybe Int) print) >> unbecome
strRecv msg = liftIO (F.forM_ (fromDynamic msg :: Maybe String) putStrLn) >> unbecome
main = do
sys <- newActorSystem "sys"
t1 <- actorOf sys test "test"
t1 ! True
t1 ! (0 :: Int)
t1 ! "hello"
{-main = do-}
{-system <- newActorSystem "test"-}
{-peers <- newEmptyMVar-}
{-refs <- V.replicateM size $ actorOf system (gossip 5 peers) ""-}
{-putMVar peers refs-}
{-V.head refs ! "start"-}
{-threadDelay 10000000-}
{-exitSuccess-}
| crdueck/actors | Main.hs | mit | 1,493 | 0 | 14 | 322 | 444 | 241 | 203 | 40 | 2 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Graphics.Urho3D.Network.Connection(
Connection
, SharedConnection
, VectorSharedPtrConnection
, connectionContext
, connectionSendMessage
, connectionDisconnect
, connectionIsClient
, connectionIsConnected
, connectionIsConnectPending
, connectionIsSceneLoaded
, connectionGetLogStatistics
, connectionGetAddress
, connectionGetPort
, connectionGetRoundTripTime
, connectionGetLastHeardTime
, connectionGetBytesInPerSec
, connectionGetBytesOutPerSec
, connectionGetPacketsInPerSec
, connectionGetPacketsOutPerSec
, connectionToString
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Cpp as C
import Data.Monoid
import Foreign
import Foreign.C.String
import Graphics.Urho3D.Container.ForeignVector
import Graphics.Urho3D.Container.Ptr
import Graphics.Urho3D.Core.Context
import Graphics.Urho3D.Creatable
import Graphics.Urho3D.Monad
import Graphics.Urho3D.Network.Internal.Connection
import qualified Data.ByteString as BS
import qualified Data.ByteString.Unsafe as BS
C.context (C.cppCtx <> connectionCntx <> contextContext <> sharedConnectionPtrCntx)
C.include "<Urho3D/Network/Connection.h>"
C.using "namespace Urho3D"
connectionContext :: C.Context
connectionContext = connectionCntx <> sharedConnectionPtrCntx
sharedPtr "Connection"
C.verbatim "typedef Vector<SharedPtr<Connection> > VectorSharedPtrConnection;"
instance Creatable (Ptr VectorSharedPtrConnection) where
type CreationOptions (Ptr VectorSharedPtrConnection) = ()
newObject _ = liftIO [C.exp| VectorSharedPtrConnection* {new Vector<SharedPtr<Connection> >() } |]
deleteObject ptr = liftIO [C.exp| void { delete $(VectorSharedPtrConnection* ptr) } |]
instance ReadableVector VectorSharedPtrConnection where
type ReadVecElem VectorSharedPtrConnection = SharedPtr Connection
foreignVectorLength ptr = liftIO $ fromIntegral <$> [C.exp| int {$(VectorSharedPtrConnection* ptr)->Size() } |]
foreignVectorElement ptr i = liftIO $ peekSharedPtr =<< [C.exp| SharedConnection* { new SharedPtr<Connection>((*$(VectorSharedPtrConnection* ptr))[$(unsigned int i')]) } |]
where i' = fromIntegral i
instance WriteableVector VectorSharedPtrConnection where
type WriteVecElem VectorSharedPtrConnection = SharedPtr Connection
foreignVectorAppend ptr e = liftIO $ [C.exp| void {$(VectorSharedPtrConnection* ptr)->Push(SharedPtr<Connection>($(Connection* e'))) } |]
where e' = parentPointer e
-- | Send a message.
-- void SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes, unsigned contentID = 0);
connectionSendMessage :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> Int -- ^ Message id
-> Bool -- ^ Reliable flag
-> Bool -- ^ Keep order flag
-> BS.ByteString -- ^ Buffer
-> Word -- ^ Content ID (default 0)
-> m ()
connectionSendMessage ptr msgID reliable inOrder bs contentID = liftIO $ BS.unsafeUseAsCStringLen bs $ \(bsptr, l) -> do
let ptr' = parentPointer ptr
msgID' = fromIntegral msgID
reliable' = fromBool reliable
inOrder' = fromBool inOrder
contentID' = fromIntegral contentID
l' = fromIntegral l
bsptr' = castPtr bsptr
[C.exp| void { $(Connection* ptr')->SendMessage($(int msgID'), $(int reliable') != 0, $(int inOrder') != 0, $(const unsigned char* bsptr'), $(unsigned int l'), $(unsigned int contentID')) } |]
-- | Send a remote event.
-- void SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
-- | Send a remote event with the specified node as sender.
-- void SendRemoteEvent(Node* node, StringHash eventType, bool inOrder, const VariantMap& eventData = Variant::emptyVariantMap);
-- | Assign scene. On the server, this will cause the client to load it.
-- void SetScene(Scene* newScene);
-- | Set new controls.
-- void SetControls(const Controls& newControls);
-- | Set the observer position for interest management, to be sent to the server.
-- void SetPosition(const Vector3& position);
-- | Set the observer rotation for interest management, to be sent to the server. Note: not used by the NetworkPriority component.
-- void SetRotation(const Quaternion& rotation);
-- | Set whether to log data in/out statistics.
-- void SetLogStatistics(bool enable);
-- | Disconnect. If wait time is non-zero, will block while waiting for disconnect to finish.
-- void Disconnect(int waitMSec = 0);
connectionDisconnect :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> Int -- ^ Wait milliseconds
-> m ()
connectionDisconnect ptr waitMSec = liftIO $ do
let ptr' = parentPointer ptr
waitMSec' = fromIntegral waitMSec
[C.exp| void { $(Connection* ptr')->Disconnect($(int waitMSec')) } |]
-- | Return the scene used by this connection.
-- Scene* GetScene() const;
-- | Return the client controls of this connection.
-- const Controls& GetControls() const { return controls_; }
-- | Return the controls timestamp, sent from client to server along each control update.
-- unsigned char GetTimeStamp() const { return timeStamp_; }
-- | Return the observer position sent by the client for interest management.
-- const Vector3& GetPosition() const { return position_; }
-- | Return the observer rotation sent by the client for interest management.
-- const Quaternion& GetRotation() const { return rotation_; }
-- | Return whether is a client connection.
-- bool IsClient() const { return isClient_; }
connectionIsClient :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Bool
connectionIsClient ptr = liftIO $ do
let ptr' = parentPointer ptr
toBool <$> [C.exp| int { (int)$(Connection* ptr')->IsClient() } |]
-- | Return whether is fully connected.
-- bool IsConnected() const;
connectionIsConnected :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Bool
connectionIsConnected ptr = liftIO $ do
let ptr' = parentPointer ptr
toBool <$> [C.exp| int { (int)$(Connection* ptr')->IsConnected() } |]
-- | Return whether connection is pending.
-- bool IsConnectPending() const { return connectPending_; }
connectionIsConnectPending :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Bool
connectionIsConnectPending ptr = liftIO $ do
let ptr' = parentPointer ptr
toBool <$> [C.exp| int { (int)$(Connection* ptr')->IsConnectPending() } |]
-- | Return whether the scene is loaded and ready to receive server updates.
-- bool IsSceneLoaded() const { return sceneLoaded_; }
connectionIsSceneLoaded :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Bool
connectionIsSceneLoaded ptr = liftIO $ do
let ptr' = parentPointer ptr
toBool <$> [C.exp| int { (int)$(Connection* ptr')->IsSceneLoaded() } |]
-- | Return whether to log data in/out statistics.
-- bool GetLogStatistics() const { return logStatistics_; }
connectionGetLogStatistics :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Bool
connectionGetLogStatistics ptr = liftIO $ do
let ptr' = parentPointer ptr
toBool <$> [C.exp| int { (int)$(Connection* ptr')->GetLogStatistics() } |]
-- | Return remote address.
-- String GetAddress() const { return address_; }
connectionGetAddress :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m String
connectionGetAddress ptr = liftIO $ do
let ptr' = parentPointer ptr
peekCString =<< [C.exp| const char* { $(Connection* ptr')->GetAddress().CString() } |]
-- | Return remote port.
-- unsigned short GetPort() const { return port_; }
connectionGetPort :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Word
connectionGetPort ptr = liftIO $ do
let ptr' = parentPointer ptr
fromIntegral <$> [C.exp| unsigned short { $(Connection* ptr')->GetPort() } |]
-- | Return the connection's round trip time in milliseconds.
-- float GetRoundTripTime() const;
connectionGetRoundTripTime :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Float
connectionGetRoundTripTime ptr = liftIO $ do
let ptr' = parentPointer ptr
realToFrac <$> [C.exp| float { $(Connection* ptr')->GetRoundTripTime() } |]
-- | Return the time since last received data from the remote host in milliseconds.
-- float GetLastHeardTime() const;
connectionGetLastHeardTime :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Float
connectionGetLastHeardTime ptr = liftIO $ do
let ptr' = parentPointer ptr
realToFrac <$> [C.exp| float { $(Connection* ptr')->GetLastHeardTime() } |]
-- | Return bytes received per second.
-- float GetBytesInPerSec() const;
connectionGetBytesInPerSec :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Float
connectionGetBytesInPerSec ptr = liftIO $ do
let ptr' = parentPointer ptr
realToFrac <$> [C.exp| float { $(Connection* ptr')->GetBytesInPerSec() } |]
-- | Return bytes sent per second.
-- float GetBytesOutPerSec() const;
connectionGetBytesOutPerSec :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Float
connectionGetBytesOutPerSec ptr = liftIO $ do
let ptr' = parentPointer ptr
realToFrac <$> [C.exp| float { $(Connection* ptr')->GetBytesOutPerSec() } |]
-- | Return packets received per second.
-- float GetPacketsInPerSec() const;
connectionGetPacketsInPerSec :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Float
connectionGetPacketsInPerSec ptr = liftIO $ do
let ptr' = parentPointer ptr
realToFrac <$> [C.exp| float { $(Connection* ptr')->GetPacketsInPerSec() } |]
-- | Return packets sent per second.
-- float GetPacketsOutPerSec() const;
connectionGetPacketsOutPerSec :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m Float
connectionGetPacketsOutPerSec ptr = liftIO $ do
let ptr' = parentPointer ptr
realToFrac <$> [C.exp| float { $(Connection* ptr')->GetPacketsOutPerSec() } |]
-- | Return an address:port string.
-- String ToString() const;
connectionToString :: (Parent Connection a, Pointer ptr a, MonadIO m)
=> ptr -- ^ Pointer to 'Connection' or ancestor
-> m String
connectionToString ptr = liftIO $ do
let ptr' = parentPointer ptr
peekCString =<< [C.exp| const char* { $(Connection* ptr')->ToString().CString() } |]
-- | Return number of package downloads remaining.
-- unsigned GetNumDownloads() const;
-- | Return name of current package download, or empty if no downloads.
-- const String& GetDownloadName() const;
-- | Return progress of current package download, or 1.0 if no downloads.
-- float GetDownloadProgress() const;
-- | Trigger client connection to download a package file from the server. Can be used to download additional resource packages when client is already joined in a scene. The package must have been added as a requirement to the scene the client is joined in, or else the eventual download will fail.
-- void SendPackageToClient(PackageFile* package);
| Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/Network/Connection.hs | mit | 11,491 | 0 | 13 | 1,848 | 1,804 | 1,001 | 803 | -1 | -1 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.ApplePayPaymentAuthorizedEvent
(getPayment, ApplePayPaymentAuthorizedEvent(..),
gTypeApplePayPaymentAuthorizedEvent)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ApplePayPaymentAuthorizedEvent.payment Mozilla ApplePayPaymentAuthorizedEvent.payment documentation>
getPayment ::
(MonadDOM m) => ApplePayPaymentAuthorizedEvent -> m ApplePayPayment
getPayment self
= liftDOM ((self ^. js "payment") >>= fromJSValUnchecked)
| ghcjs/jsaddle-dom | src/JSDOM/Generated/ApplePayPaymentAuthorizedEvent.hs | mit | 1,409 | 0 | 10 | 164 | 345 | 224 | 121 | 23 | 1 |
{-# LANGUAGE Arrows, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, TemplateHaskell, UnicodeSyntax #-}
module Database.Types
(
Domain,
DomainColumns,
DomainPGR,
DomainPGW,
PolyDomain(..),
QueryDomain
) where
import GHC.Generics
import Control.Arrow
import qualified Data.ByteString as BS (concat, ByteString)
import qualified Data.ByteString.Char8 as BSC8 (pack, unpack, unwords)
import Data.Profunctor.Product (p2, p3, p6)
import Data.Profunctor.Product.Default (Default(..))
import Opaleye (Column, Nullable, PGUuid, PGInt4, PGInt8, PGText, PGDate, PGFloat8, PGBool, Query, QueryArr, QueryRunner, QueryRunnerColumnDefault(..), Table(Table), Unpackspec,
fieldQueryRunnerColumn, matchNullable, isNull,
required, queryTable,
restrict, (.==), (.<=), (.&&), (.<),
(.===), (.++), ifThenElse, pgString, aggregate, groupBy,
count, avg, sum, leftJoin, runQuery, showSqlForPostgres)
import Database.PostgreSQL.Simple.FromField (FromField(..))
newtype BaseId = BaseId Int deriving (Show)
instance FromField BaseId where
fromField field bs = BaseId <$> fromField field bs
instance QueryRunnerColumnDefault PGInt4 BaseId where
queryRunnerColumnDefault = fieldQueryRunnerColumn
type DomainColumns = ( Column PGInt4, Column PGText)
type QueryDomain = Query DomainPGR
data PolyDomain lvl nm = Domain {level ∷ lvl, name ∷ nm}
deriving (Show)
type Domain = PolyDomain Int String
type DomainPGW = PolyDomain (Column PGInt4) (Column PGText)
type DomainPGR = DomainPGW
| xruzzz/axt-links-saver-haskell | src/Database/Types.hs | gpl-2.0 | 1,723 | 0 | 8 | 403 | 416 | 266 | 150 | 34 | 0 |
{-# LANGUAGE FlexibleInstances, ScopedTypeVariables #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Utils.Server
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL
--
-- Maintainer : maintainer@leksah.org
-- Stability : provisional
-- Portability :
--
-- |
--
------------------------------------------------------------------------------
module IDE.Utils.Server
( ipAddress
, Server (..)
, serveOne
, serveMany
, ServerRoutine
, UserAndGroup (..)
, WaitFor (waitFor))
where
import Network
import Network.Socket hiding (accept)
import System.IO
import Control.Concurrent
import Control.Exception as E
import Data.Word
import System.Log.Logger (infoM)
import Data.Text (Text)
import Control.Monad (void)
data UserAndGroup = UserAndGroup Text Text | UserWithDefaultGroup Text
-- | Set the user and group for the process. If the group is Nothing, then use the users default group.
-- This is especially useful when you are root and want to become a user.
setUserAndGroup :: UserAndGroup -> IO ()
setUserAndGroup _ = return ()
-- | make an IP Address: (127,0,0,1) is the localhost
ipAddress :: (Word8, Word8, Word8, Word8) -> HostAddress
ipAddress (a, b, c, d) = fromIntegral a + 0x100 * fromIntegral b + 0x10000 * fromIntegral c + 0x1000000 * fromIntegral d
-- | the functionality of a server
type ServerRoutine = (Handle, HostName, PortNumber) -> MVar () -> IO ()
serverSocket' :: Server -> IO Socket
serverSocket' (Server (SockAddrInet _ _) t _) = socket AF_INET t defaultProtocol
serverSocket' _ = fail "Unexpected Socket Address Type"
serverSocket :: Server -> IO (Socket, Server)
serverSocket server = do
sock <- serverSocket' server
setSocketOption sock ReuseAddr 1
bindSocket sock (serverAddr server)
infoM "leksah-server" $ "Bind " ++ show (serverAddr server)
listen sock maxListenQueue
return (sock, server)
-- |the specification of a serving process
data Server = Server {
serverAddr :: SockAddr,
serverTyp :: SocketType,
serverRoutine :: ServerRoutine}
startAccepting :: (Socket, Server) -> IO (ThreadId, MVar ())
startAccepting (sock, server) = do
mvar <- newEmptyMVar
threadId <- forkIO (acceptance sock mvar (serverRoutine server) `finally` putMVar mvar ())
return (threadId, mvar)
serveMany :: Maybe UserAndGroup -> [Server] -> IO [(ThreadId, MVar ())]
serveMany (Just userAndGroup) l = do
ready <- mapM serverSocket l
setUserAndGroup userAndGroup
mapM startAccepting ready
serveMany Nothing l = mapM serverSocket l >>= mapM startAccepting
serveOne :: Maybe UserAndGroup -> Server -> IO (ThreadId, MVar ())
serveOne ug s = do
l <- serveMany ug [s]
return (head l)
class WaitFor a where
waitFor :: a -> IO ()
instance WaitFor (MVar a) where
waitFor mvar = void (readMVar mvar)
instance WaitFor a => WaitFor [a] where
waitFor = mapM_ waitFor
instance WaitFor (ThreadId, MVar ()) where
waitFor (_, mvar) = waitFor mvar
acceptance :: Socket -> MVar () -> ServerRoutine -> IO ()
acceptance sock mvar action = E.catch (do
dta <- accept sock
void . forkIO $ action dta mvar)
(\(e :: SomeException) -> print e) >>
acceptance sock mvar action
| JPMoresmau/leksah-server | src/IDE/Utils/Server.hs | gpl-2.0 | 3,464 | 0 | 13 | 793 | 955 | 501 | 454 | 71 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module IDL.Printer
( typesFFI
, enumsFFI
, exportsFFI
, importsFFI
) where
import Data.Char (toLower, toUpper)
import Data.Maybe (isNothing)
import IDL.Cleaner (getEnums, getFuncs, getTypes)
import Text.PrettyPrint (Doc, ($+$), ($$), (<>), (<+>), char, empty,
hcat, int, integer, nest, parens, punctuate, text, vcat)
import IDL.AST
typesFFI :: IDL -> Doc
typesFFI idl =
header $+$ blank $+$
typeDefs $+$ blank $+$
typeDecls $+$ blank $+$
contextAttrs $+$ blank
where
header = vcat
[ "module Graphics.WebGL.Raw.Types where"
, ""
, "import Data.ArrayBuffer.Types"
]
typeDecls = vcat . map ppTypeDecl $ getTypes idl
enumsFFI :: IDL -> Doc
enumsFFI idl =
header $+$ blank $+$
constants $+$ blank
where
header = vcat
[ "module Graphics.WebGL.Raw.Enums where"
, ""
, "import Graphics.WebGL.Raw.Types (GLenum ())"
]
constants = vcat . map ppConstant $ getEnums idl
exportsFFI :: IDL -> Doc
exportsFFI idl =
header $+$ blank $+$
methods $+$ blank
where
header = vcat
[ "\"use strict\";"
, ""
, "// module Graphics.WebGL.Raw"
]
methods = vcat . map ppJsFunc $ getFuncs idl
importsFFI :: IDL -> Doc
importsFFI idl =
header $+$ blank $+$
funcs $+$ blank
where
header = vcat
[ "module Graphics.WebGL.Raw"
, expList
, ") where"
, ""
, "import Control.Monad.Eff"
, "import Data.ArrayBuffer.Types"
, "import Data.Function"
, "import Data.Maybe"
, "import Graphics.Canvas"
, "import Graphics.WebGL.Raw.Types"
, "import Graphics.WebGL.Raw.Util"
, "import Prelude"
]
expList = ppExportList $ getFuncs idl
funcs = vcat . map ppImport $ getFuncs idl
-- predefined text
typeDefs :: Doc
typeDefs = vcat
[ "type DOMString = String"
, "type BufferDataSource = Float32Array"
, "type FloatArray = Float32Array"
, "type GLbitfield = Int"
, "type GLboolean = Boolean"
, "type GLbyte = Int"
, "type GLclampf = Number"
, "type GLenum = Int"
, "type GLfloat = Number"
, "type GLint = Int"
, "type GLintptr = Int"
, "type GLshort = Int"
, "type GLsizei = Int"
, "type GLsizeiptr = Int"
, "type GLubyte = Int"
, "type GLuint = Int"
, "type GLushort = Int"
]
contextAttrs :: Doc
contextAttrs = vcat
[ "type WebGLContextAttributes ="
, " { alpha :: Boolean"
, " , depth :: Boolean"
, " , stencil :: Boolean"
, " , antialias :: Boolean"
, " , premultipliedAlpha :: Boolean"
, " , preserveDrawingBuffer :: Boolean"
, " , preferLowPowerToHighPerformance :: Boolean"
, " , failIfMajorPerformanceCaveat :: Boolean"
, " }"
]
-- javascript pretty-printers
ppJsFunc :: Decl -> Doc
ppJsFunc f =
expName <+> "=" <+> func <+> parens (ppJsArgs funcArgs f) <+> "{" $+$
nest 2 (ret <+> func <+> "() {") $+$
nest 4 (ret <+> ppJsFuncInner f) $+$
nest 2 "};" $+$
"}" $+$
blank
where
expName = "exports." <> implName f
func = "function"
ret = "return"
ppJsFuncInner :: Decl -> Doc
ppJsFuncInner f@Function{} =
prefixWebgl <> text (actualName f) <> parens (ppJsArgs methodArgs f) <> ";"
ppJsArgs :: (Decl -> [Arg]) -> Decl -> Doc
ppJsArgs f = hcat . punctuate ", " . map (text . argName) . f
-- purescript raw module pretty-printers
ppExportList :: [Decl] -> Doc
ppExportList = vcat . addOpener . prePunct (", ") . map (text . methodName)
where
addOpener (x:xs) = "(" <+> x : xs
addOpener xs = xs
ppImport :: Decl -> Doc
ppImport f@Function{} =
ppImpl f $+$ blank $+$
ppFunc f $+$ blank
ppConvertType :: Type -> Doc
ppConvertType Concrete{ typeName = name, typeIsArray = isArray }
| name == "void" = toType "Unit"
| name == "boolean" = toType "Boolean"
| name == "ArrayBuffer" = toType "Float32Array"
| name == "long" = toType "Int"
| otherwise = toType name
where
toType = wrapArray . text
wrapArray t = if isArray
then parens $ "Array" <+> t
else t
ppConvertType _ = genericType
ppSigForall :: Decl -> Doc
ppSigForall Function{ methodRetType = ret } =
case ret of
Generic -> ":: forall eff" <+> genericType <> "."
_ -> ":: forall eff."
-- purescript impl pretty-printers
ppImpl :: Decl -> Doc
ppImpl f@Function{} = "foreign import" <+> implName f <+> ppImplTypeSig f
ppImplTypeSig :: Decl -> Doc
ppImplTypeSig f@Function{} =
ppSigForall f <+> funcType <+> argList <+> parens (ppImplReturnType f)
where
args = funcArgs f
funcType = "Fn" <> int (length args)
argList = hcat . punctuate " " $ map (ppConvertType . argType) args
ppImplReturnType :: Decl -> Doc
ppImplReturnType fn = effMonad <+> ppConvertType (methodRetType fn)
-- purescript function pretty-printers
ppFunc :: Decl -> Doc
ppFunc f@Function{} = ppFuncTypeSig f $+$ ppFuncDef f
ppFuncTypeSig :: Decl -> Doc
ppFuncTypeSig f@Function{ methodName = name } =
text name <+> ppSigForall f <+> argList
where
types = map (ppConvertType . argType) (funcArgs f) ++ [ppFuncReturnType f]
argList = hcat $ punctuate " -> " types
ppFuncDef :: Decl -> Doc
ppFuncDef f@Function { methodName = name, methodRetType = retType } =
text name <+> args <+> "=" <+>
"runFn" <> int (length $ funcArgs f) <+>
implName f <+> args <+>
safetyFn retType
where
args = ppFuncArgs f
ppFuncArgs :: Decl -> Doc
ppFuncArgs = hcat . punctuate " " . map argNames . funcArgs
where
argNames = text . filterReserved . argName
ppFuncReturnType :: Decl -> Doc
ppFuncReturnType fn = effMonad <+> ppConvertMaybeType (methodRetType fn)
ppConvertMaybeType :: Type -> Doc
ppConvertMaybeType t = wrapMaybe $ ppConvertType t
where
wrapMaybe name = if typeIsMaybe t then parens ("Maybe" <+> name) else name
-- purecript enum pretty-printers
ppConstant :: Decl -> Doc
ppConstant Enum { enumName = n, enumValue = v } =
constName <+> ":: GLenum" $$
constName <+> "=" <+> (integer v) $$
blank
where
constName = toCamelCase n
-- purescript typedef pretty-printers
ppTypeDecl :: Type -> Doc
ppTypeDecl Concrete{ typeName = name } =
"foreign import data" <+> text name <+> ":: *"
ppTypeDecl _ = empty
-- helpers
blank :: Doc
blank = ""
effMonad :: Doc
effMonad = "Eff (canvas :: Canvas | eff)"
genericType :: Doc
genericType = char 'a'
implName :: Decl -> Doc
implName f@Function{} = text (methodName f) <> "Impl"
prefixWebgl :: Doc
prefixWebgl = text (argName webglContext) <> "."
prePunct :: Doc -> [Doc] -> [Doc]
prePunct p (x:x':xs) = x : go x' xs
where
go y [] = [p <> y]
go y (z:zs) = (p <> y) : go z zs
prePunct _ xs = xs
toCamelCase :: String -> Doc
toCamelCase = text . foldr go ""
where
go '_' (l:ls) = toUpper l : ls
go l ls = toLower l : ls
safetyFn :: Type -> Doc
safetyFn t@Concrete{}
| typeIsMaybe t = ">>= toMaybe >>> return"
| typeIsArray t = ">>= nullAsEmpty >>> return"
| otherwise = empty
safetyFn t@Generic = ">>= toMaybe >>> return"
filterReserved :: String -> String
filterReserved s = case s of
"data" -> "data'"
"where" -> "where'"
"type" -> "type'"
ok -> ok
| Jonplussed/purescript-webgl-raw | generator/IDL/Printer.hs | gpl-2.0 | 7,588 | 0 | 14 | 2,153 | 2,137 | 1,130 | 1,007 | 205 | 4 |
module Data.PrefixZipper
( PrefixZipper (..)
, empty
, fromList, fromList', toList
, toParts
, cursor
, setPrefix
, right
) where
import Data.String.Utils
import Data.Monoid
data PrefixZipper a = PrefixZipper
{ prefix :: [a]
, backward :: [[a]]
, forward :: [[a]]
}
empty :: PrefixZipper a
empty = PrefixZipper mempty [] []
fromList :: [[a]] -> PrefixZipper a
fromList l = PrefixZipper [] [] l
fromList' :: [[a]] -> PrefixZipper a
fromList' l = PrefixZipper mempty (reverse l) []
toList :: (Eq a) => PrefixZipper a -> [[a]]
toList z = filter (startswith $ prefix z) $ (backward z) ++ (forward z)
toParts :: (Eq a) => PrefixZipper a -> ([[a]], Maybe [a], [[a]])
toParts z = let f = filter $ startswith $ prefix z
in ((reverse $ f $ backward z), cursor z, (f $ drop 1 $ forward z))
cursor :: (Eq a) => PrefixZipper a -> Maybe [a]
cursor z = case forward z of
(x:_) -> Just x
[] -> Nothing
setPrefix :: (Eq a) => [a] -> PrefixZipper a -> PrefixZipper a
setPrefix str z = updateCursor $ z { prefix = str }
updateCursor :: (Eq a) => PrefixZipper a -> PrefixZipper a
updateCursor z = case forward z of
[] -> right z
(x:xs) -> if not (startswith (prefix z) x) then right z else z
{-
left :: (Eq a) => PrefixZipper a -> PrefixZipper a
left z = case toList z of
[] -> z
l -> left' z
where
left' z = case backward a of
[] -> left' $ PrefixZipper (reverse $ forward a) []
(x:xs) -> let next = PrefixZipper (prefix z) xs (x:(forward a))
in if x `startswith` prefix z
then next
else left' next
-}
right :: (Eq a) => PrefixZipper a -> PrefixZipper a
right z = case toList z of
[] -> z
l -> right' z
where
right' z = let next = case forward z of
[] -> PrefixZipper (prefix z) [] (reverse $ backward z)
[x] -> PrefixZipper (prefix z) [] (reverse $ x : backward z)
(x:x':xs) -> PrefixZipper (prefix z) (x : (backward z)) (x' : xs)
in if startswith (prefix z) (head $ forward next)
then next
else right' next
| talanis85/mudblood | src/Data/PrefixZipper.hs | gpl-3.0 | 2,231 | 0 | 18 | 714 | 832 | 436 | 396 | 46 | 5 |
import System.IO (getLine)
import Control.Monad
main :: IO()
main = do
num_samples <- getLine
replicateM_ (read num_samples) read_input
maxsub :: [Int] -> Int -> [Int]
maxsub x y
| last(x) + y > head(x) = if last(x) + y > 0
then [last(x) + y, last(x) + y]
else [last(x) + y, 0]
| otherwise = if last(x) + y > 0
then [head(x), last(x) + y]
else [head(x), 0]
kadanes :: [Int] -> Int
kadanes xs = head $ foldl maxsub [0,0] xs
parse_int_array :: String -> [Int]
parse_int_array tmp_array = map read $ words tmp_array
read_input = do
n <- getLine
tmp_array <- getLine
let xs = parse_int_array tmp_array
if length (filter (>0) xs) == 0
then do
putStr $ show $ foldl max (-9999999999) xs
putStr " "
putStrLn $ show $ foldl max (-9999999999) xs
else do
putStr $ show $ kadanes xs
putStr " "
putStrLn $ show $ sum $ filter (>0) xs
| woodsjc/hackerrank-challenges | hackerrank_max_subway.hs | gpl-3.0 | 1,052 | 0 | 13 | 389 | 460 | 233 | 227 | 31 | 3 |
-- Bernsen algorithm for binarization
module Bernsen (binarize, mixedBinarize) where
import qualified Data.Array.Repa as R
import qualified Data.Map as Map
import Data.Array.Repa (U, D, Z (..), (:.)(..))
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as Vm
import qualified Data.List as L
import PixelTraversals
import qualified Otsu
import YCbCr as Ycbcr
import Pixel
thresholds dim arr = R.traverse arr id f
where f = surroundingFilter minMaxMean dim
minMaxMean li = (L.minimum li + L.maximum li) / 2.0
binarize :: R.Array U R.DIM2 RGB8 -> IO (R.Array D R.DIM2 RGB8)
binarize arr = do
yArr <- R.computeUnboxedP $ R.map Ycbcr.y arr
let dim = R.extent yArr
thArr <- R.computeUnboxedP $ thresholds dim yArr
return $ R.traverse2 yArr thArr const fun
where fun lookUp1 lookUp2 coords =
if lookUp1 coords >= lookUp2 coords then (maxBound, maxBound, maxBound)
else (0, 0, 0)
mixedBinarize :: R.Array U R.DIM2 RGB8 -> Double -> IO (R.Array D R.DIM2 RGB8)
mixedBinarize arr threshold = do
yArr <- R.computeUnboxedP $ R.map Ycbcr.y arr
otsu_threshold <- Otsu.threshold yArr 256
let dim = R.extent yArr
thArr <- R.computeUnboxedP $ thresholds dim yArr
return $ R.traverse2 yArr thArr const (fun otsu_threshold)
where fun otTh lookUp1 lookUp2 coords =
let diff = lookUp1 coords - lookUp2 coords in
if abs diff > threshold then
if diff >= otTh then (maxBound, maxBound, maxBound)
else (0, 0, 0)
else
if diff >= 0 then (maxBound, maxBound, maxBound)
else (0, 0, 0)
| mikolajsacha/HaskellPics | bernsen.hs | gpl-3.0 | 1,651 | 0 | 12 | 395 | 584 | 315 | 269 | 37 | 4 |
{- |
Module : Coords
Description : Manage coordinates in either polar or cartesian system
Copyright : (c) Frédéric BISSON, 2015
License : GPL-3
Maintainer : zigazou@free.fr
Stability : experimental
Portability : POSIX
-}
module Tank.Units.Coords
( Coords (XY, PL)
, toXY
, toPL
, toTuple
, center
, distance
, isInside
) where
import Tank.Units.Angle
{-|
Coordinates can be either expressed as cartesian coordinates or polar
coordinates.
-}
data Coords = XY Double Double -- ^ Cartesian coordinates
| PL Double Angle -- ^ Polar coordinates
deriving (Show, Read)
{-|
Converts `PL` coordinates to `XY` coordinates.
-}
toXY :: Coords -> Coords
toXY c@(XY _ _) = c
toXY (PL dist angle) = XY (dist * cosine angle) (dist * sine angle)
{-|
Converts `XY` coordinates to `PL` coordinates.
-}
toPL :: Coords -> Coords
toPL c@(PL _ _) = c
toPL (XY x y) = PL (sqrt $ x * x + y * y) (arctan y x)
{-|
Converts coordinates to cartesian coordinates in a tuple of Double.
-}
toTuple :: Coords -> (Double, Double)
toTuple (XY x y) = (x, y)
toTuple c = (toTuple . toXY) c
{-|
Calculate center of two points.
-}
center :: Coords -> Coords -> Coords
center (XY x1 y1) (XY x2 y2) = XY ((x1 + x2) / 2) ((y1 + y2) / 2)
center c1@(XY _ _) c2 = center c1 (toXY c2)
center c1 c2 = toPL $ center (toXY c1) (toXY c2)
{-|
Calculate the distance between two points.
-}
distance :: Coords -> Coords -> Double
distance (XY x1 y1) (XY x2 y2) = sqrt ((x2 - x1) ** 2 + (y2 - y1) ** 2)
distance c1 c2 = distance (toXY c1) (toXY c2)
{-|
Tells whether a `Coords` is inside the rectangle formed by 2 `Coords`. Returns
`True` if this is the case, `False` otherwise.
-}
isInside :: (Coords, Coords) -> Coords -> Bool
isInside (XY x1 y1, XY x2 y2) (XY x y) =
(x >= x1 && x <= x2) && (y >= y1 && y <= y2)
isInside (mini, maxi) c = isInside (toXY mini, toXY maxi) (toXY c)
instance Eq Coords where
(==) (XY x1 y1) (XY x2 y2) = x1 == x2 && y1 == y2
(==) (PL d1 a1) (PL d2 a2) = d1 == d2 && a1 == a2
(==) c1@(XY _ _) c2 = c1 == toXY c2
(==) c1@(PL _ _) c2 = c1 == toPL c2
instance Num Coords where
(+) (XY x1 y1) (XY x2 y2) = XY (x1 + x2) (y1 + y2)
(+) (PL d1 a1) (PL d2 a2) = PL d a
where ca2a1 = cosine (a2 - a1)
d = sqrt (d1 * d1 + d2 * d2 + 2 * d1 * d2 * ca2a1)
a = a1 + arccosine ( (d1 + d2 * ca2a1) / d)
(+) c1@(XY _ _) c2 = c1 + toXY c2
(+) c1@(PL _ _) c2 = c1 + toPL c2
(*) (XY x1 y1) (XY x2 y2) = XY (x1 * x2 - y1 * y2) (x1 * y2 + y1 * x2)
(*) c1@(PL _ _) c2@(PL _ _) = toPL (toXY c1 * toXY c2)
(*) c1@(XY _ _) c2 = c1 * toXY c2
(*) c1@(PL _ _) c2 = c1 * toPL c2
negate (XY x y) = XY (-x) (-y)
negate (PL d a) = PL d (-a)
signum (XY x y) = XY (signum x) (signum y)
signum c = (toPL . signum . toXY) c
abs (XY x y) = XY (abs x) (abs y)
abs (PL d a) = PL d (abs a)
fromInteger n = XY (fromInteger n) 0.0
| Zigazou/Tank | src/Tank/Units/Coords.hs | gpl-3.0 | 2,936 | 0 | 16 | 789 | 1,386 | 730 | 656 | 58 | 1 |
module Main (main) where
import Data.List (genericLength)
import Data.Maybe (catMaybes)
import System.Exit (exitFailure, exitSuccess)
import System.Process (readProcess)
import Text.Regex (matchRegex, mkRegex)
average :: (Fractional a, Real b) => [b] -> a
average xs = realToFrac (sum xs) / genericLength xs
expected :: Fractional a => a
expected = 90
main :: IO ()
main = do
output <- readProcess "hpc" ["report", "dist/hpc/tix/hspec/hspec.tix"] ""
if average (match output) >= expected
then exitSuccess
else putStr output >> exitFailure
match :: String -> [Int]
match = fmap read . concat . catMaybes . fmap (matchRegex pattern) . lines
where
pattern = mkRegex "^ *([0-9]*)% "
| RomainGehrig/OhBool | tests/HPC.hs | gpl-3.0 | 715 | 0 | 11 | 138 | 254 | 136 | 118 | 19 | 2 |
{-
The Delve Programming Language
Copyright 2009 John Morrice
Distributed under the terms of the GNU General Public License v3, or ( at your option ) any later version.
This file is part of Delve.
Delve 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.
Delve 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 Delve. If not, see <http://www.gnu.org/licenses/>.
-}
-- random tools for operating on Haskell's AST
module HsAST
( module Language.Haskell.Exts
, a_src_loc
, exp_name
)
where
import Symbol
import Data.ByteString.Char8 as B
import Language.Haskell.Exts
a_src_loc :: SrcLoc
a_src_loc = SrcLoc "" 0 0
exp_name :: Symbol -> Name
exp_name = name . B.unpack
| elginer/Delve | src/HsAST.hs | gpl-3.0 | 1,171 | 0 | 6 | 263 | 75 | 47 | 28 | 11 | 1 |
module Demo where
import Data.Function
sumFstFst = (+) `on` helper where helper pp = fst $ fst pp
sumFstFst' = (+) `on` (\pp -> fst $ fst pp)
sumFstFst'' = (+) `on` (fst . fst)
p1 = ((1,2),(3,4))
p2 = ((3,4),(5,6))
| devtype-blogspot-com/Haskell-Examples | SumFstFst/Demo.hs | gpl-3.0 | 220 | 0 | 9 | 46 | 133 | 83 | 50 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module WebParsing.ArtSciParser (parseArtSci, getDeptList, fasCalendarURL) where
import Network.HTTP
import Text.HTML.TagSoup
import Text.HTML.TagSoup.Match
import Database.Persist.Sqlite
import Database.JsonParser
import Data.List
import qualified Data.Text as T
import Database.Tables
import WebParsing.ParsingHelp
import Config (dbStr)
fasCalendarURL :: String
fasCalendarURL = "http://www.artsandscience.utoronto.ca/ofr/calendar/"
-- |A collection of pages that do not contain any course information
toDelete :: [String]
toDelete = ["199299398399Big_Ideas_(Faculty_of_Arts_&_Science_Programs).html",
"Joint_Courses.html",
"Writing_in_the_Faculty_of_Arts_&_Science.html",
"crs_bio.htm",
"Life_Sciences.html"]
-- | converts the processed main page and extracts a list of department html pages
getDeptList :: [Tag String] -> [String]
getDeptList tags =
let lists = sections (tagOpenAttrNameLit "ul" "class" (=="simple")) tags
contents = takeWhile (not. isTagCloseName "ul") . head . tail $ lists
as = filter (isTagOpenName "a") contents
rawList = nub $ map (fromAttrib "href") as
in rawList \\ toDelete
-- | Takes an html filename of a department (which are found from getDeptList) and returns
-- a list, where each element is a list of strings and tags relating to a single
-- course found in that department.
getCalendar :: String -> IO ()
getCalendar str = do
let path = fasCalendarURL ++ str
rsp <- simpleHTTP (getRequest path)
body <- getResponseBody rsp
let tags = filter isNotComment $ parseTags (T.pack body)
let coursesSoup = lastH2 tags
let course = map (processCourseToData . (filter isTagText)) $ partitions isCourseTitle coursesSoup
print $ "parsing " ++ str
runSqlite dbStr $ do
runMigration migrateAll
mapM_ insertCourse course
where
isNotComment (TagComment _) = False
isNotComment _ = True
-- Changed this function - wasn't parsing for crs_cjs (or the next one)
lastH2 tags =
let s = sections (isTagOpenName "h2") tags
in
if null s
then
[]
else
last s
isCourseTitle (TagOpen _ attrs) = any (\x -> fst x == "name" && T.length (snd x) == 8) attrs
isCourseTitle _ = False
parseTitleFAS :: CoursePart -> CoursePart
parseTitleFAS (tag:tags, course) =
let (n, t) = T.splitAt 8 $ removeTitleGarbage $ removeLectureSection tag
in (tags, course {title = Just t, name = n})
where removeLectureSection (TagText s) = T.takeWhile (/= '[') s
removeTitleGarbage s = replaceAll ["\160"] "" s
-- |takes a list of tags representing a single course, and returns a course Record
processCourseToData :: [Tag T.Text] -> Course
processCourseToData tags =
let course = emptyCourse
in snd $ (tags, course) ~:
preProcess -:
parseTitleFAS -:
parseDescription -:
parsePrerequisite -:
parseCorequisite -:
parseExclusion -:
parseRecommendedPrep -:
parseDistAndBreadth
-- | parses the entire Arts & Science Course Calendar and inserts courses
-- into the database.
parseArtSci :: IO ()
parseArtSci = do
rsp <- simpleHTTP (getRequest fasCalendarURL)
body <- getResponseBody rsp
let depts = getDeptList $ parseTags body
putStrLn "Parsing Arts and Science Calendar..."
mapM_ getCalendar depts
| cchens/courseography | hs/WebParsing/ArtSciParser.hs | gpl-3.0 | 3,579 | 0 | 16 | 907 | 831 | 427 | 404 | 73 | 4 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Prediction.TrainedModels.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)
--
-- Delete a trained model.
--
-- /See:/ <https://developers.google.com/prediction/docs/developer-guide Prediction API Reference> for @prediction.trainedmodels.delete@.
module Network.Google.Resource.Prediction.TrainedModels.Delete
(
-- * REST Resource
TrainedModelsDeleteResource
-- * Creating a Request
, trainedModelsDelete
, TrainedModelsDelete
-- * Request Lenses
, tmdProject
, tmdId
) where
import Network.Google.Prediction.Types
import Network.Google.Prelude
-- | A resource alias for @prediction.trainedmodels.delete@ method which the
-- 'TrainedModelsDelete' request conforms to.
type TrainedModelsDeleteResource =
"prediction" :>
"v1.6" :>
"projects" :>
Capture "project" Text :>
"trainedmodels" :>
Capture "id" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Delete a trained model.
--
-- /See:/ 'trainedModelsDelete' smart constructor.
data TrainedModelsDelete = TrainedModelsDelete'
{ _tmdProject :: !Text
, _tmdId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'TrainedModelsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tmdProject'
--
-- * 'tmdId'
trainedModelsDelete
:: Text -- ^ 'tmdProject'
-> Text -- ^ 'tmdId'
-> TrainedModelsDelete
trainedModelsDelete pTmdProject_ pTmdId_ =
TrainedModelsDelete'
{ _tmdProject = pTmdProject_
, _tmdId = pTmdId_
}
-- | The project associated with the model.
tmdProject :: Lens' TrainedModelsDelete Text
tmdProject
= lens _tmdProject (\ s a -> s{_tmdProject = a})
-- | The unique name for the predictive model.
tmdId :: Lens' TrainedModelsDelete Text
tmdId = lens _tmdId (\ s a -> s{_tmdId = a})
instance GoogleRequest TrainedModelsDelete where
type Rs TrainedModelsDelete = ()
type Scopes TrainedModelsDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/prediction"]
requestClient TrainedModelsDelete'{..}
= go _tmdProject _tmdId (Just AltJSON)
predictionService
where go
= buildClient
(Proxy :: Proxy TrainedModelsDeleteResource)
mempty
| rueshyna/gogol | gogol-prediction/gen/Network/Google/Resource/Prediction/TrainedModels/Delete.hs | mpl-2.0 | 3,189 | 0 | 14 | 744 | 388 | 233 | 155 | 62 | 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.Content.Orders.Cancel
-- 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)
--
-- Cancels all line items in an order. This method can only be called for
-- non-multi-client accounts.
--
-- /See:/ <https://developers.google.com/shopping-content Content API for Shopping Reference> for @content.orders.cancel@.
module Network.Google.Resource.Content.Orders.Cancel
(
-- * REST Resource
OrdersCancelResource
-- * Creating a Request
, ordersCancel
, OrdersCancel
-- * Request Lenses
, occMerchantId
, occPayload
, occOrderId
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.orders.cancel@ method which the
-- 'OrdersCancel' request conforms to.
type OrdersCancelResource =
"content" :>
"v2" :>
Capture "merchantId" (Textual Word64) :>
"orders" :>
Capture "orderId" Text :>
"cancel" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] OrdersCancelRequest :>
Post '[JSON] OrdersCancelResponse
-- | Cancels all line items in an order. This method can only be called for
-- non-multi-client accounts.
--
-- /See:/ 'ordersCancel' smart constructor.
data OrdersCancel = OrdersCancel'
{ _occMerchantId :: !(Textual Word64)
, _occPayload :: !OrdersCancelRequest
, _occOrderId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'OrdersCancel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'occMerchantId'
--
-- * 'occPayload'
--
-- * 'occOrderId'
ordersCancel
:: Word64 -- ^ 'occMerchantId'
-> OrdersCancelRequest -- ^ 'occPayload'
-> Text -- ^ 'occOrderId'
-> OrdersCancel
ordersCancel pOccMerchantId_ pOccPayload_ pOccOrderId_ =
OrdersCancel'
{ _occMerchantId = _Coerce # pOccMerchantId_
, _occPayload = pOccPayload_
, _occOrderId = pOccOrderId_
}
-- | The ID of the managing account.
occMerchantId :: Lens' OrdersCancel Word64
occMerchantId
= lens _occMerchantId
(\ s a -> s{_occMerchantId = a})
. _Coerce
-- | Multipart request metadata.
occPayload :: Lens' OrdersCancel OrdersCancelRequest
occPayload
= lens _occPayload (\ s a -> s{_occPayload = a})
-- | The ID of the order to cancel.
occOrderId :: Lens' OrdersCancel Text
occOrderId
= lens _occOrderId (\ s a -> s{_occOrderId = a})
instance GoogleRequest OrdersCancel where
type Rs OrdersCancel = OrdersCancelResponse
type Scopes OrdersCancel =
'["https://www.googleapis.com/auth/content"]
requestClient OrdersCancel'{..}
= go _occMerchantId _occOrderId (Just AltJSON)
_occPayload
shoppingContentService
where go
= buildClient (Proxy :: Proxy OrdersCancelResource)
mempty
| rueshyna/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Orders/Cancel.hs | mpl-2.0 | 3,672 | 0 | 15 | 874 | 483 | 287 | 196 | 75 | 1 |
{-# Language CPP #-}
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod
import Control.Exception as CE
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Yaml (decodeEither')
import Database.Persist.Postgresql (PostgresConf)
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload,
widgetFileReload)
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: PostgresConf
-- ^ Configuration settings for accessing the database.
, appRoot :: Maybe Text
-- ^ Base for all generated URLs. If @Nothing@, determined
-- from the request headers.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appDetailedRequestLogging :: Bool
-- ^ Use detailed request logging system
, appShouldLogAll :: Bool
-- ^ Should all log messages be displayed?
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
, appAnalytics :: Maybe Text
-- ^ Google Analytics code
, appAllowDummyAuth :: Bool
, gOAuthCID :: Text
, gOAuthCS :: Text
}
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#if DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabaseConf <- o .: "database"
appRoot <- o .:? "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev
appShouldLogAll <- o .:? "should-log-all" .!= defaultDev
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
appAnalytics <- o .:? "analytics"
appAllowDummyAuth <- o .: "allowDummyAuth"
gOAuthCID <- o .: "gOAuthCID"
gOAuthCS <- o .: "gOAuthCS"
return AppSettings {..}
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either CE.throw id $ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
| enolan/emp-pl-site | Settings.hs | agpl-3.0 | 5,528 | 0 | 12 | 1,527 | 737 | 421 | 316 | -1 | -1 |
--------------------------------------------------------------------------------
-- $Id: ShowM.hs,v 1.1 2004/02/11 16:31:01 graham Exp $
--
-- Copyright (c) 2003, G. KLYNE. All rights reserved.
-- See end of this file for licence information.
--------------------------------------------------------------------------------
-- |
-- Module : ShowM
-- Copyright : (c) 2003, Graham Klyne
-- License : GPL V2
--
-- Maintainer : Graham Klyne
-- Stability : provisional
-- Portability : H98
--
-- This module defines an extension of the Show class for displaying
-- multi-line values. It serves the following purposes:
-- (1) provides a method with greater layout control of multiline values,
-- (2) provides a possibility to override the default Show behaviour
-- for programs that use the extended ShowM interface, and
-- (3) uses a ShowS intermediate value to avoid unnecessary
-- concatenation of long strings.
--
--------------------------------------------------------------------------------
module Swish.HaskellUtils.ShowM
( ShowM(..), showm
)
where
------------------------------------------------------------
-- ShowM framework
------------------------------------------------------------
-- |ShowM is a type class for values that may be formatted in
-- multi-line displays.
class (Show sh) => ShowM sh where
-- |Multi-line value display method
-- Create a multiline displayable form of a value, returned
-- as a ShowS value. The default implementation behaves just
-- like a normal instance of Show.
--
-- This function is intended to allow the calling function some control
-- of multiline displays by providing:
-- (1) the first line of the value is not preceded by any text, so
-- it may be appended to some preceding text on the same line,
-- (2) the supplied line break string is used to separate lines of the
-- formatted text, and may include any desired indentation, and
-- (3) no newline is output following the final line of text.
showms :: String -> sh -> ShowS
showms linebreak val = shows val
-- |showm
-- Return a string representation of a ShowM value.
showm :: (ShowM sh) => String -> sh -> String
showm linebreak val = showms linebreak val ""
--------------------------------------------------------------------------------
--
-- Copyright (c) 2003, G. KLYNE. All rights reserved.
--
-- This file is part of Swish.
--
-- Swish is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- Swish 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 Swish; if not, write to:
-- The Free Software Foundation, Inc.,
-- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
--------------------------------------------------------------------------------
-- $Source: /file/cvsdev/HaskellUtils/ShowM.hs,v $
-- $Author: graham $
-- $Revision: 1.1 $
-- $Log: ShowM.hs,v $
-- Revision 1.1 2004/02/11 16:31:01 graham
-- Move ShowM to HaskellUtils directory.
--
-- Revision 1.2 2003/09/24 18:50:52 graham
-- Revised module format to be Haddock compatible.
--
-- Revision 1.1 2003/06/25 21:20:12 graham
-- Add ShowM class and RDF graph instance to CVS.
-- This is part of reworking N3 formatting logic to support proof display,
-- and other multiline display requirements.
--
| amccausl/Swish | Swish/HaskellUtils/ShowM.hs | lgpl-2.1 | 3,892 | 0 | 8 | 812 | 182 | 135 | 47 | 7 | 1 |
{-|
Module : Reflex.WX.Class
Description : This module contains the basic type definitions used within a
reflex-wx program.
License : wxWindows Library License
Maintainer : joshuabrot@gmail.com
Stability : Experimental
-}
{-# LANGUAGE ExistentialQuantification, FlexibleInstances, FlexibleContexts #-}
{-# LANGUAGE FunctionalDependencies, GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImpredicativeTypes, KindSignatures, MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes, ScopedTypeVariables, TypeFamilies #-}
module Reflex.WX.Class ( AttrC (..)
, Attr
, PropC (..)
, Prop
, Widget (..)
, AnyWindow (..)
, EventMap
, MonadWidget (..)
, find
, dget
, wrapAttr
, unwrapProp
, wrapEvent
, wrapEvent1
) where
import Control.Monad
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.State hiding (get)
import Data.Dependent.Sum
import qualified Data.Dynamic as D
import Data.Typeable
import qualified Graphics.UI.WX as W
import Reflex
import Reflex.Host.Class hiding (fireEvents)
infixr 0 :=,:~
data AttrC t c w a = Attr {
get :: forall m. MonadWidget t m => c w -> m (Dynamic t a),
at :: W.Attr w a
}
data PropC t c w = forall a. Typeable a => AttrC t c w a := a
| forall a. Typeable a => AttrC t c w a :~ Dynamic t a
type Attr t w a = AttrC t (Widget t) w a
type Prop t w = PropC t (Widget t) w
data Widget t w = Widget {
wxwidget :: w,
props :: [Prop t w]
}
type family EventMap (k:: * ) :: *
data AnyWindow = forall w. AW (W.Window w)
class (Typeable t, Reflex t, MonadIO m, MonadHold t m
,MonadReflexCreateTrigger t m, MonadFix m
) => MonadWidget t m | m -> t where
askParent :: m AnyWindow
pushParent :: AnyWindow -> m ()
popParent :: m AnyWindow
addIOEvent :: Event t (IO ()) -> m ()
cacheEvent :: (Typeable w,Eq w,Typeable (EventMap a)) =>
W.Event w a -> Widget t w -> m (Event t (EventMap a))
-> m (Event t (EventMap a))
fireEvents :: (a -> [DSum (EventTrigger t)]) -> m (a -> IO ())
find :: (Typeable a, Typeable t, Reflex t) =>
W.Attr w a -> [Prop t w] -> Maybe (Either a (Dynamic t a))
find _ [] = Nothing
find a ((b := x):r)
| n == m = case D.fromDynamic (D.toDyn x) of
Just x -> Just (Left x)
Nothing -> find a r
where n = W.attrName a
m = W.attrName (at b)
find a ((b :~ x):r)
| n == m = case D.fromDynamic (D.toDyn x) of
Just x -> Just (Right x)
Nothing -> find a r
where n = W.attrName a
m = W.attrName (at b)
find a (_:r) = find a r
dget :: (Typeable a, MonadWidget t m) =>
W.Attr w a -> Widget t w -> m (Dynamic t a)
dget a w = do
case find a (props w) of
Just (Left l) -> return $ constDyn l
Just (Right r) -> return r
Nothing -> do
n <- liftIO $ W.get (wxwidget w) a
return $ constDyn n
wrapAttr :: Typeable a => W.Attr w a -> Attr t w a
wrapAttr a = Attr (dget a) a
unwrapProp :: MonadWidget t m => w -> Prop t w -> m (W.Prop w)
unwrapProp w (a := v) = return $ (at a) W.:= v
unwrapProp w (a :~ v) = do
addIOEvent $ fmap (\x -> W.set w [(at a) W.:= x]) (updated v)
cv <- sample $ current v
return $ (at a) W.:= cv
type instance EventMap (IO ()) = ()
wrapEvent :: forall t w m. (Typeable w, Eq w, MonadWidget t m) =>
W.Event w (IO ()) -> Widget t w -> m (Event t ())
wrapEvent e w = cacheEvent e w $ do
let fire :: EventTrigger t () -> [DSum (EventTrigger t)]
fire et = [et :=> ()]
f <- fireEvents fire
n <- newEventWithTrigger $ \et -> do
W.set (wxwidget w) [W.on e W.:= f et]
return $ W.set (wxwidget w) [W.on e W.:= W.propagateEvent]
return n
type instance EventMap (a -> IO ()) = a
wrapEvent1 :: forall t w m a. (Typeable a, Typeable w, Eq w, MonadWidget t m) =>
W.Event w (a -> IO ()) -> Widget t w -> m (Event t a)
wrapEvent1 e w = cacheEvent e w $ do
let fire :: (EventTrigger t a,a) -> [DSum (EventTrigger t)]
fire (et,a) = [et :=> a]
f <- fireEvents fire
n <- newEventWithTrigger $ \et -> do
W.set (wxwidget w) [W.on e W.:= \a -> f (et,a)]
return $ W.set (wxwidget w) [W.on e W.:= \_ -> W.propagateEvent]
return n
| Pamelloes/reflex-wx | src/main/Reflex/WX/Class.hs | lgpl-2.1 | 4,634 | 0 | 18 | 1,536 | 1,912 | 987 | 925 | 107 | 3 |
module ViperVM.Library.FloatMatrixAdd (
builtin, function, metaKernel, kernels
) where
import Control.Applicative ( (<$>) )
import ViperVM.VirtualPlatform.FunctionalKernel hiding (metaKernel,proto)
import ViperVM.VirtualPlatform.MetaObject
import ViperVM.VirtualPlatform.Descriptor
import ViperVM.VirtualPlatform.MetaKernel hiding (proto,name,kernels)
import ViperVM.VirtualPlatform.Objects.Matrix
import ViperVM.VirtualPlatform.Object
import ViperVM.Platform.KernelParameter
import ViperVM.Platform.Kernel
import ViperVM.Platform.Peer.KernelPeer
import qualified ViperVM.Library.OpenCL.FloatMatrixAdd as CL
----------------------------------------
-- Builtin & Function
---------------------------------------
builtin :: MakeBuiltin
builtin = makeBuiltinIO function
function :: IO FunctionalKernel
function = FunctionalKernel proto makeParams makeResult <$> metaKernel
where
proto = Prototype {
inputs = [MatrixType,MatrixType],
output = MatrixType
}
makeParams args = do
let [a,b] = args
c <- allocate (descriptor a)
return [a,b,c]
makeResult args = last args
----------------------------------------
-- MetaKernel
---------------------------------------
metaKernel :: IO MetaKernel
metaKernel = MetaKernel name proto conf <$> kernels
where
name = "FloatMatrixAdd"
proto = [
Arg ReadOnly "a",
Arg ReadOnly "b",
Arg WriteOnly "c"
]
conf :: [ObjectPeer] -> [KernelParameter]
conf objs = params
where
[MatrixObject ma, MatrixObject mb, MatrixObject mc] = objs
params =
[WordParam (fromIntegral width),
WordParam (fromIntegral height),
BufferParam (matrixBuffer ma),
WordParam (fromIntegral lda),
WordParam (fromIntegral (matrixOffset ma `div` 4)),
BufferParam (matrixBuffer mb),
WordParam (fromIntegral ldb),
WordParam (fromIntegral (matrixOffset mb `div` 4)),
BufferParam (matrixBuffer mc),
WordParam (fromIntegral ldc),
WordParam (fromIntegral (matrixOffset mc `div` 4))]
(width, height) = matrixDimensions ma
lda = ((matrixWidth ma) * 4 + (matrixPadding ma)) `div` 4
ldb = ((matrixWidth mb) * 4 + (matrixPadding mb)) `div` 4
ldc = ((matrixWidth mc) * 4 + (matrixPadding mc)) `div` 4
----------------------------------------
-- Kernels
---------------------------------------
kernels :: IO [Kernel]
kernels = initKernelsIO [
CLKernel <$> CL.kernel
]
| hsyl20/HViperVM | lib/ViperVM/Library/FloatMatrixAdd.hs | lgpl-3.0 | 2,695 | 0 | 15 | 691 | 686 | 386 | 300 | 54 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE ForeignFunctionInterface #-}
-- NOTE: This file is a copy of System.Plugins.Load. It has been patched to
-- expose some internal functionality (loadObjectFile, which used to be part
-- of load). When the patch is integrated into the plugins package, this file
-- can be removed.
--
-- Copyright (C) 2004-5 Don Stewart - http://www.cse.unsw.edu.au/~dons
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
-- USA
--
-- | An interface to the GHC runtime's dynamic linker, providing runtime
-- loading and linking of Haskell object files, commonly known as
-- /plugins/.
module Barley.AltLoad (
-- * The @LoadStatus@ type
LoadStatus(..)
-- * High-level interface
, load
, load_
, dynload
, pdynload
, pdynload_
, unload
, unloadAll
, reload
, Module(..)
-- * Low-level interface
, initLinker -- start it up
, loadObjectFile -- load and resolve a .o and all its dependencies
, loadModule -- load a vanilla .o
, loadFunction -- retrieve a function from an object
, loadFunction_ -- retrieve a function from an object
, loadPackageFunction
, loadPackage -- load a ghc library and its cbits
, unloadPackage -- unload a ghc library and its cbits
, loadPackageWith -- load a pkg using the package.conf provided
, loadShared -- load a .so object file
, resolveObjs -- and resolve symbols
, loadRawObject -- load a bare .o. no dep chasing, no .hi file reading
, Symbol
, getImports
) where
-- #include "../../../config.h"
import System.Plugins.Make ( build )
import System.Plugins.Env
import System.Plugins.Utils
import System.Plugins.Consts ( sysPkgSuffix, hiSuf, prefixUnderscore )
import System.Plugins.LoadTypes
-- import Language.Hi.Parser
import BinIface
import HscTypes
import Module (moduleName, moduleNameString, packageIdString)
import HscMain (newHscEnv)
import TcRnMonad (initTcRnIf)
import Data.Dynamic ( fromDynamic, Dynamic )
import Data.Typeable ( Typeable )
import Data.List ( isSuffixOf, nub, nubBy )
import Control.Monad ( when, filterM, liftM )
import System.Directory ( doesFileExist, removeFile )
import Foreign.C.String ( CString, withCString, peekCString )
import GHC ( defaultCallbacks )
import GHC.Ptr ( Ptr(..), nullPtr )
import GHC.Exts ( addrToHValue# )
import GHC.Prim ( unsafeCoerce# )
#if DEBUG
import System.IO ( hFlush, stdout )
#endif
import System.IO ( hClose )
ifaceModuleName :: ModIface -> String
ifaceModuleName = moduleNameString . moduleName . mi_module
readBinIface' :: FilePath -> IO ModIface
readBinIface' hi_path = do
-- kludgy as hell
e <- newHscEnv defaultCallbacks undefined
initTcRnIf 'r' e undefined undefined (readBinIface IgnoreHiWay QuietBinIFaceReading hi_path)
-- TODO need a loadPackage p package.conf :: IO () primitive
--
-- | The @LoadStatus@ type encodes the return status of functions that
-- perform dynamic loading in a type isomorphic to 'Either'. Failure
-- returns a list of error strings, success returns a reference to a
-- loaded module, and the Haskell value corresponding to the symbol that
-- was indexed.
--
data LoadStatus a
= LoadSuccess Module a
| LoadFailure Errors
--
-- | 'load' is the basic interface to the dynamic loader. A call to
-- 'load' imports a single object file into the caller's address space,
-- returning the value associated with the symbol requested. Libraries
-- and modules that the requested module depends upon are loaded and
-- linked in turn.
--
-- The first argument is the path to the object file to load, the second
-- argument is a list of directories to search for dependent modules.
-- The third argument is a list of paths to user-defined, but
-- unregistered, /package.conf/ files. The 'Symbol' argument is the
-- symbol name of the value you with to retrieve.
--
-- The value returned must be given an explicit type signature, or
-- provided with appropriate type constraints such that Haskell compiler
-- can determine the expected type returned by 'load', as the return
-- type is notionally polymorphic.
--
-- Example:
--
-- > do mv <- load "Plugin.o" ["api"] [] "resource"
-- > case mv of
-- > LoadFailure msg -> print msg
-- > LoadSuccess _ v -> return v
--
load :: FilePath -- ^ object file
-> [FilePath] -- ^ any include paths
-> [PackageConf] -- ^ list of package.conf paths
-> Symbol -- ^ symbol to find
-> IO (LoadStatus a)
load obj incpaths pkgconfs sym = do
m <- loadObjectFile obj incpaths pkgconfs
v <- loadFunction m sym
return $ case v of
Nothing -> LoadFailure ["load: couldn't find symbol <<"++sym++">>"]
Just a -> LoadSuccess m a
--
-- | Like load, but doesn't want a package.conf arg (they are rarely used)
--
load_ :: FilePath -> [FilePath] -> Symbol -> IO (LoadStatus a)
load_ o i s = load o i [] s
--
-- A work-around for Dynamics. The keys used to compare two TypeReps are
-- somehow not equal for the same type in hs-plugin's loaded objects.
-- Solution: implement our own dynamics...
--
-- The problem with dynload is that it requires the plugin to export
-- a value that is a Dynamic (in our case a (TypeRep,a) pair). If this
-- is not the case, we core dump. Use pdynload if you don't trust the
-- user to supply you with a Dynamic
--
dynload :: Typeable a
=> FilePath
-> [FilePath]
-> [PackageConf]
-> Symbol
-> IO (LoadStatus a)
dynload obj incpaths pkgconfs sym = do
s <- load obj incpaths pkgconfs sym
case s of e@(LoadFailure _) -> return e
LoadSuccess m dyn_v -> return $
case fromDynamic (unsafeCoerce# dyn_v :: Dynamic) of
Just v' -> LoadSuccess m v'
Nothing -> LoadFailure ["Mismatched types in interface"]
------------------------------------------------------------------------
--
-- The super-replacement for dynload
--
-- Use GHC at runtime so we get staged type inference, providing full
-- power dynamics, *on module interfaces only*. This is quite suitable
-- for plugins, of coures :)
--
-- TODO where does the .hc file go in the call to build() ?
--
pdynload :: FilePath -- ^ object to load
-> [FilePath] -- ^ include paths
-> [PackageConf] -- ^ package confs
-> Type -- ^ API type
-> Symbol -- ^ symbol
-> IO (LoadStatus a)
pdynload object incpaths pkgconfs ty sym = do
#if DEBUG
putStr "Checking types ... " >> hFlush stdout
#endif
errors <- unify object incpaths [] ty sym
#if DEBUG
putStrLn "done"
#endif
if null errors
then load object incpaths pkgconfs sym
else return $ LoadFailure errors
--
-- | Like pdynload, but you can specify extra arguments to the
-- typechecker.
--
pdynload_ :: FilePath -- ^ object to load
-> [FilePath] -- ^ include paths for loading
-> [PackageConf] -- ^ any extra package.conf files
-> [Arg] -- ^ extra arguments to ghc, when typechecking
-> Type -- ^ expected type
-> Symbol -- ^ symbol to load
-> IO (LoadStatus a)
pdynload_ object incpaths pkgconfs args ty sym = do
#if DEBUG
putStr "Checking types ... " >> hFlush stdout
#endif
errors <- unify object incpaths args ty sym
#if DEBUG
putStrLn "done"
#endif
if null errors
then load object incpaths pkgconfs sym
else return $ LoadFailure errors
------------------------------------------------------------------------
-- run the typechecker over the constraint file
--
-- Problem: if the user depends on a non-auto package to build the
-- module, then that package will not be in scope when we try to build
-- the module, when performing `unify'. Normally make() will handle this
-- (as it takes extra ghc args). pdynload ignores these, atm -- but it
-- shouldn't. Consider a pdynload() that accepts extra -package flags?
--
-- Also, pdynload() should accept extra in-scope modules.
-- Maybe other stuff we want to hack in here.
--
unify :: FilePath -> [[Char]] -> [String] -> String -> String -> IO [String]
unify obj incs args ty sym = do
(tmpf,hdl) <- mkTemp
(tmpf1,hdl1) <- mkTemp -- and send .hi file here.
hClose hdl1
let nm = mkModid (basename tmpf)
src = mkTest nm (hierize' . mkModid . hierize $ obj)
(fst $ break (=='.') ty) ty sym
is = map ("-i"++) incs -- api
i = "-i" ++ dirname obj -- plugin
hWrite hdl src
e <- build tmpf tmpf1 (i:is++args++["-fno-code","-ohi "++tmpf1])
mapM_ removeFile [tmpf,tmpf1]
return e
where
-- fix up hierarchical names
hierize [] = []
hierize ('/':cs) = '\\' : hierize cs
hierize (c:cs) = c : hierize cs
hierize'[] = []
hierize' ('\\':cs) = '.' : hierize' cs
hierize' (c:cs) = c : hierize' cs
mkTest :: String -> String -> String -> String -> String -> String
mkTest modnm plugin api ty sym =
"module "++ modnm ++" where" ++
"\nimport qualified " ++ plugin ++
"\nimport qualified " ++ api ++
"{-# LINE 1 \"<typecheck>\" #-}" ++
"\n_ = "++ plugin ++"."++ sym ++" :: "++ty
------------------------------------------------------------------------
{-
--
-- old version that tried to rip stuff from .hi files
--
pdynload obj incpaths pkgconfs sym ty = do
(m, v) <- load obj incpaths pkgconfs sym
ty' <- mungeIface sym obj
if ty == ty'
then return $ Just (m, v)
else return Nothing -- mismatched types
where
-- grab the iface output from GHC. find the line relevant to our
-- symbol. grab the string rep of the type.
mungeIface sym o = do
let hi = replaceSuffix o hiSuf
(out,_) <- exec ghc ["--show-iface", hi]
case find (\s -> (sym ++ " :: ") `isPrefixOf` s) out of
Nothing -> return undefined
Just v -> do let v' = drop 3 $ dropWhile (/= ':') v
return v'
-}
{-
--
-- a version of load the also unwraps and types a Dynamic object
--
dynload2 :: Typeable a =>
FilePath ->
FilePath ->
Maybe [PackageConf] ->
Symbol ->
IO (Module, a)
dynload2 obj incpath pkgconfs sym = do
(m, v) <- load obj incpath pkgconfs sym
case fromDynamic v of
Nothing -> panic $ "load: couldn't type "++(show v)
Just a -> return (m,a)
-}
------------------------------------------------------------------------
--
-- | unload a module (not its dependencies)
-- we have the dependencies, so cascaded unloading is possible
--
-- once you unload it, you can't 'load' it again, you have to 'reload'
-- it. Cause we don't unload all the dependencies
--
unload :: Module -> IO ()
unload m = rmModuleDeps m >> unloadObj m
------------------------------------------------------------------------
--
-- | unload a module and its dependencies
-- we have the dependencies, so cascaded unloading is possible
--
unloadAll :: Module -> IO ()
unloadAll m = do moduleDeps <- getModuleDeps m
rmModuleDeps m
mapM_ unloadAll moduleDeps
unload m
--
-- | this will be nice for panTHeon, needs thinking about the interface
-- reload a single object file. don't care about depends, assume they
-- are loaded. (should use state to store all this)
--
-- assumes you've already done a 'load'
--
-- should factor the code
--
reload :: Module -> Symbol -> IO (LoadStatus a)
reload m@(Module{path = p, iface = hi}) sym = do
unloadObj m -- unload module (and delete)
#if DEBUG
putStr ("Reloading "++(mname m)++" ... ") >> hFlush stdout
#endif
m_ <- loadObject p . Object . ifaceModuleName $ hi -- load object at path p
let m' = m_ { iface = hi }
resolveObjs (unloadAll m)
#if DEBUG
putStrLn "done" >> hFlush stdout
#endif
v <- loadFunction m' sym
return $ case v of
Nothing -> LoadFailure ["load: couldn't find symbol <<"++sym++">>"]
Just a -> LoadSuccess m' a
--
-- This is a stripped-down version of Andre Pang's runtime_loader,
-- which in turn is based on GHC's ghci\/ObjLinker.lhs binding
--
-- Load and unload\/Haskell modules at runtime. This is not really
-- \'dynamic loading\', as such -- that implies that you\'re working
-- with proper shared libraries, whereas this is far more simple and
-- only loads object files. But it achieves the same goal: you can
-- load a Haskell module at runtime, load a function from it, and run
-- the function. I have no idea if this works for types, but that
-- doesn\'t mean that you can\'t try it :).
--
-- read $fptools\/ghc\/compiler\/ghci\/ObjLinker.lhs for how to use this stuff
--
-- | Call the initLinker function first, before calling any of the other
-- functions in this module - otherwise you\'ll get unresolved symbols.
-- initLinker :: IO ()
-- our initLinker transparently calls the one in GHC
--
-- | This is a mid-level interface to the dynamic loader. A call to
-- 'loadObjectFile' imports a single object file into the caller's address,
-- space returning the 'Module' associated with it. Libraries and modules that
-- the requested module depends upon are loaded and linked in turn.
--
-- The first argument is the path to the object file to load, the second
-- argument is a list of directories to search for dependent modules.
-- The third argument is a list of paths to user-defined, but
-- unregistered, /package.conf/ files.
loadObjectFile :: FilePath -- ^ object file
-> [FilePath] -- ^ any include paths
-> [PackageConf] -- ^ list of package.conf paths
-> IO Module
loadObjectFile obj incpaths pkgconfs = do
initLinker
-- load extra package information
mapM_ addPkgConf pkgconfs
(hif,moduleDeps) <- loadDepends obj incpaths
-- why is this the package name?
#if DEBUG
putStr (' ':(decode $ ifaceModuleName hif)) >> hFlush stdout
#endif
m' <- loadObject obj . Object . ifaceModuleName $ hif
let m = m' { iface = hif }
resolveObjs (mapM_ unloadAll (m:moduleDeps))
#if DEBUG
putStrLn " ... done" >> hFlush stdout
#endif
addModuleDeps m' moduleDeps
return m
--
-- | Load a function from a module (which must be loaded and resolved first).
--
loadFunction :: Module -- ^ The module the value is in
-> String -- ^ Symbol name of value
-> IO (Maybe a) -- ^ The value you want
loadFunction (Module { iface = i }) valsym
= loadFunction_ (ifaceModuleName i) valsym
loadFunction_ :: String
-> String
-> IO (Maybe a)
loadFunction_ = loadFunction__ Nothing
loadFunction__ :: Maybe String
-> String
-> String
-> IO (Maybe a)
loadFunction__ pkg m valsym
= do let symbol = prefixUnderscore++(maybe "" (\p -> encode p++"_") pkg)
++encode m++"_"++(encode valsym)++"_closure"
#if DEBUG
putStrLn $ "Looking for <<"++symbol++">>"
#endif
ptr@(Ptr addr) <- withCString symbol c_lookupSymbol
if (ptr == nullPtr)
then return Nothing
else case addrToHValue# addr of
(# hval #) -> return ( Just hval )
-- | Loads a function from a package module, given the package name,
-- module name and symbol name.
loadPackageFunction :: String -- ^ Package name, including version number.
-> String -- ^ Module name
-> String -- ^ Symbol to lookup in the module
-> IO (Maybe a)
loadPackageFunction pkgName modName functionName =
do loadPackage pkgName
resolveObjs (unloadPackage pkgName)
loadFunction__ (Just pkgName) modName functionName
--
-- | Load a GHC-compiled Haskell vanilla object file.
-- The first arg is the path to the object file
--
-- We make it idempotent to stop the nasty problem of loading the same
-- .o twice. Also the rts is a very special package that is already
-- loaded, even if we ask it to be loaded. N.B. we should insert it in
-- the list of known packages.
--
-- NB the environment stores the *full path* to an object. So if you
-- want to know if a module is already loaded, you need to supply the
-- *path* to that object, not the name.
--
-- NB -- let's try just the module name.
--
-- loadObject loads normal .o objs, and packages too. .o objs come with
-- a nice canonical Z-encoded modid. packages just have a simple name.
-- Do we want to ensure they won't clash? Probably.
--
--
-- the second argument to loadObject is a string to use as the unique
-- identifier for this object. For normal .o objects, it should be the
-- Z-encoded modid from the .hi file. For archives\/packages, we can
-- probably get away with the package name
--
loadObject :: FilePath -> Key -> IO Module
loadObject p ky@(Object k) = loadObject' p ky k
loadObject p ky@(Package k) = loadObject' p ky k
loadObject' :: FilePath -> Key -> String -> IO Module
loadObject' p ky k
| ("HSrts"++sysPkgSuffix) `isSuffixOf` p = return (emptyMod p)
| otherwise
= do alreadyLoaded <- isLoaded k
when (not alreadyLoaded) $ do
r <- withCString p c_loadObj
when (not r) (panic $ "Could not load module `"++p++"'")
addModule k (emptyMod p) -- needs to Z-encode module name
return (emptyMod p)
where emptyMod q = Module q (mkModid q) Vanilla undefined ky
--
-- load a single object. no dependencies. You should know what you're
-- doing.
--
loadModule :: FilePath -> IO Module
loadModule obj = do
let hifile = replaceSuffix obj hiSuf
exists <- doesFileExist hifile
if (not exists)
then error $ "No .hi file found for "++show obj
else do hiface <- readBinIface' hifile
loadObject obj (Object (ifaceModuleName hiface))
--
-- | Load a generic .o file, good for loading C objects.
-- You should know what you're doing..
-- Returns a fairly meaningless iface value.
--
loadRawObject :: FilePath -> IO Module
loadRawObject obj = loadObject obj (Object k)
where
k = encode (mkModid obj) -- Z-encoded module name
--
-- | Resolve (link) the modules loaded by the 'loadObject' function.
--
resolveObjs :: IO a -> IO ()
resolveObjs unloadLoaded
= do r <- c_resolveObjs
when (not r) $ unloadLoaded >> panic "resolvedObjs failed."
-- | Unload a module
unloadObj :: Module -> IO ()
unloadObj (Module { path = p, kind = k, key = ky }) = case k of
Vanilla -> withCString p $ \c_p -> do
removed <- rmModule name
when (removed) $ do r <- c_unloadObj c_p
when (not r) (panic "unloadObj: failed")
Shared -> return () -- can't unload .so?
where name = case ky of Object s -> s ; Package pk -> pk
--
-- | from ghci\/ObjLinker.c
--
-- Load a .so type object file.
--
loadShared :: FilePath -> IO Module
loadShared str = do
#if DEBUG
putStrLn $ " shared: " ++ str
#endif
maybe_errmsg <- withCString str $ \dll -> c_addDLL dll
if maybe_errmsg == nullPtr
then return (Module str (mkModid str) Shared undefined (Package (mkModid str)))
else do e <- peekCString maybe_errmsg
panic $ "loadShared: couldn't load `"++str++"\' because "++e
--
-- Load a -package that we might need, implicitly loading the cbits too
-- The argument is the name of package (e.g. \"concurrent\")
--
-- How to find a package is determined by the package.conf info we store
-- in the environment. It is just a matter of looking it up.
--
-- Not printing names of dependent pkgs
--
loadPackage :: String -> IO ()
loadPackage p = do
#if DEBUG
putStr (' ':p) >> hFlush stdout
#endif
(libs,dlls) <- lookupPkg p
mapM_ (\l -> loadObject l (Package (mkModid l))) libs
#if DEBUG
putStr (' ':show libs) >> hFlush stdout
putStr (' ':show dlls) >> hFlush stdout
#endif
mapM_ loadShared dlls
--
-- Unload a -package, that has already been loaded. Unload the cbits
-- too. The argument is the name of the package.
--
-- May need to check if it exists.
--
-- Note that we currently need to unload everything. grumble grumble.
--
-- We need to add the version number to the package name with 6.4 and
-- over. "yi-0.1" for example. This is a bug really.
--
unloadPackage :: String -> IO ()
unloadPackage pkg = do
let pkg' = takeWhile (/= '-') pkg -- in case of *-0.1
libs <- liftM (\(a,_) -> (filter (isSublistOf pkg') ) a) (lookupPkg pkg)
flip mapM_ libs $ \p -> withCString p $ \c_p -> do
r <- c_unloadObj c_p
when (not r) (panic "unloadObj: failed")
rmModule (mkModid p) -- unrecord this module
--
-- load a package using the given package.conf to help
-- TODO should report if it doesn't actually load the package, instead
-- of mapM_ doing nothing like above.
--
loadPackageWith :: String -> [PackageConf] -> IO ()
loadPackageWith p pkgconfs = do
#if DEBUG
putStr "Loading package" >> hFlush stdout
#endif
mapM_ addPkgConf pkgconfs
loadPackage p
#if DEBUG
putStrLn " done"
#endif
-- ---------------------------------------------------------------------
-- module dependency loading
--
-- given an Foo.o vanilla object file, supposed to be a plugin compiled
-- by our library, find the associated .hi file. If this is found, load
-- the dependencies, packages first, then the modules. If it doesn't
-- exist, assume the user knows what they are doing and continue. The
-- linker will crash on them anyway. Second argument is any include
-- paths to search in
--
-- ToDo problem with absolute and relative paths, and different forms of
-- relative paths. A user may cause a dependency to be loaded, which
-- will search the incpaths, and perhaps find "./Foo.o". The user may
-- then explicitly load "Foo.o". These are the same, and the loader
-- should ignore the second load request. However, isLoaded will say
-- that "Foo.o" is not loaded, as the full string is used as a key to
-- the modenv fm. We need a canonical form for the keys -- is basename
-- good enough?
--
loadDepends :: FilePath -> [FilePath] -> IO (ModIface,[Module])
loadDepends obj incpaths = do
let hifile = replaceSuffix obj hiSuf
exists <- doesFileExist hifile
if (not exists)
then do
#if DEBUG
putStrLn "No .hi file found." >> hFlush stdout
#endif
return (undefined,[]) -- could be considered fatal
else do hiface <- readBinIface' hifile
let ds = mi_deps hiface
-- remove ones that we've already loaded
ds' <- filterM loaded . map (moduleNameString . fst) . dep_mods $ ds
-- now, try to generate a path to the actual .o file
-- fix up hierachical names
let mods_ = map (\s -> (s, map (\c ->
if c == '.' then '/' else c) $ s)) ds'
-- construct a list of possible dependent modules to load
let mods = concatMap (\p ->
map (\(hi,m) -> (hi,p </> m++".o")) mods_) incpaths
-- remove modules that don't exist
mods' <- filterM (\(_,y) -> doesFileExist y) $
nubBy (\v u -> snd v == snd u) mods
-- now remove duplicate valid paths to the same object
let mods'' = nubBy (\v u -> fst v == fst u) mods'
-- and find some packages to load, as well.
let ps = dep_pkgs ds
ps' <- filterM loaded . map packageIdString . nub $ ps
#if DEBUG
when (not (null ps')) $
putStr "Loading package" >> hFlush stdout
#endif
mapM_ loadPackage ps'
#if DEBUG
when (not (null ps')) $
putStr " ... linking ... " >> hFlush stdout
#endif
resolveObjs (mapM_ unloadPackage ps')
#if DEBUG
when (not (null ps')) $ putStrLn "done"
putStr "Loading object"
mapM_ (\(m,_) -> putStr (" "++ m) >> hFlush stdout) mods''
#endif
moduleDeps <- mapM (\(hi,m) -> loadObject m (Object hi)) mods''
return (hiface,moduleDeps)
-- ---------------------------------------------------------------------
-- Nice interface to .hi parser
--
getImports :: String -> IO [String]
getImports m = do
hi <- readBinIface' (m ++ hiSuf)
return . map (moduleNameString . fst) . dep_mods . mi_deps $ hi
-- ---------------------------------------------------------------------
-- C interface
--
foreign import ccall safe "lookupSymbol"
c_lookupSymbol :: CString -> IO (Ptr a)
foreign import ccall unsafe "loadObj"
c_loadObj :: CString -> IO Bool
foreign import ccall unsafe "unloadObj"
c_unloadObj :: CString -> IO Bool
foreign import ccall unsafe "resolveObjs"
c_resolveObjs :: IO Bool
foreign import ccall unsafe "addDLL"
c_addDLL :: CString -> IO CString
foreign import ccall unsafe "initLinker"
initLinker :: IO ()
| mzero/barley | src/Barley/AltLoad.hs | apache-2.0 | 26,870 | 0 | 22 | 7,541 | 4,547 | 2,428 | 2,119 | 294 | 5 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- :script test/Spark/Core/Internal/PathsSpec.hs
module Spark.Core.Internal.PathsSpec where
import Test.Hspec
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as C8
import qualified Data.Text as T
import Spark.Core.StructuresInternal
import Spark.Core.Functions
import Spark.Core.Column
import Spark.Core.Dataset
import Spark.Core.TestUtils
import Spark.Core.Internal.Paths
import Spark.Core.Internal.DAGStructures
import Spark.Core.Internal.DAGFunctions
import Spark.Core.Internal.ComputeDag
import Spark.Core.Internal.PathsUntyped
import Spark.Core.Internal.Utilities
import Spark.Core.Internal.DatasetFunctions
import Spark.Core.Internal.DatasetStructures
data MyV = MyV {
mvId :: VertexId,
mvLogical :: [MyV],
mvParents :: [MyV]
} deriving (Eq)
instance Show MyV where
show v = "MyV(" ++ (C8.unpack . unVertexId . mvId $ v) ++ ")"
assignPaths :: UntypedNode -> [UntypedNode]
assignPaths n =
let cgt = buildCGraph n :: DagTry (ComputeDag UntypedNode NodeEdge)
cg = forceRight cgt
acgt = assignPathsUntyped cg
ncg = forceRight acgt
in graphDataLexico . tieNodes $ ncg
instance GraphVertexOperations MyV where
vertexToId = mvId
expandVertexAsVertices = mvParents
myv :: String -> [MyV] -> [MyV] -> MyV
myv s logical inner = MyV (VertexId (C8.pack s)) logical inner
myvToVertex :: MyV -> Vertex MyV
myvToVertex x = Vertex (mvId x) x
buildScopes :: [MyV] -> Scopes
buildScopes l = iGetScopes0 l' fun where
l' = myvToVertex <$> l
fun vx = ParentSplit {
psLogical = myvToVertex <$> (mvLogical . vertexData $ vx),
psInner = myvToVertex <$> (mvParents . vertexData $ vx) }
simple :: [(Maybe String, [String])] -> Scopes
simple [] = M.empty
simple ((ms, ss) : t) =
let
key = VertexId . C8.pack <$> ms
vals = VertexId . C8.pack <$> ss
new = M.singleton key (S.fromList vals)
in mergeScopes new (simple t)
gatherings :: [(String, [[String]])] -> M.Map VertexId [[VertexId]]
gatherings [] = M.empty
gatherings ((key, paths) : t) =
let
k = VertexId . C8.pack $ key
ps = (VertexId . C8.pack <$>) <$> paths
new = M.singleton k ps
in M.unionWith (++) new (gatherings t)
gatherPaths' :: [MyV] -> M.Map VertexId [[VertexId]]
gatherPaths' = gatherPaths . buildScopes
spec :: Spec
spec = do
describe "Tests on paths" $ do
it "nothing" $ do
buildScopes [] `shouldBe` simple []
it "no parent" $ do
let v0 = myv "v0" [] []
let res = [ (Nothing, ["v0"]), (Just "v0", []) ]
buildScopes [v0] `shouldBe` simple res
it "one logical parent" $ do
let v0 = myv "v0" [] []
let v1 = myv "v1" [v0] []
let res = [ (Nothing, ["v0", "v1"])
, (Just "v1", [])
, (Just "v0", []) ]
buildScopes [v1, v0] `shouldBe` simple res
it "one inner parent" $ do
let v0 = myv "v0" [] []
let v1 = myv "v1" [] [v0]
let res = [ (Nothing, ["v1"])
, (Just "v1", ["v0"])
, (Just "v0", []) ]
buildScopes [v1, v0] `shouldBe` simple res
it "logical scoping over a parent" $ do
let v0 = myv "v0" [] []
let v1 = myv "v1" [v0] []
let v2 = myv "v2" [v0] [v1]
let res = [ (Nothing, ["v0", "v2"])
, (Just "v0", [])
, (Just "v1", [])
, (Just "v2", ["v1"]) ]
buildScopes [v2] `shouldBe` simple res
it "common ancestor" $ do
let top = myv "top" [] []
let inner = myv "inner" [top] []
let v1 = myv "v1" [top] [inner]
let v2 = myv "v2" [top] [inner]
let res = [ (Nothing, ["top", "v1", "v2"])
, (Just "inner", [])
, (Just "top", [])
, (Just "v1", ["inner"])
, (Just "v2", ["inner"]) ]
buildScopes [v1, v2] `shouldBe` simple res
it "common ancestor, unbalanced" $ do
let top = myv "top" [] []
let inner = myv "inner" [top] []
let v1 = myv "v1" [top] [inner]
let v2 = myv "v2" [] [inner]
let res = [ (Nothing, ["top", "v1", "v2"])
, (Just "inner", [])
, (Just "top", [])
, (Just "v1", ["inner"])
, (Just "v2", ["inner", "top"]) ]
buildScopes [v1, v2] `shouldBe` simple res
describe "Path gatherings" $ do
it "nothing" $ do
gatherPaths' [] `shouldBe` gatherings []
it "no parent" $ do
let v0 = myv "v0" [] []
let res = [("v0", [[]])]
gatherPaths' [v0] `shouldBe` gatherings res
it "one logical parent" $ do
let v0 = myv "v0" [] []
let v1 = myv "v1" [v0] []
let res = [ ("v1", [[]])
, ("v0", [[]])]
gatherPaths' [v1] `shouldBe` gatherings res
it "one inner parent" $ do
let v0 = myv "v0" [] []
let v1 = myv "v1" [] [v0]
let res = [ ("v1", [[]])
, ("v0", [["v1"]])]
gatherPaths' [v1] `shouldBe` gatherings res
it "logical scoping over a parent" $ do
let v0 = myv "v0" [] []
let v1 = myv "v1" [v0] []
let v2 = myv "v2" [v0] [v1]
let res = [ ("v0", [[]])
, ("v1", [["v2"]])
, ("v2", [[]]) ]
gatherPaths' [v2] `shouldBe` gatherings res
it "common ancestor" $ do
let top = myv "top" [] []
let inner = myv "inner" [top] []
let v1 = myv "v1" [top] [inner]
let v2 = myv "v2" [top] [inner]
let res = [ ("inner", [["v1"], ["v2"]])
, ("top", [[]])
, ("v1", [[]])
, ("v2", [[]]) ]
gatherPaths' [v1, v2] `shouldBe` gatherings res
describe "Real paths" $ do
xit "simple test" $ do
let c0 = constant (1 :: Int) @@ "c0"
let c1 = identity c0 @@ "c1"
let c2 = identity c1 `logicalParents` [untyped c0] @@ "c2"
nodeId <$> nodeParents c1 `shouldBe` [nodeId c0]
nodeId <$> nodeParents c2 `shouldBe` [nodeId c1]
let withParents = T.unpack . catNodePath . nodePath <$> assignPaths (untyped c2)
withParents `shouldBe` ["c0", "c2/c1", "c2"]
xit "simple test 2" $ do
let ds = dataset ([1 ,2, 3, 4]::[Int]) @@ "ds"
let c = count (asCol ds) @@ "c"
let c2 = (c + (identity c @@ "id")) `logicalParents` [untyped ds] @@ "c2"
let withParents = T.unpack . catNodePath . nodePath <$> assignPaths (untyped c2)
withParents `shouldBe` ["ds", "c2/c","c2/id","c2"]
| tjhunter/karps | haskell/test/Spark/Core/Internal/PathsSpec.hs | apache-2.0 | 6,509 | 0 | 22 | 1,861 | 2,726 | 1,444 | 1,282 | 173 | 1 |
data WhyNot a = Nah | Sure a
deriving Show
instance Functor WhyNot where
fmap f (Sure a) = Sure (f a)
fmap f Nah = Nah
instance Applicative WhyNot where
(<*>) (Sure f) (Sure a) = Sure (f a)
(<*>) Nah _ = Nah
(<*>) (Sure f) Nah = Nah
pure a = Sure a
instance Monad WhyNot where
(>>=) (Sure a) f = (f a)
(>>=) Nah f = Nah
return a = Sure a
fail _ = Nah
safeRoot :: Double -> WhyNot Double
safeRoot x =
if x >= 0 then
return (sqrt x)
else
fail "Boo!"
test :: Double -> WhyNot Double
test x = do
y <- safeRoot x
z <- safeRoot (y - 4)
w <- safeRoot z
return w
main = do
print $ test 9
print $ test 400 | cbare/Etudes | haskell/whynot.hs | apache-2.0 | 732 | 0 | 10 | 273 | 337 | 168 | 169 | 29 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
------------------------------------------------------------------------------
module OpenArms.Types.Session
( -- * Types
Session (..)
, columnOffsetsSession
, tableOfSession
, session
, insertSession
, insertQuerySession
, selectSession
, updateSession
, fromSqlOfSession
, toSqlOfSession
, id'
, sessionDay'
, mealsServed'
) where
------------------------------------------------------------------------------
import OpenArms.Util
------------------------------------------------------------------------------
$(defineTable "session")
| dmjio/openarms | src/OpenArms/Types/Session.hs | bsd-2-clause | 761 | 0 | 7 | 170 | 74 | 49 | 25 | 20 | 0 |
import Test.Tasty (defaultMain, testGroup)
import qualified Ord
main :: IO ()
main = defaultMain $ testGroup "Tests"
[ Ord.tests
]
| kawu/dawg-ord | tests/test.hs | bsd-2-clause | 152 | 0 | 8 | 41 | 47 | 26 | 21 | 5 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Foundation
( BitloveEnv (..)
, UIApp (..)
, Route (..)
, UIAppMessage (..)
, resourcesUIApp
, Handler
, Widget
, Form
, getFullUrlRender
, isMiro
, withDB, withDBPool, DBPool, HasDB (..), Transaction
, Period (..)
--, maybeAuth
--, requireAuth
, module Settings
, module Model
) where
import Prelude
import System.IO (stderr, hPrint)
import Yesod
import Yesod.Static
import Control.Monad (forM_)
import Control.Monad.Trans.Resource
--import Yesod.Auth
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import Settings (widgetFile, Extra (..), BitloveEnv (..))
import Model
import Text.Jasmine (minifym)
import Text.Hamlet (hamletFile)
import Control.Applicative
import Data.Conduit.Pool
import qualified Database.HDBC as HDBC (withTransaction)
import qualified Database.HDBC.PostgreSQL as PostgreSQL (Connection)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Control.Exception as E
import qualified Network.Wai as Wai
import qualified Data.ByteString.Char8 as BC
import PathPieces
import BitloveAuth
type DBPool = Pool PostgreSQL.Connection
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data UIApp = UIApp
{ settings :: AppConfig BitloveEnv Extra
, getStatic :: Static -- ^ Settings for static file serving.
, uiDBPool :: DBPool -- ^ Database connection pool.
, httpManager :: Manager
}
data TrackerApp = TrackerApp
{ trackerDBPool :: DBPool
}
-- Set up i18n messages. See the message folder.
mkMessage "UIApp" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/handler
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "UIApp" $(parseRoutesFileNoCheck "config/routes")
type Form x = Html -> MForm UIApp UIApp (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod UIApp where
approot = ApprootRelative
{-
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = do
key <- getKey "config/client_session_key.aes"
return . Just $ clientSessionBackend key 120
-}
makeSessionBackend app =
do let withDB' :: Transaction a -> IO a
withDB' = runResourceT . withDBPool (uiDBPool app)
return $ Just $ sessionBackend withDB'
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
msu <- sessionUser
routeToMaster <- getRouteToMaster
mCurrentRoute <- maybe Nothing (Just . routeToMaster) `fmap`
getCurrentRoute
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
forM_ ["jquery-1.7.1.min.js", "jquery.flot.js", "graphs.js"] $
addScript . StaticR . flip StaticRoute [] . (:[])
addScriptRemote "https://api.flattr.com/js/0.6/load.js?mode=auto&popout=0&button=compact"
$(widgetFile "default-layout")
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
urlRenderOverride y s =
Just $ uncurry (joinPath y "") $ renderRoute s
errorHandler = errorHandler'
-- The page to be redirected to when authentication is required.
--authRoute _ = Just $ AuthR LoginR
messageLogger y loc level msg _ =
return ()
--formatLogText (getLogger y) loc level msg >>= logMsg (getLogger y)
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute [])
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- Grant any read request
isAuthorized _ False = return Authorized
-- Handlers.Auth: for everyone
isAuthorized SignupR _ = return Authorized
isAuthorized LoginR _ = return Authorized
isAuthorized (ActivateR _) _ = return Authorized
isAuthorized ReactivateR _ = return Authorized
-- Handlers.Edit: for respective owners
isAuthorized (UserDetailsR user) _ = authorizeFor user
isAuthorized (UserFeedDetailsR user _) _ = authorizeFor user
isAuthorized (UserFeedR user _) _ = authorizeFor user
isAuthorized (TorrentFileR user _ _) _ = authorizeFor user
-- Forbid by default
isAuthorized _ True = return $ Unauthorized "Cannot modify this resource"
authorizeFor :: UserName -> GHandler y' UIApp AuthResult
authorizeFor user = do
canEdit' <- canEdit user
return $ if canEdit'
then Authorized
else Unauthorized "Authorization denied"
-- We want full http://host URLs only in a few cases (feeds, API)
getFullUrlRender :: GHandler sub UIApp (Route UIApp -> Text)
getFullUrlRender =
do approot <- appRoot <$> settings <$> getYesod
((approot `T.append`) .) <$> getUrlRender
isMiro :: GHandler sub master Bool
isMiro =
maybe False (maybe False (const True) .
BC.findSubstring "Miro/") <$>
lookup "User-Agent" <$>
Wai.requestHeaders <$>
waiRequest
errorHandler' NotFound =
fmap chooseRep $ defaultLayout $ do
setTitle "Bitlove: Not found"
let img = StaticR $ StaticRoute ["404.jpg"] []
toWidget [hamlet|
<article>
<h2>Not Found
<img src="@{img}">
<p class="hint">Here's a kitten instead.
|]
errorHandler' (PermissionDenied _) =
fmap chooseRep $ defaultLayout $ do
setTitle "Bitlove: Permission denied"
toWidget [hamlet|
<h2>Permission denied
|]
errorHandler' e = do
liftIO $ hPrint stderr e
fmap chooseRep $ defaultLayout $
do setTitle "Bitlove: Error"
let img = StaticR $ StaticRoute ["500.jpg"] []
toWidget [hamlet|
<article>
<h2>Oops
<img src="@{img}">
|]
class HasDB y where
getDBPool :: GHandler y' y DBPool
instance HasDB UIApp where
getDBPool = uiDBPool <$> getYesod
type Transaction a = PostgreSQL.Connection -> IO a
-- How to run database actions.
withDB :: HasDB y => Transaction a -> GHandler y' y a
withDB f = do
pool <- getDBPool
lift $ withDBPool pool f
withDBPool :: DBPool -> Transaction a -> ResourceT IO a
withDBPool pool f = do
-- TODO: use takeResourceCheck
db <- takeResource pool
ea <- liftIO $
E.catch (Right <$> HDBC.withTransaction (mrValue db) f)
(return . Left)
case ea of
Left (e :: E.SomeException) ->
do mrRelease db
E.throw e
Right a ->
do mrReuse db True
mrRelease db
return a
| jannschu/bitlove-ui | Foundation.hs | bsd-2-clause | 8,447 | 0 | 17 | 2,054 | 1,553 | 834 | 719 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UnicodeSyntax #-}
{-| This module contains functions that let one easily implement the worker side
of an adapter under the assumption that the worker uses a two-way
communication channel with the supervisor for sending and receiving
messages. (Examples of when this is NOT the case is the threads adapter,
where you can communicate with the worker threads directly, and the MPI
adapter, which has communication primitives that don't quite align with
this setup.)
-}
module LogicGrowsOnTrees.Parallel.Common.Process
(
-- * Exceptions
ConnectionLost(..)
-- * Functions
, runWorker
, runWorkerUsingHandles
) where
import Control.Concurrent (killThread)
import Control.Concurrent.MVar (isEmptyMVar,newEmptyMVar,newMVar,putMVar,takeMVar,tryTakeMVar,withMVar)
import Control.Exception (AsyncException(ThreadKilled,UserInterrupt),Handler(..),catches,throwIO)
import Control.Monad.IO.Class
import Data.Functor ((<$>))
import Data.Serialize
import Data.Void (absurd)
import System.IO (Handle)
import qualified System.Log.Logger as Logger
import System.Log.Logger (Priority(DEBUG,INFO))
import System.Log.Logger.TH
import LogicGrowsOnTrees (TreeT)
import LogicGrowsOnTrees.Parallel.Common.Message (MessageForSupervisor(..),MessageForSupervisorFor,MessageForWorker(..))
import LogicGrowsOnTrees.Parallel.Common.Worker hiding (ProgressUpdate,StolenWorkload)
import LogicGrowsOnTrees.Parallel.ExplorationMode (ProgressFor,ResultFor,ExplorationMode(..),WorkerFinishedProgressFor)
import LogicGrowsOnTrees.Parallel.Purity
import LogicGrowsOnTrees.Utils.Handle
--------------------------------------------------------------------------------
----------------------------------- Loggers ------------------------------------
--------------------------------------------------------------------------------
deriveLoggers "Logger" [DEBUG,INFO]
--------------------------------------------------------------------------------
----------------------------------- Functions ----------------------------------
--------------------------------------------------------------------------------
{-| Runs a loop that continually fetches and reacts to messages from the
supervisor until the worker quits.
-}
runWorker ::
∀ exploration_mode m n.
ExplorationMode exploration_mode {-^ the mode in to explore the tree -} →
Purity m n {-^ the purity of the tree -} →
TreeT m (ResultFor exploration_mode) {-^ the tree -} →
IO MessageForWorker {-^ the action used to fetch the next message -} →
(MessageForSupervisorFor exploration_mode → IO ()) {-^ the action to send a message to the supervisor; note that this might occur in a different thread from the worker loop -} →
IO ()
runWorker exploration_mode purity tree receiveMessage sendMessage =
-- Note: This an MVar rather than an IORef because it is used by two
-- threads --- this one and the worker thread --- and I wanted to use
-- a mechanism that ensured that the new value would be observed by
-- the other thread immediately rather than when the cache lines
-- are flushed to the other processors.
newEmptyMVar >>= \worker_environment_mvar →
let processRequest ::
(WorkerRequestQueue (ProgressFor exploration_mode) → (α → IO ()) → IO ()) →
(α → MessageForSupervisorFor exploration_mode) →
IO ()
processRequest sendRequest constructResponse =
tryTakeMVar worker_environment_mvar
>>=
maybe (return ()) (\worker_environment@WorkerEnvironment{workerPendingRequests} → do
_ ← sendRequest workerPendingRequests (sendMessage . constructResponse)
putMVar worker_environment_mvar worker_environment
)
processNextMessage = receiveMessage >>= \message →
case message of
RequestProgressUpdate → do
processRequest sendProgressUpdateRequest ProgressUpdate
processNextMessage
RequestWorkloadSteal → do
processRequest sendWorkloadStealRequest StolenWorkload
processNextMessage
StartWorkload workload → do
infoM "Received workload."
debugM $ "Workload is: " ++ show workload
worker_is_running ← not <$> isEmptyMVar worker_environment_mvar
if worker_is_running
then sendMessage $ Failed "received a workload when the worker was already running"
else forkWorkerThread
exploration_mode
purity
(\termination_reason → do
_ ← takeMVar worker_environment_mvar
case termination_reason of
WorkerFinished final_progress →
sendMessage $ Finished final_progress
WorkerFailed exception →
sendMessage $ Failed (show exception)
WorkerAborted →
return ()
)
tree
workload
(case exploration_mode of
AllMode → absurd
FirstMode → absurd
FoundModeUsingPull _ → absurd
FoundModeUsingPush _ → sendMessage . ProgressUpdate
)
>>=
putMVar worker_environment_mvar
processNextMessage
QuitWorker → do
sendMessage WorkerQuit
liftIO $
tryTakeMVar worker_environment_mvar
>>=
maybe (return ()) (killThread . workerThreadId)
in processNextMessage
`catches`
[Handler $ \e → case e of
ThreadKilled → return ()
UserInterrupt → return ()
_ → throwIO e
,Handler $ \e → case e of
ConnectionLost → debugM "Connection to supervisor was lost before this process had finished."
]
{-# INLINE runWorker #-}
{-| The same as 'runWorker', but it lets you provide handles through which the
messages will be sent and received. (Note that the reading and writing
handles might be the same.)
-}
runWorkerUsingHandles ::
( Serialize (ProgressFor exploration_mode)
, Serialize (WorkerFinishedProgressFor exploration_mode)
) ⇒
ExplorationMode exploration_mode {-^ the mode in to explore the tree -} →
Purity m n {-^ the purity of the tree -} →
TreeT m (ResultFor exploration_mode) {-^ the tree -} →
Handle {-^ handle from which messages from the supervisor are read -} →
Handle {-^ handle to which messages to the supervisor are written -} →
IO ()
runWorkerUsingHandles exploration_mode purity tree receive_handle send_handle =
newMVar () >>= \send_lock →
runWorker
exploration_mode
purity
tree
(receive receive_handle)
(withMVar send_lock . const . send send_handle)
{-# INLINE runWorkerUsingHandles #-}
| gcross/LogicGrowsOnTrees | LogicGrowsOnTrees/sources/LogicGrowsOnTrees/Parallel/Common/Process.hs | bsd-2-clause | 7,826 | 0 | 31 | 2,377 | 1,062 | 576 | 486 | 119 | 12 |
{-# LANGUAGE TemplateHaskell, StandaloneDeriving #-}
{-| Implementation of the Ganeti config objects.
-}
{-
Copyright (C) 2011, 2012, 2013, 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.Objects
( HvParams
, OsParams
, OsParamsPrivate
, PartialNicParams(..)
, FilledNicParams(..)
, fillNicParams
, allNicParamFields
, PartialNic(..)
, FileDriver(..)
, DRBDSecret
, DataCollectorConfig(..)
, LogicalVolume(..)
, DiskLogicalId(..)
, Disk(..)
, includesLogicalId
, DiskTemplate(..)
, PartialBeParams(..)
, FilledBeParams(..)
, module Ganeti.Objects.Instance
, PartialNDParams(..)
, emptyPartialNDParams
, FilledNDParams(..)
, fillNDParams
, allNDParamFields
, Node(..)
, AllocPolicy(..)
, FilledISpecParams(..)
, PartialISpecParams(..)
, emptyPartialISpecParams
, fillISpecParams
, allISpecParamFields
, MinMaxISpecs(..)
, FilledIPolicy(..)
, PartialIPolicy(..)
, fillIPolicy
, GroupDiskParams
, NodeGroup(..)
, FilterAction(..)
, FilterPredicate(..)
, FilterRule(..)
, filterRuleOrder
, IpFamily(..)
, ipFamilyToRaw
, ipFamilyToVersion
, fillDict
, ClusterHvParams
, OsHvParams
, ClusterBeParams
, ClusterOsParams
, ClusterOsParamsPrivate
, ClusterNicParams
, UidPool
, formatUidRange
, UidRange
, Cluster(..)
, ConfigData(..)
, TimeStampObject(..) -- re-exported from Types
, UuidObject(..) -- re-exported from Types
, SerialNoObject(..) -- re-exported from Types
, TagsObject(..) -- re-exported from Types
, DictObject(..) -- re-exported from THH
, TagSet -- re-exported from THH
, Network(..)
, AddressPool(..)
, Ip4Address()
, mkIp4Address
, Ip4Network()
, mkIp4Network
, ip4netAddr
, ip4netMask
, readIp4Address
, ip4AddressToList
, ip4AddressToNumber
, ip4AddressFromNumber
, nextIp4Address
, IAllocatorParams
, MasterNetworkParameters(..)
) where
import Control.Applicative
import Control.Arrow (first)
import Control.Monad.State
import Data.Char
import Data.List (foldl', isPrefixOf, isInfixOf, intercalate)
import Data.Maybe
import qualified Data.Map as Map
import Data.Monoid
import Data.Ord (comparing)
import Data.Ratio (numerator, denominator)
import Data.Tuple (swap)
import Data.Word
import System.Time (ClockTime(..))
import Text.JSON (showJSON, readJSON, JSON, JSValue(..), fromJSString,
toJSString)
import qualified Text.JSON as J
import qualified AutoConf
import qualified Ganeti.Constants as C
import qualified Ganeti.ConstantUtils as ConstantUtils
import Ganeti.JSON
import Ganeti.Objects.BitArray (BitArray)
import Ganeti.Objects.Nic
import Ganeti.Objects.Instance
import Ganeti.Query.Language
import Ganeti.Types
import Ganeti.THH
import Ganeti.THH.Field
import Ganeti.Utils (sepSplit, tryRead)
import Ganeti.Utils.Validate
-- * Generic definitions
-- | Fills one map with keys from the other map, if not already
-- existing. Mirrors objects.py:FillDict.
fillDict :: (Ord k) => Map.Map k v -> Map.Map k v -> [k] -> Map.Map k v
fillDict defaults custom skip_keys =
let updated = Map.union custom defaults
in foldl' (flip Map.delete) updated skip_keys
-- * Network definitions
-- ** Ipv4 types
data Ip4Address = Ip4Address Word8 Word8 Word8 Word8
deriving (Eq, Ord)
mkIp4Address :: (Word8, Word8, Word8, Word8) -> Ip4Address
mkIp4Address (a, b, c, d) = Ip4Address a b c d
instance Show Ip4Address where
show (Ip4Address a b c d) = intercalate "." $ map show [a, b, c, d]
readIp4Address :: (Applicative m, Monad m) => String -> m Ip4Address
readIp4Address s =
case sepSplit '.' s of
[a, b, c, d] -> Ip4Address <$>
tryRead "first octect" a <*>
tryRead "second octet" b <*>
tryRead "third octet" c <*>
tryRead "fourth octet" d
_ -> fail $ "Can't parse IPv4 address from string " ++ s
instance JSON Ip4Address where
showJSON = showJSON . show
readJSON (JSString s) = readIp4Address (fromJSString s)
readJSON v = fail $ "Invalid JSON value " ++ show v ++ " for an IPv4 address"
-- Converts an address to a list of numbers
ip4AddressToList :: Ip4Address -> [Word8]
ip4AddressToList (Ip4Address a b c d) = [a, b, c, d]
-- | Converts an address into its ordinal number.
-- This is needed for indexing IP adresses in reservation pools.
ip4AddressToNumber :: Ip4Address -> Integer
ip4AddressToNumber = foldl (\n i -> 256 * n + toInteger i) 0 . ip4AddressToList
-- | Converts a number into an address.
-- This is needed for indexing IP adresses in reservation pools.
ip4AddressFromNumber :: Integer -> Ip4Address
ip4AddressFromNumber n =
let s = state $ first fromInteger . swap . (`divMod` 256)
(d, c, b, a) = evalState ((,,,) <$> s <*> s <*> s <*> s) n
in Ip4Address a b c d
nextIp4Address :: Ip4Address -> Ip4Address
nextIp4Address = ip4AddressFromNumber . (+ 1) . ip4AddressToNumber
-- | Custom type for an IPv4 network.
data Ip4Network = Ip4Network { ip4netAddr :: Ip4Address
, ip4netMask :: Word8
}
deriving (Eq)
mkIp4Network :: Ip4Address -> Word8 -> Ip4Network
mkIp4Network = Ip4Network
instance Show Ip4Network where
show (Ip4Network ip netmask) = show ip ++ "/" ++ show netmask
-- | JSON instance for 'Ip4Network'.
instance JSON Ip4Network where
showJSON = showJSON . show
readJSON (JSString s) =
case sepSplit '/' (fromJSString s) of
[ip, nm] -> do
ip' <- readIp4Address ip
nm' <- tryRead "parsing netmask" nm
if nm' >= 0 && nm' <= 32
then return $ Ip4Network ip' nm'
else fail $ "Invalid netmask " ++ show nm' ++ " from string " ++
fromJSString s
_ -> fail $ "Can't parse IPv4 network from string " ++ fromJSString s
readJSON v = fail $ "Invalid JSON value " ++ show v ++ " for an IPv4 network"
-- ** Address pools
-- | Currently address pools just wrap a reservation 'BitArray'.
--
-- In future, 'Network' might be extended to include several address pools
-- and address pools might include their own ranges of addresses.
newtype AddressPool = AddressPool { apReservations :: BitArray }
deriving (Eq, Ord, Show)
instance JSON AddressPool where
showJSON = showJSON . apReservations
readJSON = liftM AddressPool . readJSON
-- ** Ganeti \"network\" config object.
-- FIXME: Not all types might be correct here, since they
-- haven't been exhaustively deduced from the python code yet.
--
-- FIXME: When parsing, check that the ext_reservations and reservations
-- have the same length
$(buildObject "Network" "network" $
[ simpleField "name" [t| NonEmptyString |]
, optionalField $
simpleField "mac_prefix" [t| String |]
, simpleField "network" [t| Ip4Network |]
, optionalField $
simpleField "network6" [t| String |]
, optionalField $
simpleField "gateway" [t| Ip4Address |]
, optionalField $
simpleField "gateway6" [t| String |]
, optionalField $
simpleField "reservations" [t| AddressPool |]
, optionalField $
simpleField "ext_reservations" [t| AddressPool |]
]
++ uuidFields
++ timeStampFields
++ serialFields
++ tagsFields)
instance SerialNoObject Network where
serialOf = networkSerial
instance TagsObject Network where
tagsOf = networkTags
instance UuidObject Network where
uuidOf = networkUuid
instance TimeStampObject Network where
cTimeOf = networkCtime
mTimeOf = networkMtime
-- * Datacollector definitions
type MicroSeconds = Integer
-- | The configuration regarding a single data collector.
$(buildObject "DataCollectorConfig" "dataCollector" [
simpleField "active" [t| Bool|],
simpleField "interval" [t| MicroSeconds |]
])
-- | Central default values of the data collector config.
instance Monoid DataCollectorConfig where
mempty = DataCollectorConfig
{ dataCollectorActive = True
, dataCollectorInterval = 10^(6::Integer) * fromIntegral C.mondTimeInterval
}
mappend _ a = a
-- * Disk definitions
-- | Constant for the dev_type key entry in the disk config.
devType :: String
devType = "dev_type"
-- | The disk parameters type.
type DiskParams = Container JSValue
-- | An alias for DRBD secrets
type DRBDSecret = String
-- Represents a group name and a volume name.
--
-- From @man lvm@:
--
-- The following characters are valid for VG and LV names: a-z A-Z 0-9 + _ . -
--
-- VG and LV names cannot begin with a hyphen. There are also various reserved
-- names that are used internally by lvm that can not be used as LV or VG names.
-- A VG cannot be called anything that exists in /dev/ at the time of
-- creation, nor can it be called '.' or '..'. A LV cannot be called '.' '..'
-- 'snapshot' or 'pvmove'. The LV name may also not contain the strings '_mlog'
-- or '_mimage'
data LogicalVolume = LogicalVolume { lvGroup :: String
, lvVolume :: String
}
deriving (Eq, Ord)
instance Show LogicalVolume where
showsPrec _ (LogicalVolume g v) =
showString g . showString "/" . showString v
-- | Check the constraints for a VG/LV names (except the @/dev/@ check).
instance Validatable LogicalVolume where
validate (LogicalVolume g v) = do
let vgn = "Volume group name"
-- Group name checks
nonEmpty vgn g
validChars vgn g
notStartsDash vgn g
notIn vgn g [".", ".."]
-- Volume name checks
let lvn = "Volume name"
nonEmpty lvn v
validChars lvn v
notStartsDash lvn v
notIn lvn v [".", "..", "snapshot", "pvmove"]
reportIf ("_mlog" `isInfixOf` v) $ lvn ++ " must not contain '_mlog'."
reportIf ("_mimage" `isInfixOf` v) $ lvn ++ "must not contain '_mimage'."
where
nonEmpty prefix x = reportIf (null x) $ prefix ++ " must be non-empty"
notIn prefix x =
mapM_ (\y -> reportIf (x == y)
$ prefix ++ " must not be '" ++ y ++ "'")
notStartsDash prefix x = reportIf ("-" `isPrefixOf` x)
$ prefix ++ " must not start with '-'"
validChars prefix x =
reportIf (not . all validChar $ x)
$ prefix ++ " must consist only of [a-z][A-Z][0-9][+_.-]"
validChar c = isAsciiLower c || isAsciiUpper c || isDigit c
|| (c `elem` "+_.-")
instance J.JSON LogicalVolume where
showJSON = J.showJSON . show
readJSON (J.JSString s) | (g, _ : l) <- break (== '/') (J.fromJSString s) =
either fail return . evalValidate . validate' $ LogicalVolume g l
readJSON v = fail $ "Invalid JSON value " ++ show v
++ " for a logical volume"
-- | The disk configuration type. This includes the disk type itself,
-- for a more complete consistency. Note that since in the Python
-- code-base there's no authoritative place where we document the
-- logical id, this is probably a good reference point. There is a bijective
-- correspondence between the 'DiskLogicalId' constructors and 'DiskTemplate'.
data DiskLogicalId
= LIDPlain LogicalVolume -- ^ Volume group, logical volume
| LIDDrbd8 String String Int Int Int DRBDSecret
-- ^ NodeA, NodeB, Port, MinorA, MinorB, Secret
| LIDFile FileDriver String -- ^ Driver, path
| LIDSharedFile FileDriver String -- ^ Driver, path
| LIDGluster FileDriver String -- ^ Driver, path
| LIDBlockDev BlockDriver String -- ^ Driver, path (must be under /dev)
| LIDRados String String -- ^ Unused, path
| LIDExt String String -- ^ ExtProvider, unique name
deriving (Show, Eq)
-- | Mapping from a logical id to a disk type.
lidDiskType :: DiskLogicalId -> DiskTemplate
lidDiskType (LIDPlain {}) = DTPlain
lidDiskType (LIDDrbd8 {}) = DTDrbd8
lidDiskType (LIDFile {}) = DTFile
lidDiskType (LIDSharedFile {}) = DTSharedFile
lidDiskType (LIDGluster {}) = DTGluster
lidDiskType (LIDBlockDev {}) = DTBlock
lidDiskType (LIDRados {}) = DTRbd
lidDiskType (LIDExt {}) = DTExt
-- | Builds the extra disk_type field for a given logical id.
lidEncodeType :: DiskLogicalId -> [(String, JSValue)]
lidEncodeType v = [(devType, showJSON . lidDiskType $ v)]
-- | Custom encoder for DiskLogicalId (logical id only).
encodeDLId :: DiskLogicalId -> JSValue
encodeDLId (LIDPlain (LogicalVolume vg lv)) =
JSArray [showJSON vg, showJSON lv]
encodeDLId (LIDDrbd8 nodeA nodeB port minorA minorB key) =
JSArray [ showJSON nodeA, showJSON nodeB, showJSON port
, showJSON minorA, showJSON minorB, showJSON key ]
encodeDLId (LIDRados pool name) = JSArray [showJSON pool, showJSON name]
encodeDLId (LIDFile driver name) = JSArray [showJSON driver, showJSON name]
encodeDLId (LIDSharedFile driver name) =
JSArray [showJSON driver, showJSON name]
encodeDLId (LIDGluster driver name) = JSArray [showJSON driver, showJSON name]
encodeDLId (LIDBlockDev driver name) = JSArray [showJSON driver, showJSON name]
encodeDLId (LIDExt extprovider name) =
JSArray [showJSON extprovider, showJSON name]
-- | Custom encoder for DiskLogicalId, composing both the logical id
-- and the extra disk_type field.
encodeFullDLId :: DiskLogicalId -> (JSValue, [(String, JSValue)])
encodeFullDLId v = (encodeDLId v, lidEncodeType v)
-- | Custom decoder for DiskLogicalId. This is manual for now, since
-- we don't have yet automation for separate-key style fields.
decodeDLId :: [(String, JSValue)] -> JSValue -> J.Result DiskLogicalId
decodeDLId obj lid = do
dtype <- fromObj obj devType
case dtype of
DTDrbd8 ->
case lid of
JSArray [nA, nB, p, mA, mB, k] ->
LIDDrbd8
<$> readJSON nA
<*> readJSON nB
<*> readJSON p
<*> readJSON mA
<*> readJSON mB
<*> readJSON k
_ -> fail "Can't read logical_id for DRBD8 type"
DTPlain ->
case lid of
JSArray [vg, lv] -> LIDPlain <$>
(LogicalVolume <$> readJSON vg <*> readJSON lv)
_ -> fail "Can't read logical_id for plain type"
DTFile ->
case lid of
JSArray [driver, path] ->
LIDFile
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for file type"
DTSharedFile ->
case lid of
JSArray [driver, path] ->
LIDSharedFile
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for shared file type"
DTGluster ->
case lid of
JSArray [driver, path] ->
LIDGluster
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for shared file type"
DTBlock ->
case lid of
JSArray [driver, path] ->
LIDBlockDev
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for blockdev type"
DTRbd ->
case lid of
JSArray [driver, path] ->
LIDRados
<$> readJSON driver
<*> readJSON path
_ -> fail "Can't read logical_id for rdb type"
DTExt ->
case lid of
JSArray [extprovider, name] ->
LIDExt
<$> readJSON extprovider
<*> readJSON name
_ -> fail "Can't read logical_id for extstorage type"
DTDiskless ->
fail "Retrieved 'diskless' disk."
-- | Disk data structure.
--
-- This is declared manually as it's a recursive structure, and our TH
-- code currently can't build it.
data Disk = Disk
{ diskLogicalId :: DiskLogicalId
, diskChildren :: [Disk]
, diskNodes :: [String]
, diskIvName :: String
, diskSize :: Int
, diskMode :: DiskMode
, diskName :: Maybe String
, diskSpindles :: Maybe Int
, diskParams :: Maybe DiskParams
, diskUuid :: String
, diskSerial :: Int
, diskCtime :: ClockTime
, diskMtime :: ClockTime
} deriving (Show, Eq)
$(buildObjectSerialisation "Disk" $
[ customField 'decodeDLId 'encodeFullDLId ["dev_type"] $
simpleField "logical_id" [t| DiskLogicalId |]
, defaultField [| [] |] $ simpleField "children" [t| [Disk] |]
, defaultField [| [] |] $ simpleField "nodes" [t| [String] |]
, defaultField [| "" |] $ simpleField "iv_name" [t| String |]
, simpleField "size" [t| Int |]
, defaultField [| DiskRdWr |] $ simpleField "mode" [t| DiskMode |]
, optionalField $ simpleField "name" [t| String |]
, optionalField $ simpleField "spindles" [t| Int |]
, optionalField $ simpleField "params" [t| DiskParams |]
]
++ uuidFields
++ serialFields
++ timeStampFields)
instance UuidObject Disk where
uuidOf = diskUuid
-- | Determines whether a disk or one of his children has the given logical id
-- (determined by the volume group name and by the logical volume name).
-- This can be true only for DRBD or LVM disks.
includesLogicalId :: LogicalVolume -> Disk -> Bool
includesLogicalId lv disk =
case diskLogicalId disk of
LIDPlain lv' -> lv' == lv
LIDDrbd8 {} ->
any (includesLogicalId lv) $ diskChildren disk
_ -> False
-- * IPolicy definitions
$(buildParam "ISpec" "ispec"
[ simpleField ConstantUtils.ispecMemSize [t| Int |]
, simpleField ConstantUtils.ispecDiskSize [t| Int |]
, simpleField ConstantUtils.ispecDiskCount [t| Int |]
, simpleField ConstantUtils.ispecCpuCount [t| Int |]
, simpleField ConstantUtils.ispecNicCount [t| Int |]
, simpleField ConstantUtils.ispecSpindleUse [t| Int |]
])
$(buildObject "MinMaxISpecs" "mmis"
[ renameField "MinSpec" $ simpleField "min" [t| FilledISpecParams |]
, renameField "MaxSpec" $ simpleField "max" [t| FilledISpecParams |]
])
-- | Custom partial ipolicy. This is not built via buildParam since it
-- has a special 2-level inheritance mode.
$(buildObject "PartialIPolicy" "ipolicy"
[ optionalField . renameField "MinMaxISpecsP" $
simpleField ConstantUtils.ispecsMinmax [t| [MinMaxISpecs] |]
, optionalField . renameField "StdSpecP" $
simpleField "std" [t| PartialISpecParams |]
, optionalField . renameField "SpindleRatioP" $
simpleField "spindle-ratio" [t| Double |]
, optionalField . renameField "VcpuRatioP" $
simpleField "vcpu-ratio" [t| Double |]
, optionalField . renameField "DiskTemplatesP" $
simpleField "disk-templates" [t| [DiskTemplate] |]
])
-- | Custom filled ipolicy. This is not built via buildParam since it
-- has a special 2-level inheritance mode.
$(buildObject "FilledIPolicy" "ipolicy"
[ renameField "MinMaxISpecs" $
simpleField ConstantUtils.ispecsMinmax [t| [MinMaxISpecs] |]
, renameField "StdSpec" $ simpleField "std" [t| FilledISpecParams |]
, simpleField "spindle-ratio" [t| Double |]
, simpleField "vcpu-ratio" [t| Double |]
, simpleField "disk-templates" [t| [DiskTemplate] |]
])
-- | Custom filler for the ipolicy types.
fillIPolicy :: FilledIPolicy -> PartialIPolicy -> FilledIPolicy
fillIPolicy (FilledIPolicy { ipolicyMinMaxISpecs = fminmax
, ipolicyStdSpec = fstd
, ipolicySpindleRatio = fspindleRatio
, ipolicyVcpuRatio = fvcpuRatio
, ipolicyDiskTemplates = fdiskTemplates})
(PartialIPolicy { ipolicyMinMaxISpecsP = pminmax
, ipolicyStdSpecP = pstd
, ipolicySpindleRatioP = pspindleRatio
, ipolicyVcpuRatioP = pvcpuRatio
, ipolicyDiskTemplatesP = pdiskTemplates}) =
FilledIPolicy { ipolicyMinMaxISpecs = fromMaybe fminmax pminmax
, ipolicyStdSpec = case pstd of
Nothing -> fstd
Just p -> fillISpecParams fstd p
, ipolicySpindleRatio = fromMaybe fspindleRatio pspindleRatio
, ipolicyVcpuRatio = fromMaybe fvcpuRatio pvcpuRatio
, ipolicyDiskTemplates = fromMaybe fdiskTemplates
pdiskTemplates
}
-- * Node definitions
$(buildParam "ND" "ndp"
[ simpleField "oob_program" [t| String |]
, simpleField "spindle_count" [t| Int |]
, simpleField "exclusive_storage" [t| Bool |]
, simpleField "ovs" [t| Bool |]
, simpleField "ovs_name" [t| String |]
, simpleField "ovs_link" [t| String |]
, simpleField "ssh_port" [t| Int |]
, simpleField "cpu_speed" [t| Double |]
])
$(buildObject "Node" "node" $
[ simpleField "name" [t| String |]
, simpleField "primary_ip" [t| String |]
, simpleField "secondary_ip" [t| String |]
, simpleField "master_candidate" [t| Bool |]
, simpleField "offline" [t| Bool |]
, simpleField "drained" [t| Bool |]
, simpleField "group" [t| String |]
, simpleField "master_capable" [t| Bool |]
, simpleField "vm_capable" [t| Bool |]
, simpleField "ndparams" [t| PartialNDParams |]
, simpleField "powered" [t| Bool |]
]
++ timeStampFields
++ uuidFields
++ serialFields
++ tagsFields)
instance TimeStampObject Node where
cTimeOf = nodeCtime
mTimeOf = nodeMtime
instance UuidObject Node where
uuidOf = nodeUuid
instance SerialNoObject Node where
serialOf = nodeSerial
instance TagsObject Node where
tagsOf = nodeTags
-- * NodeGroup definitions
-- | The cluster/group disk parameters type.
type GroupDiskParams = Container DiskParams
-- | A mapping from network UUIDs to nic params of the networks.
type Networks = Container PartialNicParams
$(buildObject "NodeGroup" "group" $
[ simpleField "name" [t| String |]
, defaultField [| [] |] $ simpleField "members" [t| [String] |]
, simpleField "ndparams" [t| PartialNDParams |]
, simpleField "alloc_policy" [t| AllocPolicy |]
, simpleField "ipolicy" [t| PartialIPolicy |]
, simpleField "diskparams" [t| GroupDiskParams |]
, simpleField "networks" [t| Networks |]
]
++ timeStampFields
++ uuidFields
++ serialFields
++ tagsFields)
instance TimeStampObject NodeGroup where
cTimeOf = groupCtime
mTimeOf = groupMtime
instance UuidObject NodeGroup where
uuidOf = groupUuid
instance SerialNoObject NodeGroup where
serialOf = groupSerial
instance TagsObject NodeGroup where
tagsOf = groupTags
-- * Job scheduler filtering definitions
-- | Actions that can be performed when a filter matches.
data FilterAction
= Accept
| Pause
| Reject
| Continue
| RateLimit Int
deriving (Eq, Ord, Show)
instance JSON FilterAction where
showJSON fa = case fa of
Accept -> JSString (toJSString "ACCEPT")
Pause -> JSString (toJSString "PAUSE")
Reject -> JSString (toJSString "REJECT")
Continue -> JSString (toJSString "CONTINUE")
RateLimit n -> JSArray [ JSString (toJSString "RATE_LIMIT")
, JSRational False (fromIntegral n)
]
readJSON v = case v of
-- `FilterAction`s are case-sensitive.
JSString s | fromJSString s == "ACCEPT" -> return Accept
JSString s | fromJSString s == "PAUSE" -> return Pause
JSString s | fromJSString s == "REJECT" -> return Reject
JSString s | fromJSString s == "CONTINUE" -> return Continue
JSArray (JSString s : rest) | fromJSString s == "RATE_LIMIT" ->
case rest of
[JSRational False n] | denominator n == 1 && numerator n > 0 ->
return . RateLimit . fromIntegral $ numerator n
_ -> fail "RATE_LIMIT argument must be a positive integer"
x -> fail $ "malformed FilterAction JSON: " ++ J.showJSValue x ""
data FilterPredicate
= FPJobId (Filter FilterField)
| FPOpCode (Filter FilterField)
| FPReason (Filter FilterField)
deriving (Eq, Ord, Show)
instance JSON FilterPredicate where
showJSON fp = case fp of
FPJobId expr -> JSArray [string "jobid", showJSON expr]
FPOpCode expr -> JSArray [string "opcode", showJSON expr]
FPReason expr -> JSArray [string "reason", showJSON expr]
where
string = JSString . toJSString
readJSON v = case v of
-- Predicate names are case-sensitive.
JSArray [JSString name, expr]
| name == toJSString "jobid" -> FPJobId <$> readJSON expr
| name == toJSString "opcode" -> FPOpCode <$> readJSON expr
| name == toJSString "reason" -> FPReason <$> readJSON expr
JSArray (JSString name:params) ->
fail $ "malformed FilterPredicate: bad parameter list for\
\ '" ++ fromJSString name ++ "' predicate: "
++ J.showJSArray params ""
_ -> fail "malformed FilterPredicate: must be a list with the first\
\ entry being a string describing the predicate type"
$(buildObject "FilterRule" "fr" $
[ simpleField "watermark" [t| JobId |]
, simpleField "priority" [t| NonNegative Int |]
, simpleField "predicates" [t| [FilterPredicate] |]
, simpleField "action" [t| FilterAction |]
, simpleField "reason_trail" [t| ReasonTrail |]
]
++ uuidFields)
instance UuidObject FilterRule where
uuidOf = frUuid
-- | Order in which filter rules are evaluated, according to
-- `doc/design-optables.rst`.
-- For `FilterRule` fields not specified as important for the order,
-- we choose an arbitrary ordering effect (after the ones from the spec).
--
-- The `Ord` instance for `FilterRule` agrees with this function.
-- Yet it is recommended to use this function instead of `compare` to be
-- explicit that the spec order is used.
filterRuleOrder :: FilterRule -> FilterRule -> Ordering
filterRuleOrder = compare
instance Ord FilterRule where
-- It is important that the Ord instance respects the ordering given in
-- `doc/design-optables.rst` for the fields defined in there. The other
-- fields may be ordered arbitrarily.
-- Use `filterRuleOrder` when relying on the spec order.
compare =
comparing $ \(FilterRule watermark prio predicates action reason uuid) ->
( prio, watermark, uuid -- spec part
, predicates, action, reason -- arbitrary part
)
-- | IP family type
$(declareIADT "IpFamily"
[ ("IpFamilyV4", 'AutoConf.pyAfInet4)
, ("IpFamilyV6", 'AutoConf.pyAfInet6)
])
$(makeJSONInstance ''IpFamily)
-- | Conversion from IP family to IP version. This is needed because
-- Python uses both, depending on context.
ipFamilyToVersion :: IpFamily -> Int
ipFamilyToVersion IpFamilyV4 = C.ip4Version
ipFamilyToVersion IpFamilyV6 = C.ip6Version
-- | Cluster HvParams (hvtype to hvparams mapping).
type ClusterHvParams = Container HvParams
-- | Cluster Os-HvParams (os to hvparams mapping).
type OsHvParams = Container ClusterHvParams
-- | Cluser BeParams.
type ClusterBeParams = Container FilledBeParams
-- | Cluster OsParams.
type ClusterOsParams = Container OsParams
type ClusterOsParamsPrivate = Container (Private OsParams)
-- | Cluster NicParams.
type ClusterNicParams = Container FilledNicParams
-- | A low-high UID ranges.
type UidRange = (Int, Int)
formatUidRange :: UidRange -> String
formatUidRange (lower, higher)
| lower == higher = show lower
| otherwise = show lower ++ "-" ++ show higher
-- | Cluster UID Pool, list (low, high) UID ranges.
type UidPool = [UidRange]
-- | The iallocator parameters type.
type IAllocatorParams = Container JSValue
-- | The master candidate client certificate digests
type CandidateCertificates = Container String
-- | Disk state parameters.
--
-- As according to the documentation this option is unused by Ganeti,
-- the content is just a 'JSValue'.
type DiskState = Container JSValue
-- | Hypervisor state parameters.
--
-- As according to the documentation this option is unused by Ganeti,
-- the content is just a 'JSValue'.
type HypervisorState = Container JSValue
-- * Cluster definitions
$(buildObject "Cluster" "cluster" $
[ simpleField "rsahostkeypub" [t| String |]
, optionalField $
simpleField "dsahostkeypub" [t| String |]
, simpleField "highest_used_port" [t| Int |]
, simpleField "tcpudp_port_pool" [t| [Int] |]
, simpleField "mac_prefix" [t| String |]
, optionalField $
simpleField "volume_group_name" [t| String |]
, simpleField "reserved_lvs" [t| [String] |]
, optionalField $
simpleField "drbd_usermode_helper" [t| String |]
, simpleField "master_node" [t| String |]
, simpleField "master_ip" [t| String |]
, simpleField "master_netdev" [t| String |]
, simpleField "master_netmask" [t| Int |]
, simpleField "use_external_mip_script" [t| Bool |]
, simpleField "cluster_name" [t| String |]
, simpleField "file_storage_dir" [t| String |]
, simpleField "shared_file_storage_dir" [t| String |]
, simpleField "gluster_storage_dir" [t| String |]
, simpleField "enabled_hypervisors" [t| [Hypervisor] |]
, simpleField "hvparams" [t| ClusterHvParams |]
, simpleField "os_hvp" [t| OsHvParams |]
, simpleField "beparams" [t| ClusterBeParams |]
, simpleField "osparams" [t| ClusterOsParams |]
, simpleField "osparams_private_cluster" [t| ClusterOsParamsPrivate |]
, simpleField "nicparams" [t| ClusterNicParams |]
, simpleField "ndparams" [t| FilledNDParams |]
, simpleField "diskparams" [t| GroupDiskParams |]
, simpleField "candidate_pool_size" [t| Int |]
, simpleField "modify_etc_hosts" [t| Bool |]
, simpleField "modify_ssh_setup" [t| Bool |]
, simpleField "maintain_node_health" [t| Bool |]
, simpleField "uid_pool" [t| UidPool |]
, simpleField "default_iallocator" [t| String |]
, simpleField "default_iallocator_params" [t| IAllocatorParams |]
, simpleField "hidden_os" [t| [String] |]
, simpleField "blacklisted_os" [t| [String] |]
, simpleField "primary_ip_family" [t| IpFamily |]
, simpleField "prealloc_wipe_disks" [t| Bool |]
, simpleField "ipolicy" [t| FilledIPolicy |]
, simpleField "hv_state_static" [t| HypervisorState |]
, simpleField "disk_state_static" [t| DiskState |]
, simpleField "enabled_disk_templates" [t| [DiskTemplate] |]
, simpleField "candidate_certs" [t| CandidateCertificates |]
, simpleField "max_running_jobs" [t| Int |]
, simpleField "max_tracked_jobs" [t| Int |]
, simpleField "install_image" [t| String |]
, simpleField "instance_communication_network" [t| String |]
, simpleField "zeroing_image" [t| String |]
, simpleField "compression_tools" [t| [String] |]
, simpleField "enabled_user_shutdown" [t| Bool |]
, simpleField "data_collectors" [t| Container DataCollectorConfig |]
]
++ timeStampFields
++ uuidFields
++ serialFields
++ tagsFields)
instance TimeStampObject Cluster where
cTimeOf = clusterCtime
mTimeOf = clusterMtime
instance UuidObject Cluster where
uuidOf = clusterUuid
instance SerialNoObject Cluster where
serialOf = clusterSerial
instance TagsObject Cluster where
tagsOf = clusterTags
-- * ConfigData definitions
$(buildObject "ConfigData" "config" $
-- timeStampFields ++
[ simpleField "version" [t| Int |]
, simpleField "cluster" [t| Cluster |]
, simpleField "nodes" [t| Container Node |]
, simpleField "nodegroups" [t| Container NodeGroup |]
, simpleField "instances" [t| Container Instance |]
, simpleField "networks" [t| Container Network |]
, simpleField "disks" [t| Container Disk |]
, simpleField "filters" [t| Container FilterRule |]
]
++ timeStampFields
++ serialFields)
instance SerialNoObject ConfigData where
serialOf = configSerial
instance TimeStampObject ConfigData where
cTimeOf = configCtime
mTimeOf = configMtime
-- * Master network parameters
$(buildObject "MasterNetworkParameters" "masterNetworkParameters"
[ simpleField "uuid" [t| String |]
, simpleField "ip" [t| String |]
, simpleField "netmask" [t| Int |]
, simpleField "netdev" [t| String |]
, simpleField "ip_family" [t| IpFamily |]
])
| ganeti-github-testing/ganeti-test-1 | src/Ganeti/Objects.hs | bsd-2-clause | 34,660 | 0 | 19 | 9,151 | 7,173 | 4,069 | 3,104 | 668 | 17 |
module DetectPangram where
import Data.Char (toLower)
-- | Check if string is a pangram, i.e. contains every letter (6 kyu)
-- | Link: https://biturl.io/Pangram
-- | Refactored solution I came up with after completition of this kata
-- originally the solution was almost the same
isPangram :: String -> Bool
isPangram s = all (`elem` map toLower s) ['a' .. 'z']
| Eugleo/Code-Wars | src/string-kata/DetectPangram.hs | bsd-3-clause | 365 | 0 | 7 | 64 | 57 | 35 | 22 | 4 | 1 |
module Doukaku.Honeycomb (solve) where
type Point = (Double, Double)
type Direction = (Double, Double)
solve :: String -> String
solve = map snd . scanl (\ (p, _) d -> moveOn p d) ((0, 0), 'A') . map direct
direct :: Char -> Direction
direct '0' = (0, 1)
direct '1' = (cos (pi / 6), sin (pi / 6))
direct '2' = (cos (pi / 6), - sin (pi / 6))
direct '3' = (0, - 1)
direct '4' = (- cos (pi / 6), - sin (pi / 6))
direct '5' = (- cos (pi / 6), sin (pi / 6))
(.>.) :: Direction -> Direction -> Direction
(x, y) .>. (x', y') = (x + x', y + y')
move :: Point -> Direction -> Point
move (x, y) (dx, dy) = (x + dx, y + dy)
moveOn :: Point -> Direction -> (Point, Char)
moveOn p d = let p' = move p d
in case whereIs p' of
Just c -> (p', c)
Nothing -> (p, '!')
points :: [(Point, Char)]
points = zip points' alpha
where
alpha = ['A' .. 'Z'] ++ ['a' .. 'k']
circle n = reset $ concatMap (replicate n . direct) "234501"
where
reset [] = direct '0' : []
reset ds = init ds ++ (last ds .>. direct '0') : []
directions = concatMap circle [0..]
points' = scanl move (0, 0) directions
whereIs :: Point -> Maybe Char
whereIs pt = fmap snd . head' . filter (inIt pt . fst) $ points
where
head' [] = Nothing
head' xs = Just . head $ xs
inIt :: Point -> Point -> Bool
inIt (x, y) (cx, cy) = (x - cx) ^ (2 :: Int) + (y - cy) ^ (2 :: Int) < 0.5 ^ (2 :: Int)
| hiratara/doukaku-past-questions-advent-2013 | src/Doukaku/Honeycomb.hs | bsd-3-clause | 1,436 | 4 | 13 | 406 | 787 | 427 | 360 | 35 | 2 |
-- Copyright (c) 2006-2011
-- The President and Fellows of Harvard College.
--
-- 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.
-- 3. Neither the name of the University nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
-- THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY 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 UNIVERSITY 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 : Language.C.Quote.OpenCL
-- Copyright : (c) Harvard University 2006-2011
-- License : BSD-style
-- Maintainer : mainland@eecs.harvard.edu
--
--------------------------------------------------------------------------------
module Language.C.Quote.OpenCL (
ToExp(..),
cexp,
cedecl,
cdecl,
csdecl,
cenum,
cty,
cparam,
cinit,
cstm,
cunit,
cfun
) where
import qualified Language.C.Parser as P
import qualified Language.C.Syntax as C
import Language.C.Quote.Base (ToExp(..), quasiquote)
exts :: [C.Extensions]
exts = [C.OpenCL]
typenames :: [String]
typenames =
concatMap typeN
["char", "uchar", "short", "ushort", "int", "uint",
"long" , "ulong", "float", "double", "bool", "half", "quad"] ++
["uchar", "ushort", "uint", "ulong",
"half", "quad", "image2d_t", "image3d_t", "sampler_t", "event_t"]
typeN typename = [typename ++ show n | n <- [2, 3, 4, 8, 16]]
cdecl = quasiquote exts typenames P.parseDecl
cedecl = quasiquote exts typenames P.parseEdecl
cenum = quasiquote exts typenames P.parseEnum
cexp = quasiquote exts typenames P.parseExp
cfun = quasiquote exts typenames P.parseFunc
cinit = quasiquote exts typenames P.parseInit
cparam = quasiquote exts typenames P.parseParam
csdecl = quasiquote exts typenames P.parseStructDecl
cstm = quasiquote exts typenames P.parseStm
cty = quasiquote exts typenames P.parseType
cunit = quasiquote exts typenames P.parseUnit
| HIPERFIT/language-c-quote | Language/C/Quote/OpenCL.hs | bsd-3-clause | 3,145 | 0 | 8 | 555 | 426 | 264 | 162 | 37 | 1 |
module Day20 where
import Data.List
import Data.List.Split
import Data.Ord
parse :: [String] -> [(Int, Int)]
parse = map (head . (\a -> zip a (drop 1 a)) . map read . splitOn "-")
reduce :: [(Int, Int)] -> [(Int, Int)]
reduce (a:[]) = [a]
reduce ((a, b):(a',b'):as) =
case (a' < b) of
True -> reduce ((a, max b b'):as)
False -> (a, b):(reduce ((a', b'):as))
count :: [(Int, Int)] -> Int
count ((a, b):[]) = 4294967295 - b
count ((a, b):(a', b'):as)= (a' - b) + count ((a', b'):as)
run = input >>= print . count . reduce . sortBy (comparing fst) . parse
input = do
content <- readFile "input20.txt"
return $ lines content
| ulyssesp/AoC | src/day20.hs | bsd-3-clause | 669 | 0 | 14 | 164 | 404 | 224 | 180 | 19 | 2 |
-- Copyright 2019 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- https://developers.google.com/open-source/licenses/bsd
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
module Util (IsBool (..), group, ungroup, pad, padLeft, delIdx, replaceIdx,
insertIdx, mvIdx, mapFst, mapSnd, splitOn, scan,
scanM, composeN, mapMaybe, uncons, repeated,
transitiveClosure, transitiveClosureM,
showErr, listDiff, splitMap, enumerate, restructure,
onSnd, onFst, findReplace, swapAt, uncurry3,
measureSeconds,
bindM2, foldMapM, lookupWithIdx, (...), zipWithT, for,
Zippable (..), zipWithZ_, zipErr, forMZipped, forMZipped_,
iota, whenM, unsnoc, anyM,
File (..), FileHash, FileContents, addHash, readFileWithHash) where
import Crypto.Hash
import Data.Functor.Identity (Identity(..))
import Data.List (sort)
import qualified Data.List.NonEmpty as NE
import qualified Data.ByteString as BS
import Data.Foldable
import Data.List.NonEmpty (NonEmpty (..))
import Prelude
import qualified Data.Set as Set
import qualified Data.Map.Strict as M
import Control.Monad.State.Strict
import System.CPUTime
import Cat
class IsBool a where
toBool :: a -> Bool
iota :: Int -> [Int]
iota n = [0..n-1]
swapAt :: Int -> a -> [a] -> [a]
swapAt _ _ [] = error "swapping to empty list"
swapAt 0 y (_:xs) = y:xs
swapAt n y (x:xs) = x:(swapAt (n-1) y xs)
onFst :: (a -> b) -> (a, c) -> (b, c)
onFst f (x, y) = (f x, y)
onSnd :: (a -> b) -> (c, a) -> (c, b)
onSnd f (x, y) = (x, f y)
unsnoc :: NonEmpty a -> ([a], a)
unsnoc (x:|xs) = case reverse (x:xs) of
(y:ys) -> (reverse ys, y)
_ -> error "impossible"
enumerate :: Traversable f => f a -> f (Int, a)
enumerate xs = evalState (traverse addCount xs) 0
where addCount :: a -> State Int (Int, a)
addCount x = do n <- get
put (n + 1)
return (n, x)
splitMap :: Ord k => [k] -> M.Map k v -> (M.Map k v, M.Map k v)
splitMap ks m = let ks' = Set.fromList ks
pos = M.filterWithKey (\k _ -> k `Set.member` ks') m
in (pos, m M.\\ pos)
listDiff :: Ord a => [a] -> [a] -> [a]
listDiff xs ys = Set.toList $ Set.difference (Set.fromList xs) (Set.fromList ys)
showErr :: Show e => Either e a -> Either String a
showErr (Left e) = Left (show e)
showErr (Right x) = Right x
group :: (Ord a) => [(a,b)] -> [(a, [b])]
group [] = []
group ((k,v):xs) =
let (prefix, suffix) = span ((== k) . fst) xs
g = v:(map snd prefix)
in (k, g) : group suffix
ungroup :: [(a, [b])] -> [(a,b)]
ungroup [] = []
ungroup ((k,vs):xs) = (zip (repeat k) vs) ++ ungroup xs
uncons :: [a] -> (a, [a])
uncons (x:xs) = (x, xs)
uncons [] = error "whoops! [uncons]"
pad :: a -> Int -> [a] -> [a]
pad v n xs = xs ++ replicate (n - length(xs)) v
padLeft :: a -> Int -> [a] -> [a]
padLeft v n xs = replicate (n - length(xs)) v ++ xs
delIdx :: Int -> [a] -> [a]
delIdx i xs = case splitAt i xs of
(prefix, _:suffix) -> prefix ++ suffix
(prefix, []) -> prefix -- Already not there
replaceIdx :: Int -> a -> [a] -> [a]
replaceIdx i x xs = case splitAt i xs of
(prefix, _:suffix) -> prefix ++ (x:suffix)
(prefix, []) -> prefix ++ [x]
insertIdx :: Int -> a -> [a] -> [a]
insertIdx i x xs = case splitAt i xs of
(prefix, suffix) -> prefix ++ (x:suffix)
mvIdx :: Int -> Int -> [a] -> [a]
mvIdx i j xs | j == i = xs
| j < i = let x = xs!!i
in insertIdx j x . delIdx i $ xs
| otherwise = let x = xs!!i
in delIdx i . insertIdx j x $ xs
mapFst :: (a -> b) -> [(a, c)] -> [(b, c)]
mapFst f zs = [(f x, y) | (x, y) <- zs]
mapSnd :: (a -> b) -> [(c, a)] -> [(c, b)]
mapSnd f zs = [(x, f y) | (x, y) <- zs]
mapMaybe :: (a -> Maybe b) -> [a] -> [b]
mapMaybe _ [] = []
mapMaybe f (x:xs) = let rest = mapMaybe f xs
in case f x of
Just y -> y : rest
Nothing -> rest
composeN :: Int -> (a -> a) -> a -> a
composeN n f = foldr (.) id (replicate n f)
repeated :: Ord a => [a] -> [a]
repeated = repeatedSorted . sort
repeatedSorted :: Eq a => [a] -> [a]
repeatedSorted [] = []
repeatedSorted [_] = []
repeatedSorted (x:y:rest) | x == y = [x] ++ repeatedSorted (dropWhile (== x) rest)
| otherwise = repeatedSorted (y:rest)
splitOn :: (a -> Bool) -> [a] -> [[a]]
splitOn f s = let (prefix, suffix) = break f s
in case suffix of
[] -> [prefix]
_:xs -> prefix : splitOn f xs
restructure :: Traversable f => [a] -> f b -> f a
restructure xs structure = evalState (traverse procLeaf structure) xs
where procLeaf :: b -> State [a] a
procLeaf _ = do ~(x:rest) <- get
put rest
return x
-- TODO: find a more efficient implementation
findReplace :: Eq a => [a] -> [a] -> [a] -> [a]
findReplace _ _ [] = []
findReplace old new s@(x:xs) =
if take n s == old
then new ++ recur (drop n s)
else x : recur xs
where n = length old
recur = findReplace old new
scan :: Traversable t => (a -> s -> (b, s)) -> t a -> s -> (t b, s)
scan f xs s = runState (traverse (asState . f) xs) s
scanM :: (Monad m, Traversable t) => (a -> s -> m (b, s)) -> t a -> s -> m (t b, s)
scanM f xs s = runStateT (traverse (asStateT . f) xs) s
asStateT :: Monad m => (s -> m (a, s)) -> StateT s m a
asStateT f = do
s <- get
(ans, s') <- lift $ f s
put s'
return ans
asState :: (s -> (a, s)) -> State s a
asState f = asStateT (Identity . f)
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 f (x, y, z) = f x y z
bindM2 :: Monad m => (a -> b -> m c) -> m a -> m b -> m c
bindM2 f ma mb = do
a <- ma
b <- mb
f a b
(...) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
f ... g = \x y -> f $ g x y
foldMapM :: (Monad m, Monoid w, Foldable t) => (a -> m w) -> t a -> m w
foldMapM f xs = foldM (\acc x -> (acc<>) <$> f x ) mempty xs
lookupWithIdx :: Eq a => a -> [(a, b)] -> Maybe (Int, b)
lookupWithIdx k vals = lookup k $ [(x, (i, y)) | (i, (x, y)) <- zip [0..] vals]
-- NOTE: (toList args) has to be at least as long as (toList trav)
zipWithT :: (Traversable t, Monad h, Foldable f) => (a -> b -> h c) -> t a -> f b -> h (t c)
zipWithT f trav args = flip evalStateT (toList args) $ flip traverse trav $ \e -> getNext >>= lift . f e
where getNext = get >>= \(h:t) -> put t >> return h
for :: Functor f => f a -> (a -> b) -> f b
for = flip fmap
transitiveClosure :: forall a. Ord a => (a -> [a]) -> [a] -> [a]
transitiveClosure getParents seeds =
toList $ snd $ runCat (mapM_ go seeds) mempty
where
go :: a -> Cat (Set.Set a) ()
go x = do
visited <- look
unless (x `Set.member` visited) $ do
extend $ Set.singleton x
mapM_ go $ getParents x
transitiveClosureM :: forall m a. (Monad m, Ord a) => (a -> m [a]) -> [a] -> m [a]
transitiveClosureM getParents seeds =
toList <$> execStateT (mapM_ go seeds) mempty
where
go :: a -> StateT (Set.Set a) m ()
go x = do
visited <- get
unless (x `Set.member` visited) $ do
modify (<> Set.singleton x)
lift (getParents x) >>= mapM_ go
measureSeconds :: MonadIO m => m a -> m (a, Double)
measureSeconds m = do
t1 <- liftIO $ getCPUTime
ans <- m
t2 <- liftIO $ getCPUTime
return (ans, (fromIntegral $ t2 - t1) / 1e12)
whenM :: Monad m => m Bool -> m () -> m ()
whenM test doit = test >>= \case
True -> doit
False -> return ()
anyM :: Monad m => (a -> m Bool) -> [a] -> m Bool
anyM f xs = do
conds <- mapM f xs
return $ any id conds
-- === zippable class ===
class Zippable f where
zipWithZ :: MonadFail m => (a -> b -> m c) -> f a -> f b -> m (f c)
instance Zippable [] where
zipWithZ _ [] [] = return []
zipWithZ f (x:xs) (y:ys) = (:) <$> f x y <*> zipWithZ f xs ys
zipWithZ _ _ _ = zipErr
instance Zippable NE.NonEmpty where
zipWithZ f xs ys = NE.fromList <$> zipWithZ f (NE.toList xs) (NE.toList ys)
zipWithZ_ :: Zippable f => MonadFail m => (a -> b -> m c) -> f a -> f b -> m ()
zipWithZ_ f xs ys = zipWithZ f xs ys >> return ()
zipErr :: MonadFail m => m a
zipErr = fail "zip error"
forMZipped :: Zippable f => MonadFail m => f a -> f b -> (a -> b -> m c) -> m (f c)
forMZipped xs ys f = zipWithZ f xs ys
forMZipped_ :: Zippable f => MonadFail m => f a -> f b -> (a -> b -> m c) -> m ()
forMZipped_ xs ys f = void $ forMZipped xs ys f
-- === bytestrings paired with their hash digest ===
-- TODO: use something other than a string to store the digest
type FileHash = String
type FileContents = BS.ByteString
-- TODO: consider adding mtime as well for a fast path that doesn't
-- require reading the file
data File = File
{ fContents :: FileContents
, fHash :: FileHash }
deriving (Show, Eq, Ord)
addHash :: FileContents -> File
addHash s = File s $ show (hash s :: Digest SHA256)
readFileWithHash :: MonadIO m => FilePath -> m File
readFileWithHash path = liftIO $ addHash <$> BS.readFile path
| google-research/dex-lang | src/lib/Util.hs | bsd-3-clause | 9,252 | 0 | 15 | 2,551 | 4,605 | 2,418 | 2,187 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Test.ArbitraryInstances where
import qualified Data.ByteString as B
import Data.Word (Word8, Word32)
import System.Random
import Test.QuickCheck
instance Arbitrary B.ByteString where
arbitrary = fmap B.pack arbitrary
shrink s = case B.splitAt (B.length s `div` 2) s of
(a, b) -> [a,b]
instance Arbitrary Word8 where
arbitrary = choose (minBound, maxBound)
instance Random Word8 where
randomR (low, high) g =
case randomR (fromIntegral low :: Integer, fromIntegral high) g of
(val, gen) -> (fromIntegral val, gen)
random = randomR (minBound, maxBound)
instance Arbitrary Word32 where
arbitrary = choose (minBound, maxBound)
instance Random Word32 where
randomR (low, high) g =
case randomR (fromIntegral low :: Integer, fromIntegral high) g of
(val, gen) -> (fromIntegral val, gen)
random = randomR (minBound, maxBound)
| enolan/whiteout | src/Test/ArbitraryInstances.hs | bsd-3-clause | 950 | 0 | 11 | 208 | 321 | 178 | 143 | 24 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ConstraintKinds #-}
module Bound.Unwrap ( Fresh (fresh, uname)
, name
, freshify
, erase
, nameF
, Counter
, UnwrapT
, Unwrap
, runUnwrapT
, runUnwrap
, unwrap
, unwrapAll) where
import Bound
import Control.Monad.Identity
import Control.Monad.Gen
data Fresh a = Fresh { fresh :: !Int
, uname :: a }
deriving (Eq, Ord)
instance Show a => Show (Fresh a) where
show (Fresh i a) = show i ++ '.' : show a
-- | Create a name. This name isn't unique at all at this point. Once
-- you have a name you can pass it to freshify to render it unique
-- within the current monadic context.
name :: a -> Fresh a
name = Fresh 0
-- | @erase@ drops the information in a 'Fresh' that makes it globally
-- unique and gives you back the user supplied name. For obvious
-- reasons, @erase@ isn't injective. It is the case that
--
-- @
-- erase . name = id
-- name . erase /= id
-- @
erase :: Fresh a -> a
erase = uname
-- Keeping this opaque, but I don't want *another*
-- monad for counting dammit. I built one and that was enough.
newtype Counter = Counter {getCounter :: Int}
-- | A specialized version of 'GenT' used for unwrapping things.
type UnwrapT = GenT Counter
type Unwrap = Gen Counter
-- | A specialized constraint for monads who know how to unwrap
-- things.
type MonadUnwrap m = MonadGen Counter m
runUnwrapT :: Monad m => UnwrapT m a -> m a
runUnwrapT = runGenTWith (successor $ Counter . succ . getCounter)
(Counter 0)
runUnwrap :: Unwrap a -> a
runUnwrap = runIdentity . runUnwrapT
-- | Render a name unique within the scope of a monadic computation.
freshify :: MonadUnwrap m => Fresh a -> m (Fresh a)
freshify nm = (\i -> nm{fresh = i}) <$> fmap getCounter gen
-- | Create a name which is unique within the scope of a monadic
-- computation.
nameF :: MonadUnwrap m => a -> m (Fresh a)
nameF = freshify . name
-- | Given a scope which binds one variable, unwrap it with a
-- variable. Note that @unwrap@ will take care of @freshify@ing the
-- varable.
unwrap :: (Monad f, Functor m, MonadUnwrap m)
=> Fresh a
-> Scope () f (Fresh a)
-> m (Fresh a, f (Fresh a))
unwrap nm s = fmap head <$> unwrapAll nm [s]
-- | Given a list of scopes which bind one variable, unwrap them all
-- with the same variable. Note that @unwrapAll@ will take care of
-- @freshify@ing the variable.
unwrapAll :: (Monad f, MonadUnwrap m)
=> Fresh a
-> [Scope () f (Fresh a)]
-> m (Fresh a, [f (Fresh a)])
unwrapAll nm ss = do
fnm <- freshify nm
return $ (fnm, map (instantiate1 $ return fnm) ss)
| julmue/UntypedLambda | src/Bound/Unwrap.hs | bsd-3-clause | 2,887 | 0 | 13 | 862 | 647 | 354 | 293 | 56 | 1 |
{-# LANGUAGE GADTs, NoMonomorphismRestriction, ScopedTypeVariables,
KindSignatures, RecordWildCards, FlexibleContexts #-}
----------------------------
-- | This module provides main object of cmd executor
----------------------------
module CmdExec where
import Control.Applicative hiding (empty)
import Control.Category
import Control.Concurrent
import Control.Lens
import Control.Monad.Error
import Control.Monad.Reader
import Control.Monad.State
import Data.Map.Lens
import Data.Monoid
import System.FilePath
import System.Directory
import System.IO
import System.Process
-- from coroutine-object
import Control.Monad.Coroutine
import Control.Monad.Coroutine.Event
import Control.Monad.Coroutine.Logger
import Control.Monad.Coroutine.Object
import Control.Monad.Coroutine.Queue
import Control.Monad.Coroutine.World
-- from this package
import Type.CmdExec
import Type.CmdExecEvent
import Type.CmdSet
import Type.WorldState
import Util
--
import Prelude hiding ((.),id)
-- |
doCmdAction :: Int -> CmdSet -> (Event -> IO ()) -> IO ()
doCmdAction i cmdset@CmdSet {..} handler = do
forkIO $ do setCurrentDirectory workdir
(_mhin,Just hout,_mherr,h) <- createProcess (shell program) { std_out = CreatePipe }
str <- hGetContents hout
writeFile (workdir </> stdoutfile ) str
handler (eventWrap (Finish i))
return ()
-- | command executor actor
cmdexec :: forall m m1. (Monad m, MonadState (WorldAttrib m1) m) =>
Int -> ServerObj CmdOp m ()
cmdexec i = initServer (go i None)
where
go :: Int -> JobStatus CmdSet -> MethodInput CmdOp -> ServerT CmdOp m ()
go i _jst (Input CmdReady cset) = do
req <- request (Output CmdReady ())
go i (Assigned cset) req
go i (Assigned cset) (Input CmdInit ()) = do
jst' <- fireAction (doCmdAction i cset)
req <- request (Output CmdInit ())
go i (Started cset) req
{-
case ev of
CmdReady -> do
if i == i'
else return (False,jst)
Finish i' -> do
if i == i' then return (True,Ended)
else return (False,jst)
_ -> return (False,jst)
req <- if r then request (Output GiveEventSub ())
else request Ignore
workerW i jst' req
-}
| wavewave/cmdmanager | src/CmdExec.hs | bsd-3-clause | 2,371 | 0 | 14 | 602 | 563 | 303 | 260 | 47 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
-- |
-- Module: Data.StrictPut
-- Author: Andreas Voellmy <andreas.voellmy@yale.edu>
-- Alexander Vershilov <alexander.vershilov@gmail.com>
-- License: BSD-3
-- Stability: unstable
--
-- This module is improved version of Nettle.OpenFlow.StrictPut that
-- supports additional features like Markers and delayed input.
--
-- This module provides a monad for serializing data into byte strings.
-- It provides mostly the same interface that Data.Binary.Put does.
-- However, the implementation is different. It allows for the data to be
-- serialized into an existing array of Word8 values. This differs from the Data.Binary.Put
-- data type, which allocates a Word8 array every time a value is serialized.
-- This module's implementation is useful if you want to reuse the Word8 array for many serializations.
-- In the case of an OpenFlow server, we can reuse a buffer to send messages, since we have no use
-- for the the Word8 array, except to pass it to an IO procedure to write the data to a socket or file.
module Data.StrictPut (
runPutToByteString,
module Data.StrictPut.DelayedInput,
module Data.StrictPut.Marker,
module Data.StrictPut.Types,
module Data.StrictPut.PutM,
module Data.StrictPut.Buffer,
module Data.StrictPut.LookBehind
) where
import qualified Data.ByteString as S
import qualified Data.ByteString.Internal as S
import System.IO.Unsafe
import Data.StrictPut.DelayedInput
import Data.StrictPut.Types
import Data.StrictPut.Marker
import Data.StrictPut.PutM
import Data.StrictPut.Buffer
import Data.StrictPut.LookBehind
-- | Allocates a new byte string, and runs the Put writer with that byte string.
-- The first argument is an upper bound on the size of the array needed to do the serialization.
runPutToByteString :: Int -> Put -> S.ByteString
runPutToByteString maxSize put =
unsafeDupablePerformIO (S.createAndTrim maxSize (\ptr -> runPut ptr put))
-- unsafeDupablePerformIO (S.createAndTrim maxSize (\ptr -> (`minusPtr` ptr) <$> runPut ptr put ))
| qnikst/strictput | Data/StrictPut.hs | bsd-3-clause | 2,084 | 0 | 10 | 319 | 187 | 128 | 59 | 23 | 1 |
-- |
-- Copyright : Anders Claesson 2017
-- Maintainer : Anders Claesson <anders.claesson@gmail.com>
--
-- Common permutation statistics. Most of these are "set" versions of
-- those in Sym.Perm.Stat
--
module Sym.Perm.STAT
(
asc -- list of ascent
, ascIx -- ascent indices
, ascTops -- ascent tops
, ascBots -- ascent bottoms
, des -- descents
, desIx -- descent indices
, desTops -- descent tops
, desBots -- descent bottoms
, exc -- excedances
, fp -- fixed points
-- , sfp -- strong fixed points
-- , cyc -- cycles
-- , inv -- inversions
-- , peak -- peaks
-- , vall -- valleys
-- , dasc -- double ascents
-- , ddes -- double descents
-- , lmin -- left-to-right minima
-- , lmax -- left-to-right maxima
-- , rmin -- right-to-left minima
-- , rmax -- right-to-left maxima
-- , comp -- components
-- , scomp -- skew components
-- , asc0 -- small ascents
, des0 -- list small descents
, des0Ix -- indices of small descents
, des0Tops -- small descents tops
, des0Bots -- small descents bottoms
-- , lis -- longest increasing subsequence
-- , lds -- longest decreasing subsequence
) where
import Prelude hiding (head, last)
import Sym.Perm
import qualified Sym.Perm.SSYT as Y
import qualified Sym.Perm.D8 as D8
asc :: Perm -> [(Int, Int, Int)]
asc w =
[ (i,x,y)
| (i,x,y) <- zip3 [0..] ys (drop 1 ys)
, x < y
]
where
ys = toList w
ascIx :: Perm -> [Int]
ascIx w = [ i | (i,_,_) <- asc w ]
ascBots :: Perm -> [Int]
ascBots w = [ x | (_,x,_) <- asc w ]
ascTops :: Perm -> [Int]
ascTops w = [ y | (_,_,y) <- asc w ]
des :: Perm -> [(Int, Int, Int)]
des w =
[ (i,x,y)
| (i,x,y) <- zip3 [0..] ys (drop 1 ys)
, x > y
]
where
ys = toList w
desIx :: Perm -> [Int]
desIx w = [ i | (i,_,_) <- des w ]
desBots :: Perm -> [Int]
desBots w = [ x | (_,x,_) <- des w ]
desTops :: Perm -> [Int]
desTops w = [ y | (_,_,y) <- des w ]
exc :: Perm -> [Int]
exc w = [ i | i <- [0 .. size w - 1], w `at` i > i ]
fp :: Perm -> [Int]
fp w = [ i | i <- [0 .. size w - 1], w `at` i == i ]
-- sfp :: Perm -> [Int]
-- sfp = undefined
-- cyc :: Perm -> [[Int]]
-- cyc = undefined
-- inv :: Perm -> [(Int, Int)]
-- inv = undefined
-- peak :: Perm -> [Int]
-- peak = undefined
-- vall :: Perm -> [Int]
-- vall = undefined
-- dasc :: Perm -> [Int]
-- dasc = undefined
-- ddes :: Perm -> [Int]
-- ddes = undefined
-- lmin :: Perm -> [Int]
-- lmin = undefined
-- lmax :: Perm -> [Int]
-- lmax = undefined
-- rmin :: Perm -> [Int]
-- rmin = undefined
-- rmax :: Perm -> [Int]
-- rmax = undefined
-- comp :: Perm -> [Perm]
-- comp = undefined
-- scomp :: Perm -> [Perm]
-- scomp = undefined
-- asc0 :: Perm -> [Int]
-- asc0 = undefined
des0 :: Perm -> [(Int, Int, Int)]
des0 w =
[ (i,x,y)
| (i,x,y) <- zip3 [0..] ys (drop 1 ys)
, x == y + 1
]
where
ys = toList w
des0Ix :: Perm -> [Int]
des0Ix w = [ i | (i,_,_) <- des0 w ]
des0Bots :: Perm -> [Int]
des0Bots w = [ x | (_,x,_) <- des0 w ]
des0Tops :: Perm -> [Int]
des0Tops w = [ y | (_,_,y) <- des0 w ]
-- lis :: Perm -> [Int]
-- lis = undefined
-- lds :: Perm -> [Int]
-- lds = undefined
| akc/sym | Sym/Perm/STAT.hs | bsd-3-clause | 3,429 | 0 | 10 | 1,096 | 944 | 569 | 375 | 60 | 1 |
{-# LANGUAGE FlexibleInstances, StandaloneDeriving, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | We define lots of orphan Show instances here, for debugging and learning
-- purposes.
--
-- Most of the time while trying to figure out when a constructor is used or how
-- is a term compiled, it's easiest to just create an example and run the plugin
-- on it.
--
-- Without Show instances though, we can't easily inspect compiled outputs.
-- Outputable generated strings hide lots of details(especially constructors),
-- but we still export a `showOutputable` here, for similar reasons.
--
module CoreDump.Show where
-- import Control.Monad.IO.Class
import Data.IORef
import System.IO.Unsafe (unsafePerformIO)
import Class
import CostCentre
import Demand
import ForeignCall
import GhcPlugins
import IdInfo
import PrimOp
import TypeRep
import Prelude
--------------------------------------------------------------------------------
{-# NOINLINE dynFlags_ref #-}
dynFlags_ref :: IORef DynFlags
dynFlags_ref = unsafePerformIO (newIORef undefined)
{-# NOINLINE dynFlags #-}
dynFlags :: DynFlags
dynFlags = unsafePerformIO (readIORef dynFlags_ref)
-- initDynFlags :: (HasDynFlags m, MonadIO m) => m ()
-- initDynFlags = getDynFlags >>= liftIO .writeIORef dynFlags
showOutputable :: Outputable a => a -> String
showOutputable = showSDoc dynFlags . ppr
--------------------------------------------------------------------------------
-- * Orphan Show instances
deriving instance Show a => Show (Expr a)
deriving instance Show Type
deriving instance Show Literal
deriving instance Show a => Show (Tickish a)
deriving instance Show a => Show (Bind a)
deriving instance Show AltCon
deriving instance Show TyLit
deriving instance Show FunctionOrData
deriving instance Show Module
deriving instance Show CostCentre
deriving instance Show Role
deriving instance Show LeftOrRight
deriving instance Show IsCafCC
instance Show Class where
show _ = "Class"
deriving instance Show IdDetails
deriving instance Show PrimOp
deriving instance Show ForeignCall
deriving instance Show TickBoxOp
deriving instance Show PrimOpVecCat
deriving instance Show CCallSpec
deriving instance Show CCallTarget
deriving instance Show CCallConv
deriving instance Show SpecInfo
deriving instance Show OccInfo
deriving instance Show InlinePragma
deriving instance Show OneShotInfo
deriving instance Show CafInfo
deriving instance Show Unfolding
deriving instance Show UnfoldingSource
deriving instance Show UnfoldingGuidance
deriving instance Show Activation
deriving instance Show CoreRule
deriving instance Show StrictSig
deriving instance Show DmdType
instance Show RuleFun where
show _ = "RuleFun"
instance Show (UniqFM a) where
show _ = "UniqFM"
data SIdInfo
= IdInfo Arity SpecInfo Unfolding CafInfo
OneShotInfo InlinePragInfo OccInfo
StrictSig Demand ArityInfo
deriving (Show)
instance Show IdInfo where
show info = show (IdInfo arityInfo_ specInfo_ unfoldingInfo_
cafInfo_ oneShotInfo_ inlinePragInfo_
occInfo_ strictnessInfo_ demandInfo_
callArityInfo_)
where
arityInfo_ = arityInfo info
specInfo_ = specInfo info
unfoldingInfo_ = unfoldingInfo info
cafInfo_ = cafInfo info
oneShotInfo_ = oneShotInfo info
inlinePragInfo_ = inlinePragInfo info
occInfo_ = occInfo info
strictnessInfo_ = strictnessInfo info
demandInfo_ = demandInfo info
callArityInfo_ = callArityInfo info
-- Unique's Show instance is not parseable by haskell-src-exts,
-- disabling it for now
data SId = Id Name {- Unique -} Type IdDetails IdInfo
deriving (Show)
data STyVar = TyVar Name
deriving (Show)
instance Show Var where
show v
| isId v = show (Id name {- uniq_ -} ty details info)
| otherwise = show (TyVar name)
where
name = varName v
-- uniq_ = varUnique v
ty = varType v
details = idDetails v
info = idInfo v
instance Show DataCon where
show = show . dataConName
instance Show TyCon where
show = show . tyConName
instance Show ModuleName where
show = show . moduleNameString
instance Show PackageKey where
show = show . packageKeyString
-- Outputable outputs are not generating valid Haskell syntax, so we use an
-- extra `show` here.
instance Show Name where
show = show . showOutputable . nameOccName
-- deriving instance Show Name
instance Show OccName where
show = show . showOutputable
instance Show Coercion where
show _ = "Coercion"
-- Instance for non-terms related stuff.
deriving instance Show CoreToDo
deriving instance Show SimplifierMode
deriving instance Show CompilerPhase
deriving instance Show FloatOutSwitches
instance Show PluginPass where
show _ = "PluginPass"
| osa1/CoreDump | src/CoreDump/Show.hs | bsd-3-clause | 4,871 | 0 | 9 | 952 | 964 | 506 | 458 | 113 | 1 |
module P003 where
import Primes (primeFactors)
run :: IO ()
run = print result
where
n = 600851475143
result = last . primeFactors $ n
| tyehle/euler-haskell | src/P003.hs | bsd-3-clause | 147 | 0 | 8 | 37 | 50 | 28 | 22 | 6 | 1 |
{-# LANGUAGE RecordWildCards #-}
{- | [Haskell OpenFlow]
This is an implementation of OpenFlow in Haskell.
-}
module Network.OpenFlow (
OfpFrame(..)
, OfpHeader(..)
, OfpMsg(..)
, OfpError(..)
, OfpHelloFailedCode(..)
, OfpBadRequestCode(..)
, OfpBadActionCode(..)
, OfpFlowModFailedCode(..)
, OfpPortModFailedCode(..)
, OfpQueueOpFailedCode(..)
, OfpSwitchFeatures(..)
, OfpPhyPort(..)
, OfpCapabilities(..)
, OfpActionType(..)
, OfpPortConfig(..)
, OfpPortState(..)
, OfpPortFeatures(..)
, OfpSwitchConfig(..)
, OfpConfigFlags(..)
, OfpFlowMod(..)
, OfpMatch(..)
, OfpFlowModCommand(..)
, OfpFlowModFlags(..)
, OfpAction(..)
, OfpFlowWildcards(..)
, OfpPacketIn(..)
, OfpPacketInReason(..)
, OfpPacketOut(..)
, OfpFlowRemoved(..)
, OfpFlowRemovedReason(..)
, OfpPortStatus(..)
, OfpPortReason(..)
, OfpPortMod(..)
, OfpQueueGetConfigRequest(..)
, OfpQueueGetConfigReply(..)
, OfpPacketQueue(..)
, OfpQueueProp(..)
, readOfpFrame
) where
import GHC.Word
import Control.Monad
import Data.Functor
import Data.Bits
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C
import Data.Serialize
import Data.Serialize.Get
import Data.Serialize.Put
import Network.Socket hiding (recv)
import Network.Socket.ByteString
import Network.Info
data OfpFrame =
-- 5.1 Each OpenFlow message begins with the OpenFlow header
OfpFrame { hdr :: OfpHeader
, msg :: OfpMsg
} deriving (Show)
instance Serialize OfpFrame where
put (OfpFrame (OfpHeader version _ _ xid) msg) = do
putWord8 version
putWord8 $ msgType msg
let bs = runPut $ putOfpMsg msg
let len = ofpHdrLen + (BS.length bs)
put ((fromIntegral len) :: Word16)
putWord32be xid
putByteString bs
get = do
hdr <- get :: Get OfpHeader
msg <- getOfpMsg hdr
return $ OfpFrame hdr msg
data OfpHeader =
OfpHeader { version :: Word8
, ty :: Word8
, len :: Word16
, xid :: Word32
} deriving (Show)
ofpHdrLen = 8
instance Serialize OfpHeader where
put (OfpHeader {..}) = do
putWord8 version
putWord8 ty
putWord16be len
putWord32be xid
get = do
version <- liftM fromIntegral getWord8
ty <- liftM fromIntegral getWord8
len <- liftM fromIntegral getWord16be
xid <- liftM fromIntegral getWord32be
return $ OfpHeader version ty len xid
data OfpMsg = OfptHello [Word8]
| OfptError OfpError
| OfptEchoRequest [Word8]
| OfptEchoReply [Word8]
| OfptVendor
| OfptFeaturesRequest
| OfptFeaturesReply OfpSwitchFeatures
| OfptGetConfigRequest
| OfptGetConfigReply OfpSwitchConfig
| OfptSetConfig OfpSwitchConfig
| OfptPacketIn OfpPacketIn
| OfptFlowRemoved OfpFlowRemoved
| OfptPortStatus OfpPortStatus
| OfptPacketOut OfpPacketOut
| OfptFlowMod OfpFlowMod
| OfptPortMod OfpPortMod
| OfptBarrierRequest
| OfptBarrierReply
| OfptQueueGetConfigRequest OfpQueueGetConfigRequest
| OfptQueueGetConfigReply OfpQueueGetConfigReply
deriving (Show)
-- | Immutable messages
msgType (OfptHello _) = 0
msgType (OfptError _) = 1
msgType (OfptEchoRequest _) = 2
msgType (OfptEchoReply _) = 3
msgType (OfptVendor) = 4
-- | Switch configuration messages
msgType (OfptFeaturesRequest) = 5
msgType (OfptFeaturesReply _) = 6
msgType (OfptGetConfigRequest) = 7
msgType (OfptGetConfigReply _) = 8
msgType (OfptSetConfig _) = 9
-- | Asynchronous messages
msgType (OfptPacketIn _) = 10
msgType (OfptFlowRemoved _) = 11
msgType (OfptPortStatus _) = 12
-- | Controller command messages
msgType (OfptPacketOut _) = 13
msgType (OfptFlowMod _) = 14
msgType (OfptPortMod _) = 15
-- | Statistics messages
--msgType (OfptStatsRequest) = 16
--msgType (OfptStatsReply) = 17
-- | Barrier messages
msgType (OfptBarrierRequest) = 18
msgType (OfptBarrierReply) = 19
-- | Queue configuration messages
msgType (OfptQueueGetConfigRequest _) = 20
msgType (OfptQueueGetConfigReply _) = 21
data OfpError = OfpetHelloFailed OfpHelloFailedCode String
| OfpetBadRequest OfpBadRequestCode
| OfpetBadAction OfpBadActionCode
| OfpetFlowModFailed OfpFlowModFailedCode
| OfpetPortModFailed OfpPortModFailedCode
| OfpetQueueOpFailed OfpQueueOpFailedCode
deriving (Show)
data OfpHelloFailedCode = OfphfcIncompatible
| OfphfcEperm
deriving (Show, Enum)
data OfpBadRequestCode = OfpbrcBadVersion
| OfpbrcBadType
| OfpbrcBadStat
| OfpbrcBadVendor
| OfpbrcBadSubtype
| OfpbrcEperm
| OfpbrcBadLen
| OfpbrcBufferEmpty
| OfpbrcBufferUnknown
deriving (Show, Enum)
data OfpBadActionCode = OfpbacBadType
| OfpbacBadLen
| OfpbacBadVendor
| OfpbacBadVendorType
| OfpbacBadOutPort
| OfpbacBadArgument
| OfpbacEperm
| OfpbacTooMany
| OfpbacBadQueue
deriving (Show, Enum)
data OfpFlowModFailedCode = OfpfmfcAllTablesFull
| OfpfmfcOverlap
| OfpfmfcEperm
| OfpfmfcBadEmergTimeout
| OfpfmfcBadCommand
| OfpfmfcUnsupported
deriving (Show, Enum)
data OfpPortModFailedCode = OfppmfcBadPort
| OfppmfcBadHwAddr
deriving (Show, Enum)
data OfpQueueOpFailedCode = OfpqofcBadPort
| OfpqofcBadQueue
| OfpqofcEperm
deriving (Show, Enum)
data OfpSwitchFeatures =
OfpSwitchFeatures { dataPathId :: Word64
, nBuffers :: Word32
, nTables :: Word8
, capabilities :: [OfpCapabilities]
, actions :: [OfpActionType]
, ports :: [OfpPhyPort]
} deriving (Show)
data OfpCapabilities = OfpcFlowStats
| OfpcTableStats
| OfpcPortStats
| OfpcStp
| OfpcReserved
| OfpcIpReasm
| OfpcQueueStats
| OfpcArpMatchIp
deriving (Show, Enum)
data OfpActionType = OfpatOutput
| OfpatSetVlanVid
| OfpatSetVlanPcp
| OfpatStripVlan
| OfpatSetDlSrc
| OfpatSetDlDst
| OfpatSetNwSrc
| OfpatSetNwDst
| OfpatSetNwTos
| OfpatSetTpSrc
| OfpatSetTpDst
| OfpatEnqueue
| OfpatVendor
deriving (Show, Enum)
data OfpPhyPort =
OfpPhyPort { portNo :: Word16
, hwAddr :: MAC
, name :: String
, config :: [OfpPortConfig]
, state :: [OfpPortState]
, curr :: [OfpPortFeatures]
, advertised :: [OfpPortFeatures]
, supported :: [OfpPortFeatures]
, peer :: [OfpPortFeatures]
} deriving (Show)
instance Serialize MAC where
put (MAC w1 w2 w3 w4 w5 w6) = do
putWord8 w1
putWord8 w2
putWord8 w3
putWord8 w4
putWord8 w5
putWord8 w6
get = do
w1 <- liftM fromIntegral getWord8
w2 <- liftM fromIntegral getWord8
w3 <- liftM fromIntegral getWord8
w4 <- liftM fromIntegral getWord8
w5 <- liftM fromIntegral getWord8
w6 <- liftM fromIntegral getWord8
return $ MAC w1 w2 w3 w4 w5 w6
ofpMaxPortNameLen = 16
prependSpace xs 0 = xs
prependSpace xs n = prependSpace (" " ++ xs) (n-1)
instance Serialize OfpPhyPort where
put (OfpPhyPort {..}) = do
putWord16be portNo
put hwAddr
putByteString $ C.pack $ prependSpace name (ofpMaxPortNameLen - (length name))
putWord32be $ enumToBitInst config
putWord32be $ enumToBitInst state
putWord32be $ enumToBitInst curr
putWord32be $ enumToBitInst advertised
putWord32be $ enumToBitInst supported
putWord32be $ enumToBitInst peer
get = do
portNo <- liftM fromIntegral getWord16be
hwAddr <- get :: Get MAC
nameBS <- getByteString ofpMaxPortNameLen
let name = C.unpack nameBS
configBits <- getWord32be
stateBits <- getWord32be
currBits <- getWord32be
advertisedBits <- getWord32be
supportedBits <- getWord32be
peerBits <- getWord32be
let config = word32ToEnum configBits
let state = word32ToEnum stateBits
let curr = word32ToEnum currBits
let advertised = word32ToEnum advertisedBits
let supported = word32ToEnum supportedBits
let peer = word32ToEnum peerBits
return $ OfpPhyPort portNo hwAddr name config state curr advertised supported peer
data OfpPortConfig = OfppcPortDown
| OfppcNoStp
| OfppcNoRecv
| OfppcNoRecvStp
| OfppcNoFlood
| OfppcNoFwd
| OfppcNoPacketIn
deriving (Show, Enum)
data OfpPortState = OfppsLinkDown
| OfppsStpListen
| OfppsStpLearn
| OfppsStpForward
| OfppsStpBlock
| OfppsStpMask
deriving (Show, Enum)
data OfpPortFeatures = Ofppf10MbHd
| Ofppf10MbFd
| Ofppf100MbHd
| Ofppf100MbFd
| Ofppf1GbHd
| Ofppf1GbFd
| Ofppf10GbFd
| OfppfCopper
| OfppfFiber
| OfppfAutoneg
| OfppfPause
| OfppfPauseAsym
deriving (Show, Enum)
data OfpSwitchConfig =
OfpSwitchConfig { flags :: [OfpConfigFlags]
, missSendLen :: Word16
} deriving (Show)
instance Serialize OfpSwitchConfig where
put (OfpSwitchConfig {..}) = do
putWord16be $ enumToBitInst flags
putWord16be missSendLen
get = do
flagsBits <- getWord16be
let flags = word16ToEnum flagsBits
missSendLen <- getWord16be
return $ OfpSwitchConfig flags missSendLen
data OfpConfigFlags = OfpcFragNormal
| OfpcFragDrop
| OfpcFragReasm
| OfpcFragMask
deriving (Show, Enum)
data OfpFlowMod =
OfpFlowMod { match :: OfpMatch
, cookie :: Word64
, command :: OfpFlowModCommand
, idleTimeout :: Word16
, hardTimeout :: Word16
, priority :: Word16
, bufferId :: Word32
, outPort :: Word16
, fmFlags :: OfpFlowModFlags
, fmActions :: [OfpAction]
} deriving (Show)
instance Serialize OfpFlowMod where
put (OfpFlowMod {..}) = do
put match
putWord64be cookie
putWord16be $ fromIntegral $ fromEnum command
putWord16be idleTimeout
putWord16be hardTimeout
putWord16be priority
putWord32be bufferId
putWord16be outPort
putWord16be $ fromIntegral $ fromEnum fmFlags
mapM_ put fmActions
get = do
match <- get :: Get OfpMatch
cookie <- getWord64be
command' <- liftM fromIntegral getWord16be
let command = toEnum command' :: OfpFlowModCommand
idleTimeout <- getWord16be
hardTimeout <- getWord16be
priority <- getWord16be
bufferId <- getWord32be
outPort <- getWord16be
flags' <- liftM fromIntegral getWord16be
let flags = toEnum flags' :: OfpFlowModFlags
rem <- remaining
actionsBS <- getByteString rem
let actions = readMany actionsBS
return $ OfpFlowMod match cookie command idleTimeout hardTimeout priority bufferId outPort flags actions
data OfpAction = OfpOutput Word16 Word16
| OfpSetVlanVid Word16
| OfpSetVlanPcp Word8
| OfpStripVlan
| OfpSetDlSrc MAC
| OfpSetDlDst MAC
| OfpSetNwSrc Word32
| OfpSetNwDst Word32
| OfpSetNwTos Word8
| OfpSetTpSrc Word16
| OfpSetTpDst Word16
| OfpEnqueue Word16 Word32
| OfpVendor
deriving (Show)
instance Serialize OfpAction where
put (OfpOutput port maxLen) = do
putWord16be 0
putWord16be 8
putWord16be port
putWord16be maxLen
put (OfpSetVlanVid vlanVid) = do
putWord16be 1
putWord16be 8
putWord16be vlanVid
putWord16be 0 -- pad
put (OfpSetVlanPcp vlanPcp) = do
putWord16be 2
putWord16be 8
putWord8 vlanPcp
putWord8 0 -- pad
putWord8 0 -- pad
putWord8 0 -- pad
put (OfpStripVlan) = do
putWord16be 3
putWord16be 8
putWord32be 0 -- pad
put (OfpSetDlSrc mac) = do
putWord16be 4
putWord16be 16
put mac
putWord16be 0 -- pad
putWord16be 0 -- pad
putWord16be 0 -- pad
put (OfpSetDlDst mac) = do
putWord16be 5
putWord16be 16
put mac
putWord16be 0 -- pad
putWord16be 0 -- pad
putWord16be 0 -- pad
put (OfpSetNwSrc nwAddr) = do
putWord16be 6
putWord16be 8
putWord32be nwAddr
put (OfpSetNwDst nwAddr) = do
putWord16be 7
putWord16be 8
putWord32be nwAddr
put (OfpSetNwTos nwTos) = do
putWord16be 8
putWord16be 8
putWord8 nwTos
putWord8 0 -- pad
putWord8 0 -- pad
putWord8 0 -- pad
put (OfpSetTpSrc tpPort) = do
putWord16be 9
putWord16be 8
putWord16be tpPort
putWord16be 0 -- pad
put (OfpSetTpDst tpPort) = do
putWord16be 10
putWord16be 8
putWord16be tpPort
putWord16be 0 -- pad
put (OfpEnqueue port queueId) = do
putWord16be 11
putWord16be 16
putWord16be port
putWord16be 0 -- pad
putWord32be 0 -- pad
putWord32be queueId
put (OfpVendor) = do
putWord16be 0xffff
putWord16be 8
putWord32be 0 -- pad
get = do
ty <- getWord16be
len <- getWord16be
case ty of
0 -> do
port <- getWord16be
maxLen <- getWord16be
return $ OfpOutput port maxLen
1 -> do
vlanVid <- getWord16be
pad1 <- getWord16be
return $ OfpSetVlanVid vlanVid
2 -> do
vlanPcp <- getWord8
pad1 <- getWord8
pad2 <- getWord8
pad3 <- getWord8
return $ OfpSetVlanPcp vlanPcp
3 -> do
pad1 <- getWord32be
return $ OfpStripVlan
4 -> do
mac <- get :: Get MAC
pad1 <- getWord16be
pad2 <- getWord16be
pad3 <- getWord16be
return $ OfpSetDlSrc mac
5 -> do
mac <- get :: Get MAC
pad1 <- getWord16be
pad2 <- getWord16be
pad3 <- getWord16be
return $ OfpSetDlDst mac
6 -> do
nwAddr <- getWord32be
return $ OfpSetNwSrc nwAddr
7 -> do
nwAddr <- getWord32be
return $ OfpSetNwDst nwAddr
8 -> do
nwTos <- getWord8
pad1 <- getWord8
pad2 <- getWord8
pad2 <- getWord8
return $ OfpSetNwTos nwTos
9 -> do
tpPort <- getWord16be
pad1 <- getWord16be
return $ OfpSetTpSrc tpPort
10 -> do
tpPort <- getWord16be
pad1 <- getWord16be
return $ OfpSetTpDst tpPort
11 -> do
port <- getWord16be
pad1 <- getWord16be
pad2 <- getWord32be
queueId <- getWord32be
return $ OfpEnqueue port queueId
0xffff -> return OfpVendor
data OfpMatch =
OfpMatch { wildcards :: [OfpFlowWildcards]
, inPort :: Word16
, dlSrc :: MAC
, dlDst :: MAC
, dlVlan :: Word16
, dlVlanPcp :: Word8
, dlType :: Word16
, nwTos :: Word8
, nwProto :: Word8
, nwSrc :: Word32
, nwDst :: Word32
, tpSrc :: Word16
, tpDst :: Word16
} deriving (Show)
instance Serialize OfpMatch where
put (OfpMatch {..}) = do
putWord32be $ enumToBitInst wildcards
putWord16be inPort
put dlSrc
put dlDst
putWord16be dlVlan
putWord8 dlVlanPcp
putWord8 0
putWord16be dlType
putWord8 nwTos
putWord8 nwProto
putWord8 0
putWord8 0
putWord32be nwSrc
putWord32be nwDst
putWord16be tpSrc
putWord16be tpDst
get = do
wildcardBits <- getWord32be
let wildcards = word32ToEnum wildcardBits
inPort <- getWord16be
dlSrc <- get :: Get MAC
dlDst <- get :: Get MAC
dlVlan <- getWord16be
dlVlanPcp <- getWord8
pad1 <- getWord8
dlType <- getWord16be
nwTos <- getWord8
nwProto <- getWord8
pad2 <- getWord8
pad3 <- getWord8
nwSrc <- getWord32be
nwDst <- getWord32be
tpSrc <- getWord16be
tpDst <- getWord16be
return $ OfpMatch wildcards inPort dlSrc dlDst dlVlan dlVlanPcp dlType nwTos nwProto nwSrc nwDst tpSrc tpDst
data OfpFlowWildcards = OfpfwInPort
| OfpfwDlVlan
| OfpfwDlSrc
| OfpfwDlDst
| OfpfwDlType
| OfpfwNwProto
| OfpfwTpSrc
| OfpfwTpDst
| OfpfwNwSrc -- incomplete! 6 bits
| OfpfwNwDst -- incomplete! 6 bits
| OfpfwDlVlanPcp
| OfpfwNwTos
| OfpfwAll
deriving (Show)
instance Enum OfpFlowWildcards where
fromEnum (OfpfwInPort) = 0
fromEnum (OfpfwDlVlan) = 1
fromEnum (OfpfwDlSrc) = 2
fromEnum (OfpfwDlDst) = 3
fromEnum (OfpfwDlType) = 4
fromEnum (OfpfwNwProto) = 5
fromEnum (OfpfwTpSrc) = 6
fromEnum (OfpfwTpDst) = 7
fromEnum (OfpfwNwSrc) = 8
fromEnum (OfpfwNwDst) = 14
fromEnum (OfpfwDlVlanPcp) = 20
fromEnum (OfpfwNwTos) = 21
fromEnum (OfpfwAll) = 22
toEnum 0 = (OfpfwInPort)
toEnum 1 = (OfpfwDlVlan)
toEnum 2 = (OfpfwDlSrc)
toEnum 3 = (OfpfwDlDst)
toEnum 4 = (OfpfwDlType)
toEnum 5 = (OfpfwNwProto)
toEnum 6 = (OfpfwTpSrc)
toEnum 7 = (OfpfwTpDst)
toEnum 8 = (OfpfwNwSrc)
toEnum 14 = (OfpfwNwDst)
toEnum 20 = (OfpfwDlVlanPcp)
toEnum 21 = (OfpfwNwTos)
toEnum 22 = (OfpfwAll)
allWildcards = [ OfpfwInPort, OfpfwDlVlan, OfpfwDlSrc,
OfpfwDlDst, OfpfwDlType, OfpfwNwProto,
OfpfwTpSrc, OfpfwTpDst, OfpfwNwSrc, OfpfwNwDst,
OfpfwDlVlanPcp, OfpfwNwTos, OfpfwAll ]
data OfpFlowModCommand = OfpfcAdd
| OfpfcModify
| OfpfcModifyStrict
| OfpfcDelete
| OfpfcDeleteStrict
deriving (Show, Enum)
data OfpFlowModFlags = OfpffSendFlowRem
| OfpffCheckOverlap
| OfpffEmerg
deriving (Show, Enum)
data OfpPacketIn =
OfpPacketIn { piBufferId :: Word32
, totalLen :: Word16
, piInPort :: Word16
, reason :: OfpPacketInReason
, dat :: [Word8]
} deriving (Show)
instance Serialize OfpPacketIn where
put (OfpPacketIn {..}) = do
let dat' = BS.pack dat
let len = BS.length dat'
putWord32be piBufferId
put ((fromIntegral len) :: Word16)
putWord16be piInPort
putWord8 $ fromIntegral $ fromEnum reason
putWord8 0 -- pad
putByteString dat'
get = do
bufferId <- getWord32be
totalLen <- getWord16be
inPort <- getWord16be
reason' <- liftM fromIntegral getWord8
let reason = toEnum reason' :: OfpPacketInReason
pad0 <- getWord8
rem <- remaining
-- assert(rem == totalLen)
dat' <- getByteString rem
let dat = BS.unpack dat'
return $ OfpPacketIn bufferId totalLen inPort reason dat
data OfpPacketInReason = OfprNoMatch
| OfprAction
deriving (Show, Enum)
data OfpPacketOut =
OfpPacketOut { poBufferId :: Word32
, poInPort :: Word16
, poActions :: [OfpAction]
, poDat :: [Word8]
} deriving (Show)
instance Serialize OfpPacketOut where
put (OfpPacketOut {..}) = do
putWord32be poBufferId
putWord16be poInPort
let actions' = runPut (mapM_ put poActions)
let len = BS.length actions'
put ((fromIntegral len) :: Word16)
putByteString actions'
putByteString $ BS.pack poDat
get = do
bufferId <- getWord32be
inPort <- getWord16be
actionsLen <- getWord16be
actionsBS <- getByteString (fromIntegral actionsLen)
let actions = readMany actionsBS
rem <- remaining
dat' <- getByteString rem
let dat = BS.unpack dat'
return $ OfpPacketOut bufferId inPort actions dat
data OfpFlowRemoved =
OfpFlowRemoved { frMatch :: OfpMatch
, frCookie :: Word64
, frPriority :: Word16
, frReason :: OfpFlowRemovedReason
, durationSec :: Word32
, durationNSec :: Word32
, frIdleTimeout :: Word16
, packetCount :: Word64
, byteCount :: Word64
} deriving (Show)
instance Serialize OfpFlowRemoved where
put (OfpFlowRemoved match cookie pri reason sec nsec idleTO pCnt bCnt) = do
put match
putWord64be cookie
putWord16be pri
putWord8 $ fromIntegral $ fromEnum reason
putWord32be sec
putWord32be nsec
putWord16be idleTO
putWord64be pCnt
putWord64be bCnt
get = do
match <- get :: Get OfpMatch
cookie <- getWord64be
pri <- getWord16be
reason' <- liftM fromIntegral getWord8
let reason = toEnum reason' :: OfpFlowRemovedReason
sec <- getWord32be
nsec <- getWord32be
idleTO <- getWord16be
pCnt <- getWord64be
bCnt <- getWord64be
return $ OfpFlowRemoved match cookie pri reason sec nsec idleTO pCnt bCnt
data OfpFlowRemovedReason = OfprrIdleTimeout
| OfprrHardTimeout
| OfprrDelete
deriving (Show, Enum)
data OfpPortStatus =
OfpPortStatus { psReason :: OfpPortReason
, desc :: OfpPhyPort
} deriving (Show)
instance Serialize OfpPortStatus where
put (OfpPortStatus reason desc) = do
putWord8 $ fromIntegral $ fromEnum reason
putWord32be 0 -- pad
putWord16be 0 -- pad
putWord8 0 -- pad
put desc
get = do
reason' <- liftM fromIntegral getWord8
let reason = toEnum reason' :: OfpPortReason
pad1 <- getWord32be
pad2 <- getWord16be
pad3 <- getWord8
desc <- get :: Get OfpPhyPort
return $ OfpPortStatus reason desc
data OfpPortReason = OfpprAdd
| OfpprDelete
| OfpprModify
deriving (Show, Enum)
data OfpPortMod =
OfpPortMod { pmPortNo :: Word16
, pmHwAddr :: MAC
, pmConfig :: [OfpPortConfig]
, pmMask :: [OfpPortConfig]
, pmAdvertise :: [OfpPortFeatures]
} deriving (Show)
instance Serialize OfpPortMod where
put (OfpPortMod portNo hwAddr config mask adv) = do
putWord16be portNo
put hwAddr
putWord32be $ enumToBitInst config
putWord32be $ enumToBitInst mask
putWord32be $ enumToBitInst adv
putWord32be 0 -- pad
get = do
portNo <- getWord16be
hwAddr <- get :: Get MAC
config' <- getWord32be
mask' <- getWord32be
adv' <- getWord32be
pad <- getWord32be
let config = word32ToEnum config'
let mask = word32ToEnum mask'
let adv = word32ToEnum adv'
return $ OfpPortMod portNo hwAddr config mask adv
data OfpQueueGetConfigRequest =
OfpQueueGetConfigRequest { qreqPort :: Word16
} deriving (Show)
instance Serialize OfpQueueGetConfigRequest where
put (OfpQueueGetConfigRequest port) = do
putWord16be port
putWord16be 0 -- pad
get = do
port <- getWord16be
pad <- getWord16be
return $ OfpQueueGetConfigRequest port
data OfpQueueGetConfigReply =
OfpQueueGetConfigReply { qrepPort :: Word16
, queues :: [OfpPacketQueue]
} deriving (Show)
instance Serialize OfpQueueGetConfigReply where
put (OfpQueueGetConfigReply port queues) = do
putWord16be port
putWord32be 0 -- pad
putWord16be 0 -- pad
mapM_ put queues
get = do
port <- getWord16be
pad1 <- getWord32be
pad2 <- getWord16be
rem <- remaining
queuesBS <- getByteString rem
let queues = readMany queuesBS
return $ OfpQueueGetConfigReply port queues
data OfpPacketQueue =
OfpPacketQueue { pqQueueId :: Word32
, properties :: [OfpQueueProp]
} deriving (Show)
instance Serialize OfpPacketQueue where
put (OfpPacketQueue qid props) = do
putWord32be qid
let props' = runPut (mapM_ put props)
let len = BS.length props'
put ((fromIntegral len) :: Word16)
putWord16be 0 -- pad
putByteString props'
get = do
qid <- getWord32be
len <- getWord16be
pad <- getWord16be
propsBS <- getByteString (fromIntegral len)
let props = readMany propsBS
return $ OfpPacketQueue qid props
data OfpQueueProp = OfpqtNone
| OfpqtMinRate Word16
deriving (Show)
instance Serialize OfpQueueProp where
put (OfpqtNone) = do
putWord16be 0
putWord16be 8
putWord32be 0 -- pad
put (OfpqtMinRate rate) = do
putWord16be 1
putWord16be 16
putWord32be 0 -- pad
putWord16be rate
putWord32be 0 -- pad
putWord16be 0 -- pad
get = do
property <- getWord16be
len <- getWord16be
pad1 <- getWord32be
case property of
0 -> return OfpqtNone
1 -> do
rate <- getWord16be
pad2 <- getWord32be
pad3 <- getWord16be
return $ OfpqtMinRate rate
putOfpErrorMsg ty code = do
putWord16be ty
putWord16be $ fromIntegral $ fromEnum code
enumToBitInst :: (Enum a, Bits b, Num b) => [a] -> b
enumToBitInst xs = f xs 0
where
f xs' w = foldl (\ w x -> w `setBit` fromEnum x) w xs
putOfpMsg :: OfpMsg -> Put
putOfpMsg (OfptHello msg) = putByteString $ BS.pack msg
putOfpMsg (OfptError (OfpetHelloFailed code msg)) = do
putOfpErrorMsg 0 code
putByteString $ C.pack msg
putOfpMsg (OfptError (OfpetBadRequest code)) = putOfpErrorMsg 1 code
putOfpMsg (OfptError (OfpetBadAction code)) = putOfpErrorMsg 2 code
putOfpMsg (OfptError (OfpetFlowModFailed code)) = putOfpErrorMsg 3 code
putOfpMsg (OfptError (OfpetPortModFailed code)) = putOfpErrorMsg 4 code
putOfpMsg (OfptError (OfpetQueueOpFailed code)) = putOfpErrorMsg 5 code
putOfpMsg (OfptEchoRequest dat) = putByteString $ BS.pack dat
putOfpMsg (OfptEchoReply dat) = putByteString $ BS.pack dat
putOfpMsg (OfptVendor) = putByteString BS.empty
putOfpMsg (OfptFeaturesRequest) = putByteString BS.empty
putOfpMsg (OfptFeaturesReply (OfpSwitchFeatures dip nbuf ntab caps actions ports)) = do
putWord64be dip
putWord32be nbuf
putWord8 ntab
putWord8 0 -- pad
putWord8 0 -- pad
putWord8 0 -- pad
putWord32be $ enumToBitInst caps
putWord32be $ enumToBitInst actions
mapM_ put ports
putOfpMsg (OfptGetConfigRequest) = putByteString BS.empty
putOfpMsg (OfptGetConfigReply switchConfig) = put switchConfig
putOfpMsg (OfptSetConfig switchConfig) = put switchConfig
putOfpMsg (OfptPacketIn packetIn) = put packetIn
putOfpMsg (OfptFlowRemoved flowRemoved) = put flowRemoved
putOfpMsg (OfptPortStatus portStatus) = put portStatus
putOfpMsg (OfptPacketOut packetOut) = put packetOut
putOfpMsg (OfptFlowMod flowMod) = put flowMod
putOfpMsg (OfptPortMod portMod) = put portMod
putOfpMsg (OfptBarrierRequest) = putByteString BS.empty
putOfpMsg (OfptBarrierReply) = putByteString BS.empty
putOfpMsg (OfptQueueGetConfigRequest qreq) = put qreq
putOfpMsg (OfptQueueGetConfigReply qrep) = put qrep
readMany :: (Serialize t) => BS.ByteString -> [t]
readMany bs = case runGet (readMany' [] 0) bs of
Left err -> error err
Right t -> t
where
readMany _ 1000 = error "readMany overflow"
readMany' l n = do
x <- get
rem <- remaining
if rem > 0
then readMany' (x:l) (n+1)
else return (x:l)
bitInstToEnum :: (Enum a, Bits b) => b -> Int -> [a]
bitInstToEnum w width = f 0 []
where
f i xs = if i == width
then xs
else f (i+1) xs ++ [toEnum i | w `testBit` i]
word16ToEnum word = bitInstToEnum word 16
word32ToEnum word = bitInstToEnum word 32
word64ToEnum word = bitInstToEnum word 64
getOfpMsg (OfpHeader _ ty len _) =
case ty of
0 -> OfptHello <$> getMsg
1 -> getOfptError len'
2 -> OfptEchoRequest <$> getMsg
3 -> OfptEchoReply <$> getMsg
4 -> return OfptVendor
5 -> return OfptFeaturesRequest
6 -> getOfptFeaturesReply len'
7 -> return OfptGetConfigRequest
8 -> OfptGetConfigReply <$> get
9 -> OfptSetConfig <$> get
10 -> OfptPacketIn <$> get
11 -> OfptFlowRemoved <$> get
12 -> OfptPortStatus <$> get
13 -> OfptPacketOut <$> get
14 -> OfptFlowMod <$> get
15 -> OfptPortMod <$> get
18 -> return OfptBarrierRequest
19 -> return OfptBarrierReply
20 -> OfptQueueGetConfigRequest <$> get
21 -> OfptQueueGetConfigReply <$> get
where
len' = fromIntegral len
getMsg = liftM BS.unpack (getByteString (len' - ofpHdrLen))
getOfptError len = do
ty <- liftM fromIntegral getWord16be
code <- liftM fromIntegral getWord16be
OfptError <$> case ty of
0 -> do
bs <- getByteString (len - ofpHdrLen - 4)
return $ OfpetHelloFailed (toEnum code :: OfpHelloFailedCode) (C.unpack bs)
1 -> return $ OfpetBadRequest (toEnum code :: OfpBadRequestCode)
2 -> return $ OfpetBadAction (toEnum code :: OfpBadActionCode)
3 -> return $ OfpetFlowModFailed (toEnum code :: OfpFlowModFailedCode)
4 -> return $ OfpetPortModFailed (toEnum code :: OfpPortModFailedCode)
5 -> return $ OfpetQueueOpFailed (toEnum code :: OfpQueueOpFailedCode)
_ -> error $ "bad error type"
getOfptFeaturesReply len = do
dip <- liftM fromIntegral getWord64be
nbuf <- liftM fromIntegral getWord32be
ntab <- liftM fromIntegral getWord8
pad1 <- getWord8
pad2 <- getWord8
pad3 <- getWord8
capBits <- getWord32be
actBits <- getWord32be
phyPortsBS <- getByteString (len - ofpHdrLen - 24)
let caps = word32ToEnum capBits
let actions = word32ToEnum actBits
let ports = readMany phyPortsBS
return (OfptFeaturesReply (OfpSwitchFeatures dip nbuf ntab caps actions ports))
-- | Socket functions
peekHdrLen dat =
case runGet getHdrLen dat of
Left err -> error err
Right len -> fromIntegral len
where
getHdrLen = do
OfpHeader _ _ len _ <- get :: Get OfpHeader
return len
readOfpFrame :: Socket -> IO OfpFrame
readOfpFrame sock = do
dat <- recvExact ofpHdrLen
let bytesLeft = (peekHdrLen dat) - ofpHdrLen
if bytesLeft /= 0
then do dat' <- recvExact bytesLeft
case runGet get (BS.append dat dat') of
Left err -> error err
Right frame -> return frame
else do case runGet get dat of
Left err -> error err
Right frame -> return frame
where
recvExact bytes = do
b <- recvExact' bytes BS.empty
if BS.length b /= fromIntegral bytes
then error "expected.."
else return b
recvExact' bytes buf = do
dat <- recv sock bytes
let len = BS.length dat
if len == 0
then error "peer closed connection"
else do let buf' = BS.append buf dat
if len >= bytes
then return buf'
else recvExact' (bytes-len) buf'
| brooksbp/haskell-openflow | Network/OpenFlow.hs | bsd-3-clause | 33,143 | 0 | 17 | 11,304 | 8,561 | 4,257 | 4,304 | 965 | 20 |
-- Copyright 2013 Kevin Backhouse.
{-|
The 'TopKnot' instrument is used for knot tying across passes. It
allows a value to be written during the epilogue of one pass and read
during the prologue of a later pass. Knot tying is a technique
sometimes used in lazy functional programming, in which the definition
of a variable depends on its own value. The lazy programming technique
depends on an implicit two-pass ordering of the computation. For
example, the classic repmin program produces a pair of outputs - a
tree and an integer - and there is an implicit two-pass ordering where
the integer is computed during the first pass and the tree during the
second. The 'TopKnot' instrument allows the same technique to be
applied, but the ordering of the passes is managed explicitly by the
"Control.Monad.MultiPass" library, rather than implicitly by lazy
evalution.
-}
module Control.Monad.MultiPass.Instrument.TopKnot
( TopKnot
, load, store
)
where
import Control.Exception ( assert )
import Control.Monad.ST2
import Control.Monad.MultiPass
import Data.Maybe ( isNothing, isJust, fromJust )
-- | Abstract datatype for the instrument.
data TopKnot a r w p1 p2 tc
= TopKnot
{ loadInternal :: MultiPassPrologue r w tc (p2 a)
, storeInternal :: (p1 a) -> MultiPassEpilogue r w tc ()
}
-- | Load the value that was stored during the first pass.
load :: TopKnot a r w p1 p2 tc -> MultiPassPrologue r w tc (p2 a)
load =
loadInternal
-- | Store a value during the epilogue of the first pass. This
-- function should be called exactly once.
store :: TopKnot a r w p1 p2 tc -> p1 a -> MultiPassEpilogue r w tc ()
store =
storeInternal
-- Global Context.
newtype GC r w a
= GC (ST2Ref r w (Maybe a))
instance Instrument tc () () (TopKnot a r w Off Off tc) where
createInstrument _ _ () =
wrapInstrument $ TopKnot
{ loadInternal = return Off
, storeInternal = \Off -> return ()
}
-- First pass of the TopKnot instrument. The storeInternal method is
-- expected to be called exactly once during this pass.
instance Instrument tc () (GC r w a) (TopKnot a r w On Off tc) where
createInstrument st2ToMP _ (GC r) =
wrapInstrument $ TopKnot
{ loadInternal = return Off
, storeInternal = \(On x) ->
mkMultiPassEpilogue $ st2ToMP $
do mx <- readST2Ref r
assert (isNothing mx) $ return ()
writeST2Ref r (Just x)
}
-- Second pass of the TopKnot instrument.
instance Instrument tc () (GC r w a) (TopKnot a r w On On tc) where
createInstrument st2ToMP _ (GC r) =
wrapInstrument $ TopKnot
{ loadInternal =
mkMultiPassPrologue $ st2ToMP $
do mx <- readST2Ref r
assert (isJust mx) $ return ()
return $ On $ fromJust mx
, storeInternal = \(On x) ->
mkMultiPassEpilogue $ st2ToMP $
do mx <- readST2Ref r
assert (isNothing mx) $ return ()
writeST2Ref r (Just x)
}
-- This instrument never needs to back-track.
instance BackTrack r w tc (GC r w a)
instance NextGlobalContext r w () () (GC r w a) where
nextGlobalContext _ _ () () =
do mx <- newST2Ref Nothing
return (GC mx)
instance NextGlobalContext r w () (GC r w a) (GC r w a) where
nextGlobalContext _ _ () gc = return gc
| kevinbackhouse/Control-Monad-MultiPass | src/Control/Monad/MultiPass/Instrument/TopKnot.hs | bsd-3-clause | 3,318 | 0 | 16 | 823 | 815 | 421 | 394 | -1 | -1 |
{-# LANGUAGE FlexibleInstances, TypeOperators #-}
module Value.Number where
import Core.Val
instance ToText Number where
text = prim Fun "id" "$(function(x){return x})"
instance Num (Val Number) where
(+) = prim2 Fun "+" "$(function(a,b){return a+b})"
(*) = prim2 Fun "*" "$(function(a,b){return a*b})"
(-) = prim2 Fun "-" "$(function(a,b){return a-b})"
abs = prim Fun "abs" "$(Math.abs)"
signum = prim Fun "sign" "$(Math.sign)"
fromInteger i = Prim Con (show i) (show i)
instance Fractional (Val Number) where
(/) = prim2 Fun "/" "$(function(a,b){return a/b})"
fromRational r = Prim Con (show r) (show r)
mod :: Number :-> Number :~> Number
mod = prim2 Fun "%" "$(function(a,b){return a%b})"
max :: Number :-> Number :~> Number
max = prim2 Fun "max" "$(Math.max)"
min :: Number :-> Number :~> Number
min = prim2 Fun "min" "$(Math.min)"
sin :: Number :~> Number
sin = prim Fun "sin" "$(Math.sin)"
cos :: Number :~> Number
cos = prim Fun "cos" "$(Math.cos)"
sqrt :: Number :~> Number
sqrt = prim Fun "sqrt" "$(Math.sqrt)"
floor :: Number :~> Number
floor = prim Fun "floor" "$(Math.floor)"
infix 4 <, <=, >=, >
(>) :: Number :-> Number :~> Boolean
(>) = prim2 Fun ">" "$(function(a,b){return a>b})"
(>=) :: Number :-> Number :~> Boolean
(>=) = prim2 Fun ">=" "$(function(a,b){return a>=b})"
(<) :: Number :-> Number :~> Boolean
(<) = prim2 Fun "<" "$(function(a,b){return a<b})"
(<=) :: Number :-> Number :~> Boolean
(<=) = prim2 Fun "<=" "$(function(a,b){return a<=b})"
| sebastiaanvisser/frp-js | src/Value/Number.hs | bsd-3-clause | 1,506 | 0 | 8 | 271 | 483 | 262 | 221 | 38 | 1 |
module Widgets
( noteContainer
) where
import qualified Brick.Types as T
import Brick.Widgets.Core
( hLimit
, str
, viewport
, withAttr
)
import Lens.Micro ((^.))
import Widgets.Internal (fitInWidth)
-- |Given a viewport and note content generates Brick Widget containing the content.
noteContainer :: (Ord a, Show a)
=> a -- ^ Viewport
-> String -- ^ Note content
-> T.Widget a -- ^ The widget
noteContainer _vp content =
T.Widget T.Greedy T.Greedy $ do
ctx <- T.getContext
let maxW = ctx ^. T.availWidthL
T.render $
hLimit maxW $
viewport _vp T.Vertical $
str $ fitInWidth content maxW
| klausweiss/linotes | src/Widgets.hs | bsd-3-clause | 750 | 0 | 12 | 259 | 181 | 99 | 82 | 22 | 1 |
module Physics.Falling3d.UnitSphere3d
(
)
where
import System.Random
import Data.Random.Normal
import Data.Vect.Double.Base
import Physics.Falling.Math.UnitSphere
instance UnitSphere Normal3 where
unitSphereSamples = _randomSpherePoints
-- FIXME: implement uniform sampling for nUnitSphereSamples
_randomSpherePoints :: [Normal3]
_randomSpherePoints = map mkNormal $ _doubleList2Vec3List $ normals $ mkStdGen 0
_doubleList2Vec3List :: [Double] -> [Vec3]
_doubleList2Vec3List (a:b:c:l) = Vec3 a b c : _doubleList2Vec3List l
_doubleList2Vec3List _ = []
| sebcrozet/falling3d | Physics/Falling3d/UnitSphere3d.hs | bsd-3-clause | 570 | 0 | 9 | 79 | 142 | 80 | 62 | 13 | 1 |
module Abstract.Impl.Memcache.Counter (
module Abstract.Interfaces.Counter,
counterMemcache'Int,
defaultCounterMemcache'Int,
mkCounter'Memcache'Int,
mkCounter'Memcache'Int'Inc,
mkCounter'Memcache'Int'Dec,
mkCounter'Memcache'Int'Get
) where
import Abstract.Interfaces.Counter
import Abstract.Impl.Memcache.Counter.Internal
(mkCounter'Memcache'Int, counterMemcache'Int, defaultCounterMemcache'Int)
import Abstract.Impl.Memcache.Counter.Inc (mkCounter'Memcache'Int'Inc)
import Abstract.Impl.Memcache.Counter.Dec (mkCounter'Memcache'Int'Dec)
import Abstract.Impl.Memcache.Counter.Get (mkCounter'Memcache'Int'Get)
| adarqui/Abstract-Impl-Memcache | src/Abstract/Impl/Memcache/Counter.hs | bsd-3-clause | 618 | 0 | 5 | 38 | 99 | 68 | 31 | 14 | 0 |
module Main where
import Ivory.Artifact
import Control.Monad
import Gidl.Types
import Gidl.Interface
import Gidl.Parse
import Gidl.Schema
import Gidl.Backend.Cabal
import Gidl.Backend.Haskell.Types
import Gidl.Backend.Haskell.Interface
import Gidl.Backend.Haskell
main :: IO ()
main = do
test "tests/testtypes.sexpr"
runHaskellBackend "tests/testtypes.sexpr"
"gidl-haskell-backend-test"
(words "Gidl Haskell Test")
"tests/gidl-haskell-backend-test"
test :: FilePath -> IO ()
test f = do
c <- readFile f
case parseDecls c of
Left e -> putStrLn e
Right (te@(TypeEnv te'), ie@(InterfaceEnv ie')) -> do
{-
forM_ te' $ \(tn, t) -> do
putStrLn (tn ++ ":")
print (typeLeaves t)
let a = typeModule (words "Sample IDL Haskell Types")
(typeDescrToRepr tn te)
printArtifact a
-}
forM_ ie' $ \(iname, _i) -> do
printArtifact $ interfaceModule (words "Sample IDL Haskell Interface")
(interfaceDescrToRepr iname ie te)
| GaloisInc/gidl | tests/Test.hs | bsd-3-clause | 1,116 | 0 | 19 | 330 | 236 | 124 | 112 | 27 | 2 |
{-# LANGUAGE ScopedTypeVariables, FlexibleContexts, CPP #-}
module Main where
import Control.Monad.Error (runErrorT)
import Control.Monad.State (runStateT)
import Data.IORef (newIORef)
import Data.List (intersperse)
import System.IO (hFlush, stdout)
import Core (scheme)
import Initial (initialEnv, initialLoad)
import Types.Core (SchemeT (..))
import Types.Exception (SchemeException (..))
import Types.Syntax (EnvRef, Macro)
main :: IO ()
main = do
ref <- newIORef initialEnv
mac <- initialLoad ref
repl mac ref
repl :: Macro -> EnvRef -> IO ()
repl mac ref = do
putStr "scheme> "
hFlush stdout
str <- getLine
(results, mac') <- runStateT (runErrorT $ runSchemeT $ scheme ref str) mac
case results of
Left Exit -> putStrLn "Bye."
Left (Break e) -> next (show e) mac' ref
Left (err :: SchemeException) -> next (show err) mac' ref
Right es -> next (newline es) mac' ref
where
next e m r = putStrLn e >> repl m r
newline = concat . intersperse "\n" . map show
| amutake/psg-scheme | src/main.hs | bsd-3-clause | 1,039 | 0 | 12 | 231 | 387 | 199 | 188 | 30 | 4 |
class Composable a where
compose :: a -> a -> a
newtype Add = Add Integer deriving Show
instance Composable Add where
compose (Add x) (Add y) = Add $ x + y
newtype Mul = Mul Integer deriving Show
instance Composable Mul where
compose (Mul x) (Mul y) = Mul $ x * y
| YoshikuniJujo/funpaala | samples/26_type_class/composable1.hs | bsd-3-clause | 271 | 0 | 8 | 62 | 121 | 63 | 58 | 8 | 0 |
{-# LANGUAGE FlexibleContexts #-}
module Webcrank.Internal.Halt where
import Control.Monad.Trans.Either
import qualified Data.ByteString.Lazy as LB
import Network.HTTP.Types
import Webcrank.Internal.Types
runHaltT :: HaltT m a -> m (Either Halt a)
runHaltT = runEitherT . unHaltT
{-# INLINE runHaltT #-}
-- | Immediately end processing of the request, returning the response
-- @Status@. It is the responsibility of the resource to ensure that all
-- necessary response header and body elements have been added in
-- order to make that response code valid.
halt :: Monad m => Status -> HaltT m a
halt = HaltT . left . Halt
{-# INLINE halt #-}
-- | Immediately end processing of this request, returning a
-- @500 Internal Server Error@ response. The response body will contain the
-- reason.
werror :: Monad m => LB.ByteString -> HaltT m a
werror = werrorWith internalServerError500
{-# INLINE werror #-}
-- | Immediately end processing of this request, returning a response
-- with the given @Status@. The response body will contain the reason.
werrorWith :: Monad m => Status -> LB.ByteString -> HaltT m a
werrorWith s = HaltT . left . Error s
{-# INLINE werrorWith #-}
| webcrank/webcrank.hs | src/Webcrank/Internal/Halt.hs | bsd-3-clause | 1,178 | 0 | 8 | 198 | 194 | 110 | 84 | 18 | 1 |
{-# LANGUAGE RecordWildCards #-}
module UnitTests.Distribution.Client.Dependency.Modular.Solver (tests)
where
-- base
import Control.Monad
import Data.Maybe (isNothing)
import qualified Data.Version as V
import qualified Distribution.Version as V
-- test-framework
import Test.Tasty as TF
import Test.Tasty.HUnit (testCase, assertEqual, assertBool)
-- Cabal
import Language.Haskell.Extension ( Extension(..)
, KnownExtension(..), Language(..))
-- cabal-install
import Distribution.Client.PkgConfigDb (PkgConfigDb, pkgConfigDbFromList)
import Distribution.Client.Dependency.Types (Solver(Modular))
import UnitTests.Distribution.Client.Dependency.Modular.DSL
import UnitTests.Options
tests :: [TF.TestTree]
tests = [
testGroup "Simple dependencies" [
runTest $ mkTest db1 "alreadyInstalled" ["A"] (Just [])
, runTest $ mkTest db1 "installLatest" ["B"] (Just [("B", 2)])
, runTest $ mkTest db1 "simpleDep1" ["C"] (Just [("B", 1), ("C", 1)])
, runTest $ mkTest db1 "simpleDep2" ["D"] (Just [("B", 2), ("D", 1)])
, runTest $ mkTest db1 "failTwoVersions" ["C", "D"] Nothing
, runTest $ indep $ mkTest db1 "indepTwoVersions" ["C", "D"] (Just [("B", 1), ("B", 2), ("C", 1), ("D", 1)])
, runTest $ indep $ mkTest db1 "aliasWhenPossible1" ["C", "E"] (Just [("B", 1), ("C", 1), ("E", 1)])
, runTest $ indep $ mkTest db1 "aliasWhenPossible2" ["D", "E"] (Just [("B", 2), ("D", 1), ("E", 1)])
, runTest $ indep $ mkTest db2 "aliasWhenPossible3" ["C", "D"] (Just [("A", 1), ("A", 2), ("B", 1), ("B", 2), ("C", 1), ("D", 1)])
, runTest $ mkTest db1 "buildDepAgainstOld" ["F"] (Just [("B", 1), ("E", 1), ("F", 1)])
, runTest $ mkTest db1 "buildDepAgainstNew" ["G"] (Just [("B", 2), ("E", 1), ("G", 1)])
, runTest $ indep $ mkTest db1 "multipleInstances" ["F", "G"] Nothing
]
, testGroup "Flagged dependencies" [
runTest $ mkTest db3 "forceFlagOn" ["C"] (Just [("A", 1), ("B", 1), ("C", 1)])
, runTest $ mkTest db3 "forceFlagOff" ["D"] (Just [("A", 2), ("B", 1), ("D", 1)])
, runTest $ indep $ mkTest db3 "linkFlags1" ["C", "D"] Nothing
, runTest $ indep $ mkTest db4 "linkFlags2" ["C", "D"] Nothing
]
, testGroup "Stanzas" [
runTest $ mkTest db5 "simpleTest1" ["C"] (Just [("A", 2), ("C", 1)])
, runTest $ mkTest db5 "simpleTest2" ["D"] Nothing
, runTest $ mkTest db5 "simpleTest3" ["E"] (Just [("A", 1), ("E", 1)])
, runTest $ mkTest db5 "simpleTest4" ["F"] Nothing -- TODO
, runTest $ mkTest db5 "simpleTest5" ["G"] (Just [("A", 2), ("G", 1)])
, runTest $ mkTest db5 "simpleTest6" ["E", "G"] Nothing
, runTest $ indep $ mkTest db5 "simpleTest7" ["E", "G"] (Just [("A", 1), ("A", 2), ("E", 1), ("G", 1)])
, runTest $ mkTest db6 "depsWithTests1" ["C"] (Just [("A", 1), ("B", 1), ("C", 1)])
, runTest $ indep $ mkTest db6 "depsWithTests2" ["C", "D"] (Just [("A", 1), ("B", 1), ("C", 1), ("D", 1)])
]
, testGroup "Setup dependencies" [
runTest $ mkTest db7 "setupDeps1" ["B"] (Just [("A", 2), ("B", 1)])
, runTest $ mkTest db7 "setupDeps2" ["C"] (Just [("A", 2), ("C", 1)])
, runTest $ mkTest db7 "setupDeps3" ["D"] (Just [("A", 1), ("D", 1)])
, runTest $ mkTest db7 "setupDeps4" ["E"] (Just [("A", 1), ("A", 2), ("E", 1)])
, runTest $ mkTest db7 "setupDeps5" ["F"] (Just [("A", 1), ("A", 2), ("F", 1)])
, runTest $ mkTest db8 "setupDeps6" ["C", "D"] (Just [("A", 1), ("B", 1), ("B", 2), ("C", 1), ("D", 1)])
, runTest $ mkTest db9 "setupDeps7" ["F", "G"] (Just [("A", 1), ("B", 1), ("B",2 ), ("C", 1), ("D", 1), ("E", 1), ("E", 2), ("F", 1), ("G", 1)])
, runTest $ mkTest db10 "setupDeps8" ["C"] (Just [("C", 1)])
]
, testGroup "Base shim" [
runTest $ mkTest db11 "baseShim1" ["A"] (Just [("A", 1)])
, runTest $ mkTest db12 "baseShim2" ["A"] (Just [("A", 1)])
, runTest $ mkTest db12 "baseShim3" ["B"] (Just [("B", 1)])
, runTest $ mkTest db12 "baseShim4" ["C"] (Just [("A", 1), ("B", 1), ("C", 1)])
, runTest $ mkTest db12 "baseShim5" ["D"] Nothing
, runTest $ mkTest db12 "baseShim6" ["E"] (Just [("E", 1), ("syb", 2)])
]
, testGroup "Cycles" [
runTest $ mkTest db14 "simpleCycle1" ["A"] Nothing
, runTest $ mkTest db14 "simpleCycle2" ["A", "B"] Nothing
, runTest $ mkTest db14 "cycleWithFlagChoice1" ["C"] (Just [("C", 1), ("E", 1)])
, runTest $ mkTest db15 "cycleThroughSetupDep1" ["A"] Nothing
, runTest $ mkTest db15 "cycleThroughSetupDep2" ["B"] Nothing
, runTest $ mkTest db15 "cycleThroughSetupDep3" ["C"] (Just [("C", 2), ("D", 1)])
, runTest $ mkTest db15 "cycleThroughSetupDep4" ["D"] (Just [("D", 1)])
, runTest $ mkTest db15 "cycleThroughSetupDep5" ["E"] (Just [("C", 2), ("D", 1), ("E", 1)])
]
, testGroup "Extensions" [
runTest $ mkTestExts [EnableExtension CPP] dbExts1 "unsupported" ["A"] Nothing
, runTest $ mkTestExts [EnableExtension CPP] dbExts1 "unsupportedIndirect" ["B"] Nothing
, runTest $ mkTestExts [EnableExtension RankNTypes] dbExts1 "supported" ["A"] (Just [("A",1)])
, runTest $ mkTestExts (map EnableExtension [CPP,RankNTypes]) dbExts1 "supportedIndirect" ["C"] (Just [("A",1),("B",1), ("C",1)])
, runTest $ mkTestExts [EnableExtension CPP] dbExts1 "disabledExtension" ["D"] Nothing
, runTest $ mkTestExts (map EnableExtension [CPP,RankNTypes]) dbExts1 "disabledExtension" ["D"] Nothing
, runTest $ mkTestExts (UnknownExtension "custom" : map EnableExtension [CPP,RankNTypes]) dbExts1 "supportedUnknown" ["E"] (Just [("A",1),("B",1),("C",1),("E",1)])
]
, testGroup "Languages" [
runTest $ mkTestLangs [Haskell98] dbLangs1 "unsupported" ["A"] Nothing
, runTest $ mkTestLangs [Haskell98,Haskell2010] dbLangs1 "supported" ["A"] (Just [("A",1)])
, runTest $ mkTestLangs [Haskell98] dbLangs1 "unsupportedIndirect" ["B"] Nothing
, runTest $ mkTestLangs [Haskell98, Haskell2010, UnknownLanguage "Haskell3000"] dbLangs1 "supportedUnknown" ["C"] (Just [("A",1),("B",1),("C",1)])
]
, testGroup "Soft Constraints" [
runTest $ soft [ ExPref "A" $ mkvrThis 1] $ mkTest db13 "selectPreferredVersionSimple" ["A"] (Just [("A", 1)])
, runTest $ soft [ ExPref "A" $ mkvrOrEarlier 2] $ mkTest db13 "selectPreferredVersionSimple2" ["A"] (Just [("A", 2)])
, runTest $ soft [ ExPref "A" $ mkvrOrEarlier 2
, ExPref "A" $ mkvrOrEarlier 1] $ mkTest db13 "selectPreferredVersionMultiple" ["A"] (Just [("A", 1)])
, runTest $ soft [ ExPref "A" $ mkvrOrEarlier 1
, ExPref "A" $ mkvrOrEarlier 2] $ mkTest db13 "selectPreferredVersionMultiple2" ["A"] (Just [("A", 1)])
, runTest $ soft [ ExPref "A" $ mkvrThis 1
, ExPref "A" $ mkvrThis 2] $ mkTest db13 "selectPreferredVersionMultiple3" ["A"] (Just [("A", 2)])
, runTest $ soft [ ExPref "A" $ mkvrThis 1
, ExPref "A" $ mkvrOrEarlier 2] $ mkTest db13 "selectPreferredVersionMultiple4" ["A"] (Just [("A", 1)])
]
, testGroup "Buildable Field" [
testBuildable "avoid building component with unknown dependency" (ExAny "unknown")
, testBuildable "avoid building component with unknown extension" (ExExt (UnknownExtension "unknown"))
, testBuildable "avoid building component with unknown language" (ExLang (UnknownLanguage "unknown"))
, runTest $ mkTest dbBuildable1 "choose flags that set buildable to false" ["pkg"] (Just [("flag1-false", 1), ("flag2-true", 1), ("pkg", 1)])
, runTest $ mkTest dbBuildable2 "choose version that sets buildable to false" ["A"] (Just [("A", 1), ("B", 2)])
]
, testGroup "Pkg-config dependencies" [
runTest $ mkTestPCDepends [] dbPC1 "noPkgs" ["A"] Nothing
, runTest $ mkTestPCDepends [("pkgA", "0")] dbPC1 "tooOld" ["A"] Nothing
, runTest $ mkTestPCDepends [("pkgA", "1.0.0"), ("pkgB", "1.0.0")] dbPC1 "pruneNotFound" ["C"] (Just [("A", 1), ("B", 1), ("C", 1)])
, runTest $ mkTestPCDepends [("pkgA", "1.0.0"), ("pkgB", "2.0.0")] dbPC1 "chooseNewest" ["C"] (Just [("A", 1), ("B", 2), ("C", 1)])
]
]
where
-- | Combinator to turn on --independent-goals behavior, i.e. solve
-- for the goals as if we were solving for each goal independently.
-- (This doesn't really work well at the moment, see #2842)
indep test = test { testIndepGoals = IndepGoals True }
soft prefs test = test { testSoftConstraints = prefs }
mkvrThis = V.thisVersion . makeV
mkvrOrEarlier = V.orEarlierVersion . makeV
makeV v = V.Version [v,0,0] []
{-------------------------------------------------------------------------------
Solver tests
-------------------------------------------------------------------------------}
data SolverTest = SolverTest {
testLabel :: String
, testTargets :: [String]
, testResult :: Maybe [(String, Int)]
, testIndepGoals :: IndepGoals
, testSoftConstraints :: [ExPreference]
, testDb :: ExampleDb
, testSupportedExts :: Maybe [Extension]
, testSupportedLangs :: Maybe [Language]
, testPkgConfigDb :: PkgConfigDb
}
-- | Makes a solver test case, consisting of the following components:
--
-- 1. An 'ExampleDb', representing the package database (both
-- installed and remote) we are doing dependency solving over,
-- 2. A 'String' name for the test,
-- 3. A list '[String]' of package names to solve for
-- 4. The expected result, either 'Nothing' if there is no
-- satisfying solution, or a list '[(String, Int)]' of
-- packages to install, at which versions.
--
-- See 'UnitTests.Distribution.Client.Dependency.Modular.DSL' for how
-- to construct an 'ExampleDb', as well as definitions of 'db1' etc.
-- in this file.
mkTest :: ExampleDb
-> String
-> [String]
-> Maybe [(String, Int)]
-> SolverTest
mkTest = mkTestExtLangPC Nothing Nothing []
mkTestExts :: [Extension]
-> ExampleDb
-> String
-> [String]
-> Maybe [(String, Int)]
-> SolverTest
mkTestExts exts = mkTestExtLangPC (Just exts) Nothing []
mkTestLangs :: [Language]
-> ExampleDb
-> String
-> [String]
-> Maybe [(String, Int)]
-> SolverTest
mkTestLangs langs = mkTestExtLangPC Nothing (Just langs) []
mkTestPCDepends :: [(String, String)]
-> ExampleDb
-> String
-> [String]
-> Maybe [(String, Int)]
-> SolverTest
mkTestPCDepends pkgConfigDb = mkTestExtLangPC Nothing Nothing pkgConfigDb
mkTestExtLangPC :: Maybe [Extension]
-> Maybe [Language]
-> [(String, String)]
-> ExampleDb
-> String
-> [String]
-> Maybe [(String, Int)]
-> SolverTest
mkTestExtLangPC exts langs pkgConfigDb db label targets result = SolverTest {
testLabel = label
, testTargets = targets
, testResult = result
, testIndepGoals = IndepGoals False
, testSoftConstraints = []
, testDb = db
, testSupportedExts = exts
, testSupportedLangs = langs
, testPkgConfigDb = pkgConfigDbFromList pkgConfigDb
}
runTest :: SolverTest -> TF.TestTree
runTest SolverTest{..} = askOption $ \(OptionShowSolverLog showSolverLog) ->
testCase testLabel $ do
let (_msgs, result) = exResolve testDb testSupportedExts
testSupportedLangs testPkgConfigDb testTargets
Modular Nothing testIndepGoals (ReorderGoals False)
testSoftConstraints
when showSolverLog $ mapM_ putStrLn _msgs
case result of
Left err -> assertBool ("Unexpected error:\n" ++ err) (isNothing testResult)
Right plan -> assertEqual "" testResult (Just (extractInstallPlan plan))
{-------------------------------------------------------------------------------
Specific example database for the tests
-------------------------------------------------------------------------------}
db1 :: ExampleDb
db1 =
let a = exInst "A" 1 "A-1" []
in [ Left a
, Right $ exAv "B" 1 [ExAny "A"]
, Right $ exAv "B" 2 [ExAny "A"]
, Right $ exAv "C" 1 [ExFix "B" 1]
, Right $ exAv "D" 1 [ExFix "B" 2]
, Right $ exAv "E" 1 [ExAny "B"]
, Right $ exAv "F" 1 [ExFix "B" 1, ExAny "E"]
, Right $ exAv "G" 1 [ExFix "B" 2, ExAny "E"]
, Right $ exAv "Z" 1 []
]
-- In this example, we _can_ install C and D as independent goals, but we have
-- to pick two diferent versions for B (arbitrarily)
db2 :: ExampleDb
db2 = [
Right $ exAv "A" 1 []
, Right $ exAv "A" 2 []
, Right $ exAv "B" 1 [ExAny "A"]
, Right $ exAv "B" 2 [ExAny "A"]
, Right $ exAv "C" 1 [ExAny "B", ExFix "A" 1]
, Right $ exAv "D" 1 [ExAny "B", ExFix "A" 2]
]
db3 :: ExampleDb
db3 = [
Right $ exAv "A" 1 []
, Right $ exAv "A" 2 []
, Right $ exAv "B" 1 [exFlag "flagB" [ExFix "A" 1] [ExFix "A" 2]]
, Right $ exAv "C" 1 [ExFix "A" 1, ExAny "B"]
, Right $ exAv "D" 1 [ExFix "A" 2, ExAny "B"]
]
-- | Like db3, but the flag picks a different package rather than a
-- different package version
--
-- In db3 we cannot install C and D as independent goals because:
--
-- * The multiple instance restriction says C and D _must_ share B
-- * Since C relies on A-1, C needs B to be compiled with flagB on
-- * Since D relies on A-2, D needs B to be compiled with flagB off
-- * Hence C and D have incompatible requirements on B's flags.
--
-- However, _even_ if we don't check explicitly that we pick the same flag
-- assignment for 0.B and 1.B, we will still detect the problem because
-- 0.B depends on 0.A-1, 1.B depends on 1.A-2, hence we cannot link 0.A to
-- 1.A and therefore we cannot link 0.B to 1.B.
--
-- In db4 the situation however is trickier. We again cannot install
-- packages C and D as independent goals because:
--
-- * As above, the multiple instance restriction says that C and D _must_ share B
-- * Since C relies on Ax-2, it requires B to be compiled with flagB off
-- * Since D relies on Ay-2, it requires B to be compiled with flagB on
-- * Hence C and D have incompatible requirements on B's flags.
--
-- But now this requirement is more indirect. If we only check dependencies
-- we don't see the problem:
--
-- * We link 0.B to 1.B
-- * 0.B relies on Ay-1
-- * 1.B relies on Ax-1
--
-- We will insist that 0.Ay will be linked to 1.Ay, and 0.Ax to 1.Ax, but since
-- we only ever assign to one of these, these constraints are never broken.
db4 :: ExampleDb
db4 = [
Right $ exAv "Ax" 1 []
, Right $ exAv "Ax" 2 []
, Right $ exAv "Ay" 1 []
, Right $ exAv "Ay" 2 []
, Right $ exAv "B" 1 [exFlag "flagB" [ExFix "Ax" 1] [ExFix "Ay" 1]]
, Right $ exAv "C" 1 [ExFix "Ax" 2, ExAny "B"]
, Right $ exAv "D" 1 [ExFix "Ay" 2, ExAny "B"]
]
-- | Some tests involving testsuites
--
-- Note that in this test framework test suites are always enabled; if you
-- want to test without test suites just set up a test database without
-- test suites.
--
-- * C depends on A (through its test suite)
-- * D depends on B-2 (through its test suite), but B-2 is unavailable
-- * E depends on A-1 directly and on A through its test suite. We prefer
-- to use A-1 for the test suite in this case.
-- * F depends on A-1 directly and on A-2 through its test suite. In this
-- case we currently fail to install F, although strictly speaking
-- test suites should be considered independent goals.
-- * G is like E, but for version A-2. This means that if we cannot install
-- E and G together, unless we regard them as independent goals.
db5 :: ExampleDb
db5 = [
Right $ exAv "A" 1 []
, Right $ exAv "A" 2 []
, Right $ exAv "B" 1 []
, Right $ exAv "C" 1 [] `withTest` ExTest "testC" [ExAny "A"]
, Right $ exAv "D" 1 [] `withTest` ExTest "testD" [ExFix "B" 2]
, Right $ exAv "E" 1 [ExFix "A" 1] `withTest` ExTest "testE" [ExAny "A"]
, Right $ exAv "F" 1 [ExFix "A" 1] `withTest` ExTest "testF" [ExFix "A" 2]
, Right $ exAv "G" 1 [ExFix "A" 2] `withTest` ExTest "testG" [ExAny "A"]
]
-- Now the _dependencies_ have test suites
--
-- * Installing C is a simple example. C wants version 1 of A, but depends on
-- B, and B's testsuite depends on an any version of A. In this case we prefer
-- to link (if we don't regard test suites as independent goals then of course
-- linking here doesn't even come into it).
-- * Installing [C, D] means that we prefer to link B -- depending on how we
-- set things up, this means that we should also link their test suites.
db6 :: ExampleDb
db6 = [
Right $ exAv "A" 1 []
, Right $ exAv "A" 2 []
, Right $ exAv "B" 1 [] `withTest` ExTest "testA" [ExAny "A"]
, Right $ exAv "C" 1 [ExFix "A" 1, ExAny "B"]
, Right $ exAv "D" 1 [ExAny "B"]
]
-- Packages with setup dependencies
--
-- Install..
-- * B: Simple example, just make sure setup deps are taken into account at all
-- * C: Both the package and the setup script depend on any version of A.
-- In this case we prefer to link
-- * D: Variation on C.1 where the package requires a specific (not latest)
-- version but the setup dependency is not fixed. Again, we prefer to
-- link (picking the older version)
-- * E: Variation on C.2 with the setup dependency the more inflexible.
-- Currently, in this case we do not see the opportunity to link because
-- we consider setup dependencies after normal dependencies; we will
-- pick A.2 for E, then realize we cannot link E.setup.A to A.2, and pick
-- A.1 instead. This isn't so easy to fix (if we want to fix it at all);
-- in particular, considering setup dependencies _before_ other deps is
-- not an improvement, because in general we would prefer to link setup
-- setups to package deps, rather than the other way around. (For example,
-- if we change this ordering then the test for D would start to install
-- two versions of A).
-- * F: The package and the setup script depend on different versions of A.
-- This will only work if setup dependencies are considered independent.
db7 :: ExampleDb
db7 = [
Right $ exAv "A" 1 []
, Right $ exAv "A" 2 []
, Right $ exAv "B" 1 [] `withSetupDeps` [ExAny "A"]
, Right $ exAv "C" 1 [ExAny "A" ] `withSetupDeps` [ExAny "A" ]
, Right $ exAv "D" 1 [ExFix "A" 1] `withSetupDeps` [ExAny "A" ]
, Right $ exAv "E" 1 [ExAny "A" ] `withSetupDeps` [ExFix "A" 1]
, Right $ exAv "F" 1 [ExFix "A" 2] `withSetupDeps` [ExFix "A" 1]
]
-- If we install C and D together (not as independent goals), we need to build
-- both B.1 and B.2, both of which depend on A.
db8 :: ExampleDb
db8 = [
Right $ exAv "A" 1 []
, Right $ exAv "B" 1 [ExAny "A"]
, Right $ exAv "B" 2 [ExAny "A"]
, Right $ exAv "C" 1 [] `withSetupDeps` [ExFix "B" 1]
, Right $ exAv "D" 1 [] `withSetupDeps` [ExFix "B" 2]
]
-- Extended version of `db8` so that we have nested setup dependencies
db9 :: ExampleDb
db9 = db8 ++ [
Right $ exAv "E" 1 [ExAny "C"]
, Right $ exAv "E" 2 [ExAny "D"]
, Right $ exAv "F" 1 [] `withSetupDeps` [ExFix "E" 1]
, Right $ exAv "G" 1 [] `withSetupDeps` [ExFix "E" 2]
]
-- Multiple already-installed packages with inter-dependencies, and one package
-- (C) that depends on package A-1 for its setup script and package A-2 as a
-- library dependency.
db10 :: ExampleDb
db10 =
let rts = exInst "rts" 1 "rts-inst" []
ghc_prim = exInst "ghc-prim" 1 "ghc-prim-inst" [rts]
base = exInst "base" 1 "base-inst" [rts, ghc_prim]
a1 = exInst "A" 1 "A1-inst" [base]
a2 = exInst "A" 2 "A2-inst" [base]
in [
Left rts
, Left ghc_prim
, Left base
, Left a1
, Left a2
, Right $ exAv "C" 1 [ExFix "A" 2] `withSetupDeps` [ExFix "A" 1]
]
-- | Tests for dealing with base shims
db11 :: ExampleDb
db11 =
let base3 = exInst "base" 3 "base-3-inst" [base4]
base4 = exInst "base" 4 "base-4-inst" []
in [
Left base3
, Left base4
, Right $ exAv "A" 1 [ExFix "base" 3]
]
-- | Slightly more realistic version of db11 where base-3 depends on syb
-- This means that if a package depends on base-3 and on syb, then they MUST
-- share the version of syb
--
-- * Package A relies on base-3 (which relies on base-4)
-- * Package B relies on base-4
-- * Package C relies on both A and B
-- * Package D relies on base-3 and on syb-2, which is not possible because
-- base-3 has a dependency on syb-1 (non-inheritance of the Base qualifier)
-- * Package E relies on base-4 and on syb-2, which is fine.
db12 :: ExampleDb
db12 =
let base3 = exInst "base" 3 "base-3-inst" [base4, syb1]
base4 = exInst "base" 4 "base-4-inst" []
syb1 = exInst "syb" 1 "syb-1-inst" [base4]
in [
Left base3
, Left base4
, Left syb1
, Right $ exAv "syb" 2 [ExFix "base" 4]
, Right $ exAv "A" 1 [ExFix "base" 3, ExAny "syb"]
, Right $ exAv "B" 1 [ExFix "base" 4, ExAny "syb"]
, Right $ exAv "C" 1 [ExAny "A", ExAny "B"]
, Right $ exAv "D" 1 [ExFix "base" 3, ExFix "syb" 2]
, Right $ exAv "E" 1 [ExFix "base" 4, ExFix "syb" 2]
]
db13 :: ExampleDb
db13 = [
Right $ exAv "A" 1 []
, Right $ exAv "A" 2 []
, Right $ exAv "A" 3 []
]
-- | Database with some cycles
--
-- * Simplest non-trivial cycle: A -> B and B -> A
-- * There is a cycle C -> D -> C, but it can be broken by picking the
-- right flag assignment.
db14 :: ExampleDb
db14 = [
Right $ exAv "A" 1 [ExAny "B"]
, Right $ exAv "B" 1 [ExAny "A"]
, Right $ exAv "C" 1 [exFlag "flagC" [ExAny "D"] [ExAny "E"]]
, Right $ exAv "D" 1 [ExAny "C"]
, Right $ exAv "E" 1 []
]
-- | Cycles through setup dependencies
--
-- The first cycle is unsolvable: package A has a setup dependency on B,
-- B has a regular dependency on A, and we only have a single version available
-- for both.
--
-- The second cycle can be broken by picking different versions: package C-2.0
-- has a setup dependency on D, and D has a regular dependency on C-*. However,
-- version C-1.0 is already available (perhaps it didn't have this setup dep).
-- Thus, we should be able to break this cycle even if we are installing package
-- E, which explictly depends on C-2.0.
db15 :: ExampleDb
db15 = [
-- First example (real cycle, no solution)
Right $ exAv "A" 1 [] `withSetupDeps` [ExAny "B"]
, Right $ exAv "B" 1 [ExAny "A"]
-- Second example (cycle can be broken by picking versions carefully)
, Left $ exInst "C" 1 "C-1-inst" []
, Right $ exAv "C" 2 [] `withSetupDeps` [ExAny "D"]
, Right $ exAv "D" 1 [ExAny "C" ]
, Right $ exAv "E" 1 [ExFix "C" 2]
]
dbExts1 :: ExampleDb
dbExts1 = [
Right $ exAv "A" 1 [ExExt (EnableExtension RankNTypes)]
, Right $ exAv "B" 1 [ExExt (EnableExtension CPP), ExAny "A"]
, Right $ exAv "C" 1 [ExAny "B"]
, Right $ exAv "D" 1 [ExExt (DisableExtension CPP), ExAny "B"]
, Right $ exAv "E" 1 [ExExt (UnknownExtension "custom"), ExAny "C"]
]
dbLangs1 :: ExampleDb
dbLangs1 = [
Right $ exAv "A" 1 [ExLang Haskell2010]
, Right $ exAv "B" 1 [ExLang Haskell98, ExAny "A"]
, Right $ exAv "C" 1 [ExLang (UnknownLanguage "Haskell3000"), ExAny "B"]
]
-- | cabal must set enable-lib to false in order to avoid the unavailable
-- dependency. Flags are true by default. The flag choice causes "pkg" to
-- depend on "false-dep".
testBuildable :: String -> ExampleDependency -> TestTree
testBuildable testName unavailableDep =
runTest $ mkTestExtLangPC (Just []) (Just []) [] db testName ["pkg"] expected
where
expected = Just [("false-dep", 1), ("pkg", 1)]
db = [
Right $ exAv "pkg" 1
[ unavailableDep
, ExFlag "enable-lib" (Buildable []) NotBuildable ]
`withTest`
ExTest "test" [exFlag "enable-lib"
[ExAny "true-dep"]
[ExAny "false-dep"]]
, Right $ exAv "true-dep" 1 []
, Right $ exAv "false-dep" 1 []
]
-- | cabal must choose -flag1 +flag2 for "pkg", which requires packages
-- "flag1-false" and "flag2-true".
dbBuildable1 :: ExampleDb
dbBuildable1 = [
Right $ exAv "pkg" 1
[ ExAny "unknown"
, ExFlag "flag1" (Buildable []) NotBuildable
, ExFlag "flag2" (Buildable []) NotBuildable]
`withTests`
[ ExTest "optional-test"
[ ExAny "unknown"
, ExFlag "flag1"
(Buildable [])
(Buildable [ExFlag "flag2" NotBuildable (Buildable [])])]
, ExTest "test" [ exFlag "flag1" [ExAny "flag1-true"] [ExAny "flag1-false"]
, exFlag "flag2" [ExAny "flag2-true"] [ExAny "flag2-false"]]
]
, Right $ exAv "flag1-true" 1 []
, Right $ exAv "flag1-false" 1 []
, Right $ exAv "flag2-true" 1 []
, Right $ exAv "flag2-false" 1 []
]
-- | Package databases for testing @pkg-config@ dependencies.
dbPC1 :: ExampleDb
dbPC1 = [
Right $ exAv "A" 1 [ExPkg ("pkgA", 1)]
, Right $ exAv "B" 1 [ExPkg ("pkgB", 1), ExAny "A"]
, Right $ exAv "B" 2 [ExPkg ("pkgB", 2), ExAny "A"]
, Right $ exAv "C" 1 [ExAny "B"]
]
-- | cabal must pick B-2 to avoid the unknown dependency.
dbBuildable2 :: ExampleDb
dbBuildable2 = [
Right $ exAv "A" 1 [ExAny "B"]
, Right $ exAv "B" 1 [ExAny "unknown"]
, Right $ exAv "B" 2
[ ExAny "unknown"
, ExFlag "disable-lib" NotBuildable (Buildable [])
]
, Right $ exAv "B" 3 [ExAny "unknown"]
]
| gbaz/cabal | cabal-install/tests/UnitTests/Distribution/Client/Dependency/Modular/Solver.hs | bsd-3-clause | 26,482 | 0 | 17 | 7,065 | 7,555 | 4,184 | 3,371 | 365 | 2 |
-- |
-- Module : Network.Pcap.Conduit
-- Copyright : (c) Austin Seipp 2012
-- License : BSD3
--
-- Maintainer : mad.one@gmail.com
-- Stability : experimental
-- Portability : GHC probably
--
-- This package provides conduit 'Sources' for pcap data ( captured by
-- wireshark, tcpdump, etc.) You can enumerate pcap files and live
-- interfaces.
--
-- Based on @pcap-enumerator@.
--
module Network.Pcap.Conduit
( Packet -- :: *
, sourceOffline -- :: MonadIO m => FilePath -> Source m Packet
, sourceLive -- :: MonadIO m => String -> Int -> Bool -> Int64 -> Source m Packet
) where
import Control.Monad.IO.Class (liftIO, MonadIO)
import Data.ByteString (ByteString)
import Data.Conduit (Source, yield)
import Data.Int (Int64)
import Network.Pcap
-- | Convenient alias.
type Packet = (PktHdr, ByteString)
-- | Create a conduit 'Source' from a pcap data file.
sourceOffline :: MonadIO m => FilePath -> Source m Packet
sourceOffline path = (liftIO $ openOffline path) >>= sourcePcap1
-- | Create a conduit 'Source' from a live interface.
sourceLive :: MonadIO m
=> String -- ^ Device name
-> Int -- ^ Snapshot length in bytes
-> Bool -- ^ Promiscuous mode?
-> Int64 -- ^ Timeout (in microseconds)
-> Source m Packet
sourceLive n s p t = (liftIO $ openLive n s p t) >>= sourcePcap1
sourcePcap1 :: MonadIO m => PcapHandle -> Source m Packet
sourcePcap1 h = do
pkt@(hdr,_) <- liftIO (nextBS h)
if (hdrCaptureLength hdr == 0)
then return ()
else yield pkt >> sourcePcap1 h
| thoughtpolice/pcap-conduit | Network/Pcap/Conduit.hs | bsd-3-clause | 1,593 | 0 | 10 | 380 | 308 | 176 | 132 | 25 | 2 |
{-# LANGUAGE LambdaCase #-}
--
-- | Primitive argument safe copy propagation.
--
-- Copy propagation that doesn't touch the names of arguments to primitives.
-- This is useful because it can be applied after register allocation.
--
module River.Core.Transform.Copy (
copyOfProgram
, copyOfTerm
) where
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Set as Set
import River.Bifunctor
import River.Core.Syntax
import River.Map
import River.Progress
copyOfProgram :: (Ord n, MonadProgress m) => Program k p n a -> m (Program k p n a)
copyOfProgram = \case
Program a tm0 -> do
Program a <$> copyOfTerm Map.empty tm0
copyOfTerm ::
Ord n =>
MonadProgress m =>
Map n (Atom n a) ->
Term k p n a ->
m (Term k p n a)
copyOfTerm env0 = \case
Return a tl ->
pure $
Return a tl
If a k i t e ->
If a k i
<$> copyOfTerm env0 t
<*> copyOfTerm env0 e
Let a ns tl0 tm0 -> do
tl <- copyOfTail env0 tl0
let
env =
case tl of
Copy _ xs ->
Map.fromList (zip ns xs) `Map.union`
removeStaleBindings ns env0
Call _ _ _ ->
removeStaleBindings ns env0
Prim _ _ _ ->
removeStaleBindings ns env0
Let a ns tl <$> copyOfTerm env tm0
LetRec a bs tm ->
LetRec a
<$> copyOfBindings env0 bs
<*> copyOfTerm env0 tm
removeStaleBindings :: Ord n => [n] -> Map n (Atom n a) -> Map n (Atom n a)
removeStaleBindings ns env =
let
names =
Set.fromList ns
-- k is bound to one of the names which we are about to bind
bound k =
Set.member k names
-- v references one of the names which we are about to bind
references v =
case v of
Variable _ n ->
Set.member n names
Immediate _ _ ->
False
stale (k, v) =
bound k || references v
in
Map.filterWithKey (curry $ not . stale) env
copyOfTail ::
Ord n =>
MonadProgress m =>
Map n (Atom n a) ->
Tail p n a ->
m (Tail p n a)
copyOfTail env = \case
Copy a xs ->
Copy a <$> traverse (copyOfAtom env) xs
Call a n xs ->
Call a n <$> traverse (copyOfAtom env) xs
Prim a p xs ->
-- We can't change the names of arguments to primitives or this transform
-- can't be used after register allocation.
pure $
Prim a p xs
copyOfAtom ::
Ord n =>
MonadProgress m =>
Map n (Atom n a) ->
Atom n a ->
m (Atom n a)
copyOfAtom env = \case
Immediate a i ->
pure $ Immediate a i
Variable an n ->
case Map.lookup n env of
Nothing ->
pure $ Variable an n
-- TODO I think propagating constants at this stage could be detrimental
-- Just (Immediate _ _) ->
-- pure $ Variable an n
Just x ->
progress x
copyOfBindings ::
Ord n =>
MonadProgress m =>
Map n (Atom n a) ->
Bindings k p n a ->
m (Bindings k p n a)
copyOfBindings env0 = \case
Bindings a bs ->
let
env =
env0 `mapDifferenceList` fmap fst bs
in
Bindings a <$> traverse (secondA (copyOfBinding env)) bs
copyOfBinding ::
Ord n =>
MonadProgress m =>
Map n (Atom n a) ->
Binding k p n a ->
m (Binding k p n a)
copyOfBinding env0 = \case
Lambda a ns tm ->
let
env =
env0 `mapDifferenceList` ns
in
Lambda a ns <$> copyOfTerm env tm
| jystic/river | src/River/Core/Transform/Copy.hs | bsd-3-clause | 3,421 | 0 | 19 | 1,121 | 1,175 | 569 | 606 | -1 | -1 |
{-# LANGUAGE DeriveAnyClass, DeriveGeneric #-}
module Stan.AST.Pretty where
import Stan.AST
import Text.PrettyPrint.HughesPJClass
instance Pretty Stan where
pPrint (Model ds) = text "model {"
$$ nest 2 (ppDecls ds)
$$ char '}'
pPrint (Parameters ds)
= text "parameters {"
$$ nest 2 (ppDecls ds)
$$ char '}'
pPrint (TransformedParameters ds)
= text "transformed parameters {"
$$ nest 2 (ppDecls ds)
$$ char '}'
pPrint (Data ds) = text "data {"
$$ nest 2 (ppDecls ds)
$$ char '}'
pPrint (TransformedData ds)
= text "transformed data {"
$$ nest 2 (ppDecls ds)
$$ char '}'
pPrint (GeneratedQuantities ds)
= text "generated quantities {"
$$ nest 2 (ppDecls ds)
$$ char '}'
ppStans :: [Stan] -> String
ppStans = render . vcat . map pPrint
ppDecls :: [Decl] -> Doc
ppDecls = vcat . map ((<>(char ';')) . pPrint)
instance Pretty Decl where
pPrint (t ::: (nm, ixs)) = pPrint t <+> text nm <> mcommasepBrackets (map pPrint ixs)
pPrint ((nm,ixes) := e) = (text nm <> mcommasepBrackets (map pPrint ixes))
<+> text "=" <+> pPrint e
pPrint ((nm,ixes) :~ (dnm, es)) = (text nm <> mcommasepBrackets (map pPrint ixes))
<+> text "~" <+> text dnm <> parens (commasep (map pPrint es))
pPrint (For vnm elo ehi ds) = let range = pPrint elo <> char ':' <> pPrint ehi
in text "for" <+> parens (text vnm <+> text "in" <+> range) <+> char '{'
$$ nest 2 (ppDecls ds)
$$ char '}'
pPrint (Print s es) = text "print" <> parens (commasep $ text (show s) : map pPrint es)
instance Pretty Type where
pPrint Real = text "real"
pPrint Int = text "int"
pPrint (Bounded Nothing Nothing t) = pPrint t
pPrint (Bounded (Just e) Nothing t) = pPrint t <> angles ( ppLowerBound e)
pPrint (Bounded Nothing (Just e) t) = pPrint t <> angles ( ppUpperBound e)
pPrint (Bounded (Just e1) (Just e2) t) = pPrint t <> angles ( ppLowerBound e1 <> comma <> ppUpperBound e2)
ppLowerBound :: Expr -> Doc
ppLowerBound e = text "lower=" <> pPrint e
ppUpperBound :: Expr -> Doc
ppUpperBound e = text "upper=" <> pPrint e
angles :: Doc -> Doc
angles d = char '<' <> d <> char '>'
commasep :: [Doc] -> Doc
commasep = hcat . punctuate comma
mcommasepBrackets :: [Doc] -> Doc
mcommasepBrackets [] = empty
mcommasepBrackets ds = brackets $ commasep ds
instance Pretty Expr where
pPrintPrec _ _ (Var v) = text v
pPrintPrec _ _ (LitInt x) = int x
pPrintPrec _ _ (LitFloat x) = float x
pPrintPrec l r (Ix e es) = pPrintPrec l r e <> brackets (commasep (map (pPrintPrec l r) es))
pPrintPrec l r (BinOp s e1 e2)
= let prec = opPrec s
in maybeParens (r >= prec) $ pPrintPrec l prec e1 <> text s <> pPrintPrec l prec e2
pPrintPrec l r (Apply fnm es) = text fnm <> parens (commasep (map (pPrintPrec l r) es))
pp :: Pretty a => a -> String
pp = render . pPrint
opPrec :: String -> Rational
opPrec "+" = 6
opPrec "-" = 6
opPrec "*" = 7
opPrec "/" = 7
opPrec _ = 1
| filopodia/open | stanhs/lib/Stan/AST/Pretty.hs | mit | 3,372 | 0 | 16 | 1,111 | 1,340 | 652 | 688 | 77 | 1 |
{-
emacs2nix - Generate Nix expressions for Emacs packages
Copyright (C) 2016 Thomas Tuegel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE DeriveGeneric #-}
module Distribution.Elpa ( Elpa(..) ) where
import Data.Aeson ( FromJSON(..), ToJSON(..) )
import Data.Map.Strict ( Map )
import Data.Text ( Text )
import GHC.Generics
data Elpa =
Elpa
{ ver :: [Integer]
, deps :: Maybe (Map Text [Integer])
, dist :: Text -- TODO: replace with an enumeration
, broken :: Maybe Bool
}
deriving (Eq, Generic, Read, Show)
instance FromJSON Elpa
instance ToJSON Elpa
| mdorman/emacs2nix | src/Distribution/Elpa.hs | gpl-3.0 | 1,157 | 0 | 12 | 210 | 151 | 90 | 61 | 15 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- Module : Test.AWS.ElastiCache
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Test.AWS.ElastiCache
( tests
, fixtures
) where
import Network.AWS.ElastiCache
import Test.AWS.Gen.ElastiCache
import Test.Tasty
tests :: [TestTree]
tests = []
fixtures :: [TestTree]
fixtures = []
| fmapfmapfmap/amazonka | amazonka-elasticache/test/Test/AWS/ElastiCache.hs | mpl-2.0 | 756 | 0 | 5 | 201 | 73 | 50 | 23 | 11 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CodeDeploy.ListApplications
-- 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)
--
-- Lists the applications registered with the applicable IAM user or AWS
-- account.
--
-- /See:/ <http://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListApplications.html AWS API Reference> for ListApplications.
module Network.AWS.CodeDeploy.ListApplications
(
-- * Creating a Request
listApplications
, ListApplications
-- * Request Lenses
, laNextToken
-- * Destructuring the Response
, listApplicationsResponse
, ListApplicationsResponse
-- * Response Lenses
, larsNextToken
, larsApplications
, larsResponseStatus
) where
import Network.AWS.CodeDeploy.Types
import Network.AWS.CodeDeploy.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Represents the input of a list applications operation.
--
-- /See:/ 'listApplications' smart constructor.
newtype ListApplications = ListApplications'
{ _laNextToken :: Maybe Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListApplications' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'laNextToken'
listApplications
:: ListApplications
listApplications =
ListApplications'
{ _laNextToken = Nothing
}
-- | An identifier that was returned from the previous list applications
-- call, which can be used to return the next set of applications in the
-- list.
laNextToken :: Lens' ListApplications (Maybe Text)
laNextToken = lens _laNextToken (\ s a -> s{_laNextToken = a});
instance AWSRequest ListApplications where
type Rs ListApplications = ListApplicationsResponse
request = postJSON codeDeploy
response
= receiveJSON
(\ s h x ->
ListApplicationsResponse' <$>
(x .?> "nextToken") <*>
(x .?> "applications" .!@ mempty)
<*> (pure (fromEnum s)))
instance ToHeaders ListApplications where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("CodeDeploy_20141006.ListApplications" ::
ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON ListApplications where
toJSON ListApplications'{..}
= object
(catMaybes [("nextToken" .=) <$> _laNextToken])
instance ToPath ListApplications where
toPath = const "/"
instance ToQuery ListApplications where
toQuery = const mempty
-- | Represents the output of a list applications operation.
--
-- /See:/ 'listApplicationsResponse' smart constructor.
data ListApplicationsResponse = ListApplicationsResponse'
{ _larsNextToken :: !(Maybe Text)
, _larsApplications :: !(Maybe [Text])
, _larsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListApplicationsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'larsNextToken'
--
-- * 'larsApplications'
--
-- * 'larsResponseStatus'
listApplicationsResponse
:: Int -- ^ 'larsResponseStatus'
-> ListApplicationsResponse
listApplicationsResponse pResponseStatus_ =
ListApplicationsResponse'
{ _larsNextToken = Nothing
, _larsApplications = Nothing
, _larsResponseStatus = pResponseStatus_
}
-- | If the amount of information that is returned is significantly large, an
-- identifier will also be returned, which can be used in a subsequent list
-- applications call to return the next set of applications in the list.
larsNextToken :: Lens' ListApplicationsResponse (Maybe Text)
larsNextToken = lens _larsNextToken (\ s a -> s{_larsNextToken = a});
-- | A list of application names.
larsApplications :: Lens' ListApplicationsResponse [Text]
larsApplications = lens _larsApplications (\ s a -> s{_larsApplications = a}) . _Default . _Coerce;
-- | The response status code.
larsResponseStatus :: Lens' ListApplicationsResponse Int
larsResponseStatus = lens _larsResponseStatus (\ s a -> s{_larsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-codedeploy/gen/Network/AWS/CodeDeploy/ListApplications.hs | mpl-2.0 | 4,966 | 0 | 13 | 1,100 | 679 | 407 | 272 | 85 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.DescribeRegions
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes one or more regions that are currently available to you.
--
-- For a list of the regions supported by Amazon EC2, see <http://docs.aws.amazon.com/general/latest/gr/rande.html#ec2_region Regions and Endpoints>.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeRegions.html>
module Network.AWS.EC2.DescribeRegions
(
-- * Request
DescribeRegions
-- ** Request constructor
, describeRegions
-- ** Request lenses
, dr1DryRun
, dr1Filters
, dr1RegionNames
-- * Response
, DescribeRegionsResponse
-- ** Response constructor
, describeRegionsResponse
-- ** Response lenses
, drrRegions
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data DescribeRegions = DescribeRegions
{ _dr1DryRun :: Maybe Bool
, _dr1Filters :: List "Filter" Filter
, _dr1RegionNames :: List "RegionName" Text
} deriving (Eq, Read, Show)
-- | 'DescribeRegions' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dr1DryRun' @::@ 'Maybe' 'Bool'
--
-- * 'dr1Filters' @::@ ['Filter']
--
-- * 'dr1RegionNames' @::@ ['Text']
--
describeRegions :: DescribeRegions
describeRegions = DescribeRegions
{ _dr1DryRun = Nothing
, _dr1RegionNames = mempty
, _dr1Filters = mempty
}
dr1DryRun :: Lens' DescribeRegions (Maybe Bool)
dr1DryRun = lens _dr1DryRun (\s a -> s { _dr1DryRun = a })
-- | One or more filters.
--
-- 'endpoint' - The endpoint of the region (for example, 'ec2.us-east-1.amazonaws.com').
--
-- 'region-name' - The name of the region (for example, 'us-east-1').
--
--
dr1Filters :: Lens' DescribeRegions [Filter]
dr1Filters = lens _dr1Filters (\s a -> s { _dr1Filters = a }) . _List
-- | The names of one or more regions.
dr1RegionNames :: Lens' DescribeRegions [Text]
dr1RegionNames = lens _dr1RegionNames (\s a -> s { _dr1RegionNames = a }) . _List
newtype DescribeRegionsResponse = DescribeRegionsResponse
{ _drrRegions :: List "item" Region
} deriving (Eq, Read, Show, Monoid, Semigroup)
-- | 'DescribeRegionsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'drrRegions' @::@ ['Region']
--
describeRegionsResponse :: DescribeRegionsResponse
describeRegionsResponse = DescribeRegionsResponse
{ _drrRegions = mempty
}
-- | Information about one or more regions.
drrRegions :: Lens' DescribeRegionsResponse [Region]
drrRegions = lens _drrRegions (\s a -> s { _drrRegions = a }) . _List
instance ToPath DescribeRegions where
toPath = const "/"
instance ToQuery DescribeRegions where
toQuery DescribeRegions{..} = mconcat
[ "DryRun" =? _dr1DryRun
, "Filter" `toQueryList` _dr1Filters
, "RegionName" `toQueryList` _dr1RegionNames
]
instance ToHeaders DescribeRegions
instance AWSRequest DescribeRegions where
type Sv DescribeRegions = EC2
type Rs DescribeRegions = DescribeRegionsResponse
request = post "DescribeRegions"
response = xmlResponse
instance FromXML DescribeRegionsResponse where
parseXML x = DescribeRegionsResponse
<$> x .@? "regionInfo" .!@ mempty
| kim/amazonka | amazonka-ec2/gen/Network/AWS/EC2/DescribeRegions.hs | mpl-2.0 | 4,290 | 0 | 10 | 916 | 580 | 354 | 226 | 64 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-| Implementation of the Ganeti LUXI interface.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Luxi
( LuxiOp(..)
, LuxiReq(..)
, Client
, Server
, JobId
, fromJobId
, makeJobId
, RecvResult(..)
, strOfOp
, opToArgs
, getLuxiClient
, getLuxiServer
, acceptClient
, closeClient
, closeServer
, callMethod
, submitManyJobs
, queryJobsStatus
, buildCall
, buildResponse
, decodeLuxiCall
, recvMsg
, recvMsgExt
, sendMsg
, allLuxiCalls
, extractArray
, fromJValWithStatus
) where
import Control.Applicative (optional, liftA, (<|>))
import Control.Monad
import qualified Text.JSON as J
import Text.JSON.Pretty (pp_value)
import Text.JSON.Types
import Ganeti.BasicTypes
import Ganeti.Constants
import Ganeti.Errors
import Ganeti.JSON (fromJResult, fromJVal, fromObj, Tuple5(..), MaybeForJSON(..), TimeAsDoubleJSON(..))
import Ganeti.UDSServer
import Ganeti.Objects
import Ganeti.OpParams (pTagsObject)
import Ganeti.OpCodes
import qualified Ganeti.Query.Language as Qlang
import Ganeti.Runtime (GanetiDaemon(..), GanetiGroup(..), MiscGroup(..))
import Ganeti.THH
import Ganeti.THH.Field
import Ganeti.THH.Types (getOneTuple)
import Ganeti.Types
import Ganeti.Utils
-- | Currently supported Luxi operations and JSON serialization.
$(genLuxiOp "LuxiOp"
[ (luxiReqQuery,
[ simpleField "what" [t| Qlang.ItemType |]
, simpleField "fields" [t| [String] |]
, simpleField "qfilter" [t| Qlang.Filter Qlang.FilterField |]
])
, (luxiReqQueryFields,
[ simpleField "what" [t| Qlang.ItemType |]
, simpleField "fields" [t| [String] |]
])
, (luxiReqQueryNodes,
[ simpleField "names" [t| [String] |]
, simpleField "fields" [t| [String] |]
, simpleField "lock" [t| Bool |]
])
, (luxiReqQueryGroups,
[ simpleField "names" [t| [String] |]
, simpleField "fields" [t| [String] |]
, simpleField "lock" [t| Bool |]
])
, (luxiReqQueryNetworks,
[ simpleField "names" [t| [String] |]
, simpleField "fields" [t| [String] |]
, simpleField "lock" [t| Bool |]
])
, (luxiReqQueryInstances,
[ simpleField "names" [t| [String] |]
, simpleField "fields" [t| [String] |]
, simpleField "lock" [t| Bool |]
])
, (luxiReqQueryFilters,
[ simpleField "uuids" [t| [String] |]
, simpleField "fields" [t| [String] |]
])
, (luxiReqReplaceFilter,
-- UUID is missing for insert, present for upsert
[ optionalNullSerField
$ simpleField "uuid" [t| String |]
, simpleField "priority" [t| NonNegative Int |]
, simpleField "predicates" [t| [FilterPredicate] |]
, simpleField "action" [t| FilterAction |]
, simpleField "reason" [t| ReasonTrail |]
])
, (luxiReqDeleteFilter,
[ simpleField "uuid" [t| String |]
])
, (luxiReqQueryJobs,
[ simpleField "ids" [t| [JobId] |]
, simpleField "fields" [t| [String] |]
])
, (luxiReqQueryExports,
[ simpleField "nodes" [t| [String] |]
, simpleField "lock" [t| Bool |]
])
, (luxiReqQueryConfigValues,
[ simpleField "fields" [t| [String] |] ]
)
, (luxiReqQueryClusterInfo, [])
, (luxiReqQueryTags,
[ pTagsObject
, simpleField "name" [t| String |]
])
, (luxiReqSubmitJob,
[ simpleField "job" [t| [MetaOpCode] |] ]
)
, (luxiReqSubmitJobToDrainedQueue,
[ simpleField "job" [t| [MetaOpCode] |] ]
)
, (luxiReqSubmitManyJobs,
[ simpleField "ops" [t| [[MetaOpCode]] |] ]
)
, (luxiReqWaitForJobChange,
[ simpleField "job" [t| JobId |]
, simpleField "fields" [t| [String]|]
, simpleField "prev_job" [t| JSValue |]
, simpleField "prev_log" [t| JSValue |]
, simpleField "tmout" [t| Int |]
])
, (luxiReqPickupJob,
[ simpleField "job" [t| JobId |] ]
)
, (luxiReqArchiveJob,
[ simpleField "job" [t| JobId |] ]
)
, (luxiReqAutoArchiveJobs,
[ simpleField "age" [t| Int |]
, simpleField "tmout" [t| Int |]
])
, (luxiReqCancelJob,
[ simpleField "job" [t| JobId |]
, simpleField "kill" [t| Bool |]
])
, (luxiReqChangeJobPriority,
[ simpleField "job" [t| JobId |]
, simpleField "priority" [t| Int |] ]
)
, (luxiReqSetDrainFlag,
[ simpleField "flag" [t| Bool |] ]
)
, (luxiReqSetWatcherPause,
[ optionalNullSerField
$ timeAsDoubleField "duration" ]
)
])
$(makeJSONInstance ''LuxiReq)
-- | List of all defined Luxi calls.
$(genAllConstr (drop 3) ''LuxiReq "allLuxiCalls")
-- | The serialisation of LuxiOps into strings in messages.
$(genStrOfOp ''LuxiOp "strOfOp")
luxiConnectConfig :: ServerConfig
luxiConnectConfig = ServerConfig
-- The rapi daemon talks to the luxi one, and for this
-- purpose we need group rw permissions.
FilePermissions { fpOwner = Just GanetiLuxid
, fpGroup = Just $ ExtraGroup DaemonsGroup
, fpPermissions = 0o0660
}
ConnectConfig { recvTmo = luxiDefRwto
, sendTmo = luxiDefRwto
}
-- | Connects to the master daemon and returns a luxi Client.
getLuxiClient :: String -> IO Client
getLuxiClient = connectClient (connConfig luxiConnectConfig) luxiDefCtmo
-- | Creates and returns a server endpoint.
getLuxiServer :: Bool -> FilePath -> IO Server
getLuxiServer = connectServer luxiConnectConfig
-- | Converts Luxi call arguments into a 'LuxiOp' data structure.
-- This is used for building a Luxi 'Handler'.
--
-- This is currently hand-coded until we make it more uniform so that
-- it can be generated using TH.
decodeLuxiCall :: JSValue -> JSValue -> Result LuxiOp
decodeLuxiCall method args = do
call <- fromJResult "Unable to parse LUXI request method" $ J.readJSON method
case call of
ReqQueryFilters -> do
(uuids, fields) <- fromJVal args
uuids' <- case uuids of
JSNull -> return []
_ -> fromJVal uuids
return $ QueryFilters uuids' fields
ReqReplaceFilter -> do
Tuple5 ( uuid
, priority
, predicates
, action
, reason) <- fromJVal args
return $
ReplaceFilter (unMaybeForJSON uuid) priority predicates
action reason
ReqDeleteFilter -> do
[uuid] <- fromJVal args
return $ DeleteFilter uuid
ReqQueryJobs -> do
(jids, jargs) <- fromJVal args
jids' <- case jids of
JSNull -> return []
_ -> fromJVal jids
return $ QueryJobs jids' jargs
ReqQueryInstances -> do
(names, fields, locking) <- fromJVal args
return $ QueryInstances names fields locking
ReqQueryNodes -> do
(names, fields, locking) <- fromJVal args
return $ QueryNodes names fields locking
ReqQueryGroups -> do
(names, fields, locking) <- fromJVal args
return $ QueryGroups names fields locking
ReqQueryClusterInfo ->
return QueryClusterInfo
ReqQueryNetworks -> do
(names, fields, locking) <- fromJVal args
return $ QueryNetworks names fields locking
ReqQuery -> do
(what, fields, qfilter) <- fromJVal args
return $ Query what fields qfilter
ReqQueryFields -> do
(what, fields) <- fromJVal args
fields' <- case fields of
JSNull -> return []
_ -> fromJVal fields
return $ QueryFields what fields'
ReqSubmitJob -> do
[ops1] <- fromJVal args
ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1
return $ SubmitJob ops2
ReqSubmitJobToDrainedQueue -> do
[ops1] <- fromJVal args
ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1
return $ SubmitJobToDrainedQueue ops2
ReqSubmitManyJobs -> do
[ops1] <- fromJVal args
ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1
return $ SubmitManyJobs ops2
ReqWaitForJobChange -> do
(jid, fields, pinfo, pidx, wtmout) <-
-- No instance for 5-tuple, code copied from the
-- json sources and adapted
fromJResult "Parsing WaitForJobChange message" $
case args of
JSArray [a, b, c, d, e] ->
(,,,,) `fmap`
J.readJSON a `ap`
J.readJSON b `ap`
J.readJSON c `ap`
J.readJSON d `ap`
J.readJSON e
_ -> J.Error "Not enough values"
return $ WaitForJobChange jid fields pinfo pidx wtmout
ReqPickupJob -> do
[jid] <- fromJVal args
return $ PickupJob jid
ReqArchiveJob -> do
[jid] <- fromJVal args
return $ ArchiveJob jid
ReqAutoArchiveJobs -> do
(age, tmout) <- fromJVal args
return $ AutoArchiveJobs age tmout
ReqQueryExports -> do
(nodes, lock) <- fromJVal args
return $ QueryExports nodes lock
ReqQueryConfigValues -> do
[fields] <- fromJVal args
return $ QueryConfigValues fields
ReqQueryTags -> do
(kind, name) <- fromJVal args
return $ QueryTags kind name
ReqCancelJob -> do
(jid, kill) <- fromJVal args
<|> liftA (flip (,) False . getOneTuple)
(fromJVal args)
return $ CancelJob jid kill
ReqChangeJobPriority -> do
(jid, priority) <- fromJVal args
return $ ChangeJobPriority jid priority
ReqSetDrainFlag -> do
[flag] <- fromJVal args
return $ SetDrainFlag flag
ReqSetWatcherPause -> do
duration <- optional $ do
[x] <- fromJVal args
liftM unTimeAsDoubleJSON $ fromJVal x
return $ SetWatcherPause duration
-- | Generic luxi method call
callMethod :: LuxiOp -> Client -> IO (ErrorResult JSValue)
callMethod method s = do
sendMsg s $ buildCall (strOfOp method) (opToArgs method)
result <- recvMsg s
return $ parseResponse result
-- | Parse job submission result.
parseSubmitJobResult :: JSValue -> ErrorResult JobId
parseSubmitJobResult (JSArray [JSBool True, v]) =
case J.readJSON v of
J.Error msg -> Bad $ LuxiError msg
J.Ok v' -> Ok v'
parseSubmitJobResult (JSArray [JSBool False, JSString x]) =
Bad . LuxiError $ fromJSString x
parseSubmitJobResult v =
Bad . LuxiError $ "Unknown result from the master daemon: " ++
show (pp_value v)
-- | Specialized submitManyJobs call.
submitManyJobs :: Client -> [[MetaOpCode]] -> IO (ErrorResult [JobId])
submitManyJobs s jobs = do
rval <- callMethod (SubmitManyJobs jobs) s
-- map each result (status, payload) pair into a nice Result ADT
return $ case rval of
Bad x -> Bad x
Ok (JSArray r) -> mapM parseSubmitJobResult r
x -> Bad . LuxiError $
"Cannot parse response from Ganeti: " ++ show x
-- | Custom queryJobs call.
queryJobsStatus :: Client -> [JobId] -> IO (ErrorResult [JobStatus])
queryJobsStatus s jids = do
rval <- callMethod (QueryJobs jids ["status"]) s
return $ case rval of
Bad x -> Bad x
Ok y -> case J.readJSON y::(J.Result [[JobStatus]]) of
J.Ok vals -> if any null vals
then Bad $
LuxiError "Missing job status field"
else Ok (map head vals)
J.Error x -> Bad $ LuxiError x
-- * Utility functions
-- | Get values behind \"data\" part of the result.
getData :: (Monad m) => JSValue -> m JSValue
getData (JSObject o) = fromObj (fromJSObject o) "data"
getData x = fail $ "Invalid input, expected dict entry but got " ++ show x
-- | Converts a (status, value) into m value, if possible.
parseQueryField :: (Monad m) => JSValue -> m (JSValue, JSValue)
parseQueryField (JSArray [status, result]) = return (status, result)
parseQueryField o =
fail $ "Invalid query field, expected (status, value) but got " ++ show o
-- | Parse a result row.
parseQueryRow :: (Monad m) => JSValue -> m [(JSValue, JSValue)]
parseQueryRow (JSArray arr) = mapM parseQueryField arr
parseQueryRow o =
fail $ "Invalid query row result, expected array but got " ++ show o
-- | Parse an overall query result and get the [(status, value)] list
-- for each element queried.
parseQueryResult :: (Monad m) => JSValue -> m [[(JSValue, JSValue)]]
parseQueryResult (JSArray arr) = mapM parseQueryRow arr
parseQueryResult o =
fail $ "Invalid query result, expected array but got " ++ show o
-- | Prepare resulting output as parsers expect it.
extractArray :: (Monad m) => JSValue -> m [[(JSValue, JSValue)]]
extractArray v =
getData v >>= parseQueryResult
-- | Testing result status for more verbose error message.
fromJValWithStatus :: (J.JSON a, Monad m) => (JSValue, JSValue) -> m a
fromJValWithStatus (st, v) = do
st' <- fromJVal st
Qlang.checkRS st' v >>= fromJVal
| onponomarev/ganeti | src/Ganeti/Luxi.hs | bsd-2-clause | 15,089 | 0 | 23 | 4,556 | 3,477 | 1,902 | 1,575 | 307 | 29 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Dependency
-- Copyright : (c) David Himmelstrup 2005,
-- Bjorn Bringert 2007
-- Duncan Coutts 2008
-- License : BSD-like
--
-- Maintainer : cabal-devel@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Top level interface to dependency resolution.
-----------------------------------------------------------------------------
module Distribution.Client.Dependency (
-- * The main package dependency resolver
chooseSolver,
resolveDependencies,
Progress(..),
foldProgress,
-- * Alternate, simple resolver that does not do dependencies recursively
resolveWithoutDependencies,
-- * Constructing resolver policies
DepResolverParams(..),
PackageConstraint(..),
PackagesPreferenceDefault(..),
PackagePreference(..),
InstalledPreference(..),
-- ** Standard policy
standardInstallPolicy,
PackageSpecifier(..),
-- ** Sandbox policy
applySandboxInstallPolicy,
-- ** Extra policy options
dontUpgradeNonUpgradeablePackages,
hideBrokenInstalledPackages,
upgradeDependencies,
reinstallTargets,
-- ** Policy utils
addConstraints,
addPreferences,
setPreferenceDefault,
setReorderGoals,
setIndependentGoals,
setAvoidReinstalls,
setShadowPkgs,
setStrongFlags,
setMaxBackjumps,
addSourcePackages,
hideInstalledPackagesSpecificByComponentId,
hideInstalledPackagesSpecificBySourcePackageId,
hideInstalledPackagesAllVersions,
removeUpperBounds
) where
import Distribution.Client.Dependency.TopDown
( topDownResolver )
import Distribution.Client.Dependency.Modular
( modularResolver, SolverConfig(..) )
import qualified Distribution.Client.PackageIndex as PackageIndex
import Distribution.Simple.PackageIndex (InstalledPackageIndex)
import qualified Distribution.Simple.PackageIndex as InstalledPackageIndex
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Client.InstallPlan (InstallPlan)
import Distribution.Client.Types
( SourcePackageDb(SourcePackageDb), SourcePackage(..)
, ConfiguredPackage(..), ConfiguredId(..), enableStanzas )
import Distribution.Client.Dependency.Types
( PreSolver(..), Solver(..), DependencyResolver, ResolverPackage(..)
, PackageConstraint(..), showPackageConstraint
, LabeledPackageConstraint(..), unlabelPackageConstraint
, ConstraintSource(..), showConstraintSource
, AllowNewer(..), PackagePreferences(..), InstalledPreference(..)
, PackagesPreferenceDefault(..)
, Progress(..), foldProgress )
import Distribution.Client.Sandbox.Types
( SandboxPackageInfo(..) )
import Distribution.Client.Targets
import Distribution.Client.ComponentDeps (ComponentDeps)
import qualified Distribution.Client.ComponentDeps as CD
import qualified Distribution.InstalledPackageInfo as Installed
import Distribution.Package
( PackageName(..), PackageIdentifier(PackageIdentifier), PackageId
, Package(..), packageName, packageVersion
, ComponentId, Dependency(Dependency))
import qualified Distribution.PackageDescription as PD
( PackageDescription(..), Library(..), Executable(..)
, TestSuite(..), Benchmark(..), SetupBuildInfo(..)
, GenericPackageDescription(..), CondTree
, Flag(flagName), FlagName(..) )
import Distribution.PackageDescription (BuildInfo(targetBuildDepends))
import Distribution.PackageDescription.Configuration
( mapCondTree, finalizePackageDescription )
import Distribution.Client.PackageUtils
( externalBuildDepends )
import Distribution.Version
( VersionRange, anyVersion, thisVersion, withinRange
, removeUpperBound, simplifyVersionRange )
import Distribution.Compiler
( CompilerInfo(..) )
import Distribution.System
( Platform )
import Distribution.Client.Utils
( duplicates, duplicatesBy, mergeBy, MergeResult(..) )
import Distribution.Simple.Utils
( comparing, warn, info )
import Distribution.Text
( display )
import Distribution.Verbosity
( Verbosity )
import Data.List
( foldl', sort, sortBy, nubBy, maximumBy, intercalate )
import Data.Function (on)
import Data.Maybe (fromMaybe)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Set (Set)
import Control.Exception
( assert )
-- ------------------------------------------------------------
-- * High level planner policy
-- ------------------------------------------------------------
-- | The set of parameters to the dependency resolver. These parameters are
-- relatively low level but many kinds of high level policies can be
-- implemented in terms of adjustments to the parameters.
--
data DepResolverParams = DepResolverParams {
depResolverTargets :: [PackageName],
depResolverConstraints :: [LabeledPackageConstraint],
depResolverPreferences :: [PackagePreference],
depResolverPreferenceDefault :: PackagesPreferenceDefault,
depResolverInstalledPkgIndex :: InstalledPackageIndex,
depResolverSourcePkgIndex :: PackageIndex.PackageIndex SourcePackage,
depResolverReorderGoals :: Bool,
depResolverIndependentGoals :: Bool,
depResolverAvoidReinstalls :: Bool,
depResolverShadowPkgs :: Bool,
depResolverStrongFlags :: Bool,
depResolverMaxBackjumps :: Maybe Int
}
showDepResolverParams :: DepResolverParams -> String
showDepResolverParams p =
"targets: " ++ intercalate ", " (map display (depResolverTargets p))
++ "\nconstraints: "
++ concatMap (("\n " ++) . showLabeledConstraint)
(depResolverConstraints p)
++ "\npreferences: "
++ concatMap (("\n " ++) . showPackagePreference)
(depResolverPreferences p)
++ "\nstrategy: " ++ show (depResolverPreferenceDefault p)
where
showLabeledConstraint :: LabeledPackageConstraint -> String
showLabeledConstraint (LabeledPackageConstraint pc src) =
showPackageConstraint pc ++ " (" ++ showConstraintSource src ++ ")"
-- | A package selection preference for a particular package.
--
-- Preferences are soft constraints that the dependency resolver should try to
-- respect where possible. It is not specified if preferences on some packages
-- are more important than others.
--
data PackagePreference =
-- | A suggested constraint on the version number.
PackageVersionPreference PackageName VersionRange
-- | If we prefer versions of packages that are already installed.
| PackageInstalledPreference PackageName InstalledPreference
-- | Provide a textual representation of a package preference
-- for debugging purposes.
--
showPackagePreference :: PackagePreference -> String
showPackagePreference (PackageVersionPreference pn vr) =
display pn ++ " " ++ display (simplifyVersionRange vr)
showPackagePreference (PackageInstalledPreference pn ip) =
display pn ++ " " ++ show ip
basicDepResolverParams :: InstalledPackageIndex
-> PackageIndex.PackageIndex SourcePackage
-> DepResolverParams
basicDepResolverParams installedPkgIndex sourcePkgIndex =
DepResolverParams {
depResolverTargets = [],
depResolverConstraints = [],
depResolverPreferences = [],
depResolverPreferenceDefault = PreferLatestForSelected,
depResolverInstalledPkgIndex = installedPkgIndex,
depResolverSourcePkgIndex = sourcePkgIndex,
depResolverReorderGoals = False,
depResolverIndependentGoals = False,
depResolverAvoidReinstalls = False,
depResolverShadowPkgs = False,
depResolverStrongFlags = False,
depResolverMaxBackjumps = Nothing
}
addTargets :: [PackageName]
-> DepResolverParams -> DepResolverParams
addTargets extraTargets params =
params {
depResolverTargets = extraTargets ++ depResolverTargets params
}
addConstraints :: [LabeledPackageConstraint]
-> DepResolverParams -> DepResolverParams
addConstraints extraConstraints params =
params {
depResolverConstraints = extraConstraints
++ depResolverConstraints params
}
addPreferences :: [PackagePreference]
-> DepResolverParams -> DepResolverParams
addPreferences extraPreferences params =
params {
depResolverPreferences = extraPreferences
++ depResolverPreferences params
}
setPreferenceDefault :: PackagesPreferenceDefault
-> DepResolverParams -> DepResolverParams
setPreferenceDefault preferenceDefault params =
params {
depResolverPreferenceDefault = preferenceDefault
}
setReorderGoals :: Bool -> DepResolverParams -> DepResolverParams
setReorderGoals b params =
params {
depResolverReorderGoals = b
}
setIndependentGoals :: Bool -> DepResolverParams -> DepResolverParams
setIndependentGoals b params =
params {
depResolverIndependentGoals = b
}
setAvoidReinstalls :: Bool -> DepResolverParams -> DepResolverParams
setAvoidReinstalls b params =
params {
depResolverAvoidReinstalls = b
}
setShadowPkgs :: Bool -> DepResolverParams -> DepResolverParams
setShadowPkgs b params =
params {
depResolverShadowPkgs = b
}
setStrongFlags :: Bool -> DepResolverParams -> DepResolverParams
setStrongFlags b params =
params {
depResolverStrongFlags = b
}
setMaxBackjumps :: Maybe Int -> DepResolverParams -> DepResolverParams
setMaxBackjumps n params =
params {
depResolverMaxBackjumps = n
}
-- | Some packages are specific to a given compiler version and should never be
-- upgraded.
dontUpgradeNonUpgradeablePackages :: DepResolverParams -> DepResolverParams
dontUpgradeNonUpgradeablePackages params =
addConstraints extraConstraints params
where
extraConstraints =
[ LabeledPackageConstraint
(PackageConstraintInstalled pkgname)
ConstraintSourceNonUpgradeablePackage
| notElem (PackageName "base") (depResolverTargets params)
, pkgname <- map PackageName [ "base", "ghc-prim", "integer-gmp"
, "integer-simple" ]
, isInstalled pkgname ]
-- TODO: the top down resolver chokes on the base constraints
-- below when there are no targets and thus no dep on base.
-- Need to refactor constraints separate from needing packages.
isInstalled = not . null
. InstalledPackageIndex.lookupPackageName
(depResolverInstalledPkgIndex params)
addSourcePackages :: [SourcePackage]
-> DepResolverParams -> DepResolverParams
addSourcePackages pkgs params =
params {
depResolverSourcePkgIndex =
foldl (flip PackageIndex.insert)
(depResolverSourcePkgIndex params) pkgs
}
hideInstalledPackagesSpecificByComponentId :: [ComponentId]
-> DepResolverParams
-> DepResolverParams
hideInstalledPackagesSpecificByComponentId pkgids params =
--TODO: this should work using exclude constraints instead
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deleteComponentId)
(depResolverInstalledPkgIndex params) pkgids
}
hideInstalledPackagesSpecificBySourcePackageId :: [PackageId]
-> DepResolverParams
-> DepResolverParams
hideInstalledPackagesSpecificBySourcePackageId pkgids params =
--TODO: this should work using exclude constraints instead
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deleteSourcePackageId)
(depResolverInstalledPkgIndex params) pkgids
}
hideInstalledPackagesAllVersions :: [PackageName]
-> DepResolverParams -> DepResolverParams
hideInstalledPackagesAllVersions pkgnames params =
--TODO: this should work using exclude constraints instead
params {
depResolverInstalledPkgIndex =
foldl' (flip InstalledPackageIndex.deletePackageName)
(depResolverInstalledPkgIndex params) pkgnames
}
hideBrokenInstalledPackages :: DepResolverParams -> DepResolverParams
hideBrokenInstalledPackages params =
hideInstalledPackagesSpecificByComponentId pkgids params
where
pkgids = map Installed.installedComponentId
. InstalledPackageIndex.reverseDependencyClosure
(depResolverInstalledPkgIndex params)
. map (Installed.installedComponentId . fst)
. InstalledPackageIndex.brokenPackages
$ depResolverInstalledPkgIndex params
-- | Remove upper bounds in dependencies using the policy specified by the
-- 'AllowNewer' argument (all/some/none).
removeUpperBounds :: AllowNewer -> DepResolverParams -> DepResolverParams
removeUpperBounds allowNewer params =
params {
-- NB: It's important to apply 'removeUpperBounds' after
-- 'addSourcePackages'. Otherwise, the packages inserted by
-- 'addSourcePackages' won't have upper bounds in dependencies relaxed.
depResolverSourcePkgIndex = sourcePkgIndex'
}
where
sourcePkgIndex = depResolverSourcePkgIndex params
sourcePkgIndex' = case allowNewer of
AllowNewerNone -> sourcePkgIndex
AllowNewerAll -> fmap relaxAllPackageDeps sourcePkgIndex
AllowNewerSome pkgs -> fmap (relaxSomePackageDeps pkgs) sourcePkgIndex
relaxAllPackageDeps :: SourcePackage -> SourcePackage
relaxAllPackageDeps = onAllBuildDepends doRelax
where
doRelax (Dependency pkgName verRange) =
Dependency pkgName (removeUpperBound verRange)
relaxSomePackageDeps :: [PackageName] -> SourcePackage -> SourcePackage
relaxSomePackageDeps pkgNames = onAllBuildDepends doRelax
where
doRelax d@(Dependency pkgName verRange)
| pkgName `elem` pkgNames = Dependency pkgName
(removeUpperBound verRange)
| otherwise = d
-- Walk a 'GenericPackageDescription' and apply 'f' to all 'build-depends'
-- fields.
onAllBuildDepends :: (Dependency -> Dependency)
-> SourcePackage -> SourcePackage
onAllBuildDepends f srcPkg = srcPkg'
where
gpd = packageDescription srcPkg
pd = PD.packageDescription gpd
condLib = PD.condLibrary gpd
condExes = PD.condExecutables gpd
condTests = PD.condTestSuites gpd
condBenchs = PD.condBenchmarks gpd
f' = onBuildInfo f
onBuildInfo g bi = bi
{ targetBuildDepends = map g (targetBuildDepends bi) }
onLibrary lib = lib { PD.libBuildInfo = f' $ PD.libBuildInfo lib }
onExecutable exe = exe { PD.buildInfo = f' $ PD.buildInfo exe }
onTestSuite tst = tst { PD.testBuildInfo = f' $ PD.testBuildInfo tst }
onBenchmark bmk = bmk { PD.benchmarkBuildInfo =
f' $ PD.benchmarkBuildInfo bmk }
srcPkg' = srcPkg { packageDescription = gpd' }
gpd' = gpd {
PD.packageDescription = pd',
PD.condLibrary = condLib',
PD.condExecutables = condExes',
PD.condTestSuites = condTests',
PD.condBenchmarks = condBenchs'
}
pd' = pd {
PD.buildDepends = map f (PD.buildDepends pd),
PD.library = fmap onLibrary (PD.library pd),
PD.executables = map onExecutable (PD.executables pd),
PD.testSuites = map onTestSuite (PD.testSuites pd),
PD.benchmarks = map onBenchmark (PD.benchmarks pd)
}
condLib' = fmap (onCondTree onLibrary) condLib
condExes' = map (mapSnd $ onCondTree onExecutable) condExes
condTests' = map (mapSnd $ onCondTree onTestSuite) condTests
condBenchs' = map (mapSnd $ onCondTree onBenchmark) condBenchs
mapSnd :: (a -> b) -> (c,a) -> (c,b)
mapSnd = fmap
onCondTree :: (a -> b) -> PD.CondTree v [Dependency] a
-> PD.CondTree v [Dependency] b
onCondTree g = mapCondTree g (map f) id
upgradeDependencies :: DepResolverParams -> DepResolverParams
upgradeDependencies = setPreferenceDefault PreferAllLatest
reinstallTargets :: DepResolverParams -> DepResolverParams
reinstallTargets params =
hideInstalledPackagesAllVersions (depResolverTargets params) params
standardInstallPolicy :: InstalledPackageIndex
-> SourcePackageDb
-> [PackageSpecifier SourcePackage]
-> DepResolverParams
standardInstallPolicy
installedPkgIndex (SourcePackageDb sourcePkgIndex sourcePkgPrefs)
pkgSpecifiers
= addPreferences
[ PackageVersionPreference name ver
| (name, ver) <- Map.toList sourcePkgPrefs ]
. addConstraints
(concatMap pkgSpecifierConstraints pkgSpecifiers)
. addTargets
(map pkgSpecifierTarget pkgSpecifiers)
. hideInstalledPackagesSpecificBySourcePackageId
[ packageId pkg | SpecificSourcePackage pkg <- pkgSpecifiers ]
. addSourcePackages
[ pkg | SpecificSourcePackage pkg <- pkgSpecifiers ]
$ basicDepResolverParams
installedPkgIndex sourcePkgIndex
applySandboxInstallPolicy :: SandboxPackageInfo
-> DepResolverParams
-> DepResolverParams
applySandboxInstallPolicy
(SandboxPackageInfo modifiedDeps otherDeps allSandboxPkgs _allDeps)
params
= addPreferences [ PackageInstalledPreference n PreferInstalled
| n <- installedNotModified ]
. addTargets installedNotModified
. addPreferences
[ PackageVersionPreference (packageName pkg)
(thisVersion (packageVersion pkg)) | pkg <- otherDeps ]
. addConstraints
[ let pc = PackageConstraintVersion (packageName pkg)
(thisVersion (packageVersion pkg))
in LabeledPackageConstraint pc ConstraintSourceModifiedAddSourceDep
| pkg <- modifiedDeps ]
. addTargets [ packageName pkg | pkg <- modifiedDeps ]
. hideInstalledPackagesSpecificBySourcePackageId
[ packageId pkg | pkg <- modifiedDeps ]
-- We don't need to add source packages for add-source deps to the
-- 'installedPkgIndex' since 'getSourcePackages' did that for us.
$ params
where
installedPkgIds =
map fst . InstalledPackageIndex.allPackagesBySourcePackageId
$ allSandboxPkgs
modifiedPkgIds = map packageId modifiedDeps
installedNotModified = [ packageName pkg | pkg <- installedPkgIds,
pkg `notElem` modifiedPkgIds ]
-- ------------------------------------------------------------
-- * Interface to the standard resolver
-- ------------------------------------------------------------
chooseSolver :: Verbosity -> PreSolver -> CompilerInfo -> IO Solver
chooseSolver verbosity preSolver _cinfo =
case preSolver of
AlwaysTopDown -> do
warn verbosity "Topdown solver is deprecated"
return TopDown
AlwaysModular -> do
return Modular
Choose -> do
info verbosity "Choosing modular solver."
return Modular
runSolver :: Solver -> SolverConfig -> DependencyResolver
runSolver TopDown = const topDownResolver -- TODO: warn about unsupported options
runSolver Modular = modularResolver
-- | Run the dependency solver.
--
-- Since this is potentially an expensive operation, the result is wrapped in a
-- a 'Progress' structure that can be unfolded to provide progress information,
-- logging messages and the final result or an error.
--
resolveDependencies :: Platform
-> CompilerInfo
-> Solver
-> DepResolverParams
-> Progress String String InstallPlan
--TODO: is this needed here? see dontUpgradeNonUpgradeablePackages
resolveDependencies platform comp _solver params
| null (depResolverTargets params)
= return (validateSolverResult platform comp indGoals [])
where
indGoals = depResolverIndependentGoals params
resolveDependencies platform comp solver params =
Step (showDepResolverParams finalparams)
$ fmap (validateSolverResult platform comp indGoals)
$ runSolver solver (SolverConfig reorderGoals indGoals noReinstalls
shadowing strFlags maxBkjumps)
platform comp installedPkgIndex sourcePkgIndex
preferences constraints targets
where
finalparams @ (DepResolverParams
targets constraints
prefs defpref
installedPkgIndex
sourcePkgIndex
reorderGoals
indGoals
noReinstalls
shadowing
strFlags
maxBkjumps) = dontUpgradeNonUpgradeablePackages
-- TODO:
-- The modular solver can properly deal with broken
-- packages and won't select them. So the
-- 'hideBrokenInstalledPackages' function should be moved
-- into a module that is specific to the top-down solver.
. (if solver /= Modular then hideBrokenInstalledPackages
else id)
$ params
preferences = interpretPackagesPreference
(Set.fromList targets) defpref prefs
-- | Give an interpretation to the global 'PackagesPreference' as
-- specific per-package 'PackageVersionPreference'.
--
interpretPackagesPreference :: Set PackageName
-> PackagesPreferenceDefault
-> [PackagePreference]
-> (PackageName -> PackagePreferences)
interpretPackagesPreference selected defaultPref prefs =
\pkgname -> PackagePreferences (versionPref pkgname) (installPref pkgname)
where
versionPref pkgname =
fromMaybe anyVersion (Map.lookup pkgname versionPrefs)
versionPrefs = Map.fromList
[ (pkgname, pref)
| PackageVersionPreference pkgname pref <- prefs ]
installPref pkgname =
fromMaybe (installPrefDefault pkgname) (Map.lookup pkgname installPrefs)
installPrefs = Map.fromList
[ (pkgname, pref)
| PackageInstalledPreference pkgname pref <- prefs ]
installPrefDefault = case defaultPref of
PreferAllLatest -> const PreferLatest
PreferAllInstalled -> const PreferInstalled
PreferLatestForSelected -> \pkgname ->
-- When you say cabal install foo, what you really mean is, prefer the
-- latest version of foo, but the installed version of everything else
if pkgname `Set.member` selected then PreferLatest
else PreferInstalled
-- ------------------------------------------------------------
-- * Checking the result of the solver
-- ------------------------------------------------------------
-- | Make an install plan from the output of the dep resolver.
-- It checks that the plan is valid, or it's an error in the dep resolver.
--
validateSolverResult :: Platform
-> CompilerInfo
-> Bool
-> [ResolverPackage]
-> InstallPlan
validateSolverResult platform comp indepGoals pkgs =
case planPackagesProblems platform comp pkgs of
[] -> case InstallPlan.new indepGoals index of
Right plan -> plan
Left problems -> error (formatPlanProblems problems)
problems -> error (formatPkgProblems problems)
where
index = InstalledPackageIndex.fromList (map toPlanPackage pkgs)
toPlanPackage (PreExisting pkg) = InstallPlan.PreExisting pkg
toPlanPackage (Configured pkg) = InstallPlan.Configured pkg
formatPkgProblems = formatProblemMessage . map showPlanPackageProblem
formatPlanProblems = formatProblemMessage . map InstallPlan.showPlanProblem
formatProblemMessage problems =
unlines $
"internal error: could not construct a valid install plan."
: "The proposed (invalid) plan contained the following problems:"
: problems
++ "Proposed plan:"
: [InstallPlan.showPlanIndex index]
data PlanPackageProblem =
InvalidConfiguredPackage ConfiguredPackage [PackageProblem]
showPlanPackageProblem :: PlanPackageProblem -> String
showPlanPackageProblem (InvalidConfiguredPackage pkg packageProblems) =
"Package " ++ display (packageId pkg)
++ " has an invalid configuration, in particular:\n"
++ unlines [ " " ++ showPackageProblem problem
| problem <- packageProblems ]
planPackagesProblems :: Platform -> CompilerInfo
-> [ResolverPackage]
-> [PlanPackageProblem]
planPackagesProblems platform cinfo pkgs =
[ InvalidConfiguredPackage pkg packageProblems
| Configured pkg <- pkgs
, let packageProblems = configuredPackageProblems platform cinfo pkg
, not (null packageProblems) ]
data PackageProblem = DuplicateFlag PD.FlagName
| MissingFlag PD.FlagName
| ExtraFlag PD.FlagName
| DuplicateDeps [PackageId]
| MissingDep Dependency
| ExtraDep PackageId
| InvalidDep Dependency PackageId
showPackageProblem :: PackageProblem -> String
showPackageProblem (DuplicateFlag (PD.FlagName flag)) =
"duplicate flag in the flag assignment: " ++ flag
showPackageProblem (MissingFlag (PD.FlagName flag)) =
"missing an assignment for the flag: " ++ flag
showPackageProblem (ExtraFlag (PD.FlagName flag)) =
"extra flag given that is not used by the package: " ++ flag
showPackageProblem (DuplicateDeps pkgids) =
"duplicate packages specified as selected dependencies: "
++ intercalate ", " (map display pkgids)
showPackageProblem (MissingDep dep) =
"the package has a dependency " ++ display dep
++ " but no package has been selected to satisfy it."
showPackageProblem (ExtraDep pkgid) =
"the package configuration specifies " ++ display pkgid
++ " but (with the given flag assignment) the package does not actually"
++ " depend on any version of that package."
showPackageProblem (InvalidDep dep pkgid) =
"the package depends on " ++ display dep
++ " but the configuration specifies " ++ display pkgid
++ " which does not satisfy the dependency."
-- | A 'ConfiguredPackage' is valid if the flag assignment is total and if
-- in the configuration given by the flag assignment, all the package
-- dependencies are satisfied by the specified packages.
--
configuredPackageProblems :: Platform -> CompilerInfo
-> ConfiguredPackage -> [PackageProblem]
configuredPackageProblems platform cinfo
(ConfiguredPackage pkg specifiedFlags stanzas specifiedDeps') =
[ DuplicateFlag flag | ((flag,_):_) <- duplicates specifiedFlags ]
++ [ MissingFlag flag | OnlyInLeft flag <- mergedFlags ]
++ [ ExtraFlag flag | OnlyInRight flag <- mergedFlags ]
++ [ DuplicateDeps pkgs
| pkgs <- CD.nonSetupDeps (fmap (duplicatesBy (comparing packageName))
specifiedDeps) ]
++ [ MissingDep dep | OnlyInLeft dep <- mergedDeps ]
++ [ ExtraDep pkgid | OnlyInRight pkgid <- mergedDeps ]
++ [ InvalidDep dep pkgid | InBoth dep pkgid <- mergedDeps
, not (packageSatisfiesDependency pkgid dep) ]
where
specifiedDeps :: ComponentDeps [PackageId]
specifiedDeps = fmap (map confSrcId) specifiedDeps'
mergedFlags = mergeBy compare
(sort $ map PD.flagName (PD.genPackageFlags (packageDescription pkg)))
(sort $ map fst specifiedFlags)
packageSatisfiesDependency
(PackageIdentifier name version)
(Dependency name' versionRange) = assert (name == name') $
version `withinRange` versionRange
dependencyName (Dependency name _) = name
mergedDeps :: [MergeResult Dependency PackageId]
mergedDeps = mergeDeps requiredDeps (CD.flatDeps specifiedDeps)
mergeDeps :: [Dependency] -> [PackageId]
-> [MergeResult Dependency PackageId]
mergeDeps required specified =
let sortNubOn f = nubBy ((==) `on` f) . sortBy (compare `on` f) in
mergeBy
(\dep pkgid -> dependencyName dep `compare` packageName pkgid)
(sortNubOn dependencyName required)
(sortNubOn packageName specified)
-- TODO: It would be nicer to use ComponentDeps here so we can be more
-- precise in our checks. That's a bit tricky though, as this currently
-- relies on the 'buildDepends' field of 'PackageDescription'. (OTOH, that
-- field is deprecated and should be removed anyway.) As long as we _do_
-- use a flat list here, we have to allow for duplicates when we fold
-- specifiedDeps; once we have proper ComponentDeps here we should get rid
-- of the `nubOn` in `mergeDeps`.
requiredDeps :: [Dependency]
requiredDeps =
--TODO: use something lower level than finalizePackageDescription
case finalizePackageDescription specifiedFlags
(const True)
platform cinfo
[]
(enableStanzas stanzas $ packageDescription pkg) of
Right (resolvedPkg, _) ->
externalBuildDepends resolvedPkg
++ maybe [] PD.setupDepends (PD.setupBuildInfo resolvedPkg)
Left _ ->
error "configuredPackageInvalidDeps internal error"
-- ------------------------------------------------------------
-- * Simple resolver that ignores dependencies
-- ------------------------------------------------------------
-- | A simplistic method of resolving a list of target package names to
-- available packages.
--
-- Specifically, it does not consider package dependencies at all. Unlike
-- 'resolveDependencies', no attempt is made to ensure that the selected
-- packages have dependencies that are satisfiable or consistent with
-- each other.
--
-- It is suitable for tasks such as selecting packages to download for user
-- inspection. It is not suitable for selecting packages to install.
--
-- Note: if no installed package index is available, it is OK to pass 'mempty'.
-- It simply means preferences for installed packages will be ignored.
--
resolveWithoutDependencies :: DepResolverParams
-> Either [ResolveNoDepsError] [SourcePackage]
resolveWithoutDependencies (DepResolverParams targets constraints
prefs defpref installedPkgIndex sourcePkgIndex
_reorderGoals _indGoals _avoidReinstalls
_shadowing _strFlags _maxBjumps) =
collectEithers (map selectPackage targets)
where
selectPackage :: PackageName -> Either ResolveNoDepsError SourcePackage
selectPackage pkgname
| null choices = Left $! ResolveUnsatisfiable pkgname requiredVersions
| otherwise = Right $! maximumBy bestByPrefs choices
where
-- Constraints
requiredVersions = packageConstraints pkgname
pkgDependency = Dependency pkgname requiredVersions
choices = PackageIndex.lookupDependency sourcePkgIndex
pkgDependency
-- Preferences
PackagePreferences preferredVersions preferInstalled
= packagePreferences pkgname
bestByPrefs = comparing $ \pkg ->
(installPref pkg, versionPref pkg, packageVersion pkg)
installPref = case preferInstalled of
PreferLatest -> const False
PreferInstalled -> not . null
. InstalledPackageIndex.lookupSourcePackageId
installedPkgIndex
. packageId
versionPref pkg = packageVersion pkg `withinRange` preferredVersions
packageConstraints :: PackageName -> VersionRange
packageConstraints pkgname =
Map.findWithDefault anyVersion pkgname packageVersionConstraintMap
packageVersionConstraintMap =
let pcs = map unlabelPackageConstraint constraints
in Map.fromList [ (name, range)
| PackageConstraintVersion name range <- pcs ]
packagePreferences :: PackageName -> PackagePreferences
packagePreferences = interpretPackagesPreference
(Set.fromList targets) defpref prefs
collectEithers :: [Either a b] -> Either [a] [b]
collectEithers = collect . partitionEithers
where
collect ([], xs) = Right xs
collect (errs,_) = Left errs
partitionEithers :: [Either a b] -> ([a],[b])
partitionEithers = foldr (either left right) ([],[])
where
left a (l, r) = (a:l, r)
right a (l, r) = (l, a:r)
-- | Errors for 'resolveWithoutDependencies'.
--
data ResolveNoDepsError =
-- | A package name which cannot be resolved to a specific package.
-- Also gives the constraint on the version and whether there was
-- a constraint on the package being installed.
ResolveUnsatisfiable PackageName VersionRange
instance Show ResolveNoDepsError where
show (ResolveUnsatisfiable name ver) =
"There is no available version of " ++ display name
++ " that satisfies " ++ display (simplifyVersionRange ver)
| randen/cabal | cabal-install/Distribution/Client/Dependency.hs | bsd-3-clause | 33,977 | 1 | 19 | 8,570 | 5,871 | 3,197 | 2,674 | 587 | 4 |
module GHC.Utils.Outputable (module Outputable) where
import Outputable
| google/ghc-source-gen | compat/GHC/Utils/Outputable.hs | bsd-3-clause | 72 | 0 | 4 | 7 | 16 | 11 | 5 | 2 | 0 |
module HLearn.Models.Classifiers.HTree
where
import Debug.Trace
import qualified Data.Map as Map
import HLearn.Algebra
import HLearn.Models.Distributions
import HLearn.Models.Classification
import HLearn.Models.Classifiers.Bayes
newtype HTreeParams distparams = HTreeParams (BayesParams distparams)
deriving (Read,Show,Eq,Ord)
newtype HTree dist label prob = HTree (Bayes dist label prob)
deriving (Read,Show,Eq,Ord)
-- instance (Ord prob, Show (dist prob), Show label, Untup (dist prob) a b, Show b) => ProbabilityClassifier (HTree dist label prob) dp label prob where
-- probabilityClassify (HTree (SGJust (Bayes' labelDist attrDist))) dp =
-- trace (show $ untup $ map snd $ Map.toList attrDist) $ undefined
debug (HTree (SGJust (Bayes' labelDist attrDist))) dp = map snd $ Map.toList attrDist
htree = HTree model
-- class TupTranspose tup where
-- tuptrans :: tup ->
-- tuptrans [a:::b] -> [a]:::[b]
-- tuptrans [] = []
-- tuptrans x:xs =
class Untup tup a b where
untup :: [tup] -> a:::[b]
instance (Untup a a' b') => Untup (a:::b) (a':::[b']) b where
untup xs = (untup a) ::: b
where (a:::b) = untupzip xs
instance Untup (a:::b) [a] b where
untup = untupzip
kindswap :: ((a:::.b) c) -> (a c):::(b c)
kindswap (a:::.b) = (a:::b)
{-instance (Untup (a c) (a' c) (b' c)) => Untup ((a:::.b) c) ((a' c):::[b' c]) (b c) where
untup xs = (untup a) ::: b
where (a:::.b) = untupzip xs
instance Untup ((a:::.b) c) [a c] (b c) where
untup = untupzip-}
untupzip :: [(a:::b)] -> ([a]:::[b])
{-# INLINE untupzip #-}
untupzip = foldr (\(a:::b) ~(as:::bs) -> ((a:as):::(b:bs))) ([]:::[]) | iamkingmaker/HLearn | src/HLearn/Models/Classifiers/HTree.hs | bsd-3-clause | 1,726 | 0 | 11 | 392 | 475 | 268 | 207 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.