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 LambdaCase #-}
import Haskus.Apps.System.Build.Config
import Haskus.Apps.System.Build.Linux
import Haskus.Apps.System.Build.Syslinux
import Haskus.Apps.System.Build.CmdLine
import Haskus.Apps.System.Build.Utils
import Haskus.Apps.System.Build.Ramdisk
import Haskus.Apps.System.Build.Stack
import Haskus.Apps.System.Build.GMP
import Haskus.Apps.System.Build.QEMU
import Haskus.Apps.System.Build.ISO
import Haskus.Apps.System.Build.Disk
import qualified Data.Text as Text
import Haskus.Utils.Flow
import Options.Applicative.Simple
import Paths_haskus_system_build
import Data.Version
import System.IO.Temp
import System.Directory
import System.FilePath
main :: IO ()
main = do
-- read command-line options
(_,runCmd) <-
simpleOptions (showVersion version)
"haskus-system-build"
"This tool lets you build systems using haskus-system framework. It manages Linux/Syslinux (download and build), it builds ramdisk, it launches QEMU, etc."
(pure ()) $ do
addCommand "init"
"Create a new project from a template"
initCommand
initOptions
addCommand "build"
"Build a project"
buildCommand
buildOptions
addCommand "test"
"Test a project with QEMU"
testCommand
testOptions
addCommand "make-iso"
"Create an ISO image"
(const makeISOCommand)
(pure ())
addCommand "test-iso"
"Test an ISO image"
(const testISOCommand)
(pure ())
addCommand "make-disk"
"Create a disk directory"
makeDiskCommand
(makeDiskOptions)
addCommand "make-device"
"Create a bootable device (WARNING: IT ERASES IT). You must be in the sudoers list"
makeDeviceCommand
(makeDeviceOptions)
runCmd
initCommand :: InitOptions -> IO ()
initCommand opts = do
let
template = initOptTemplate opts
cd <- getCurrentDirectory
withSystemTempDirectory "haskus-system-build" $ \fp -> do
-- get latest templates
showStep "Retrieving templates..."
shellInErr fp "git clone --depth=1 https://github.com/haskus/haskus-system-templates.git" $
failWith "Cannot retrieve templates. Check that `git` is installed and that github is reachable using https."
let fp2 = fp </> "haskus-system-templates"
dirs <- listDirectory fp2
unless (any (== template) dirs) $
failWith $ "Cannot find template \"" ++ template ++"\""
-- copy template
showStep $ "Copying \"" ++ template ++ "\" template..."
shellInErr fp2
("cp -i -r ./" ++ template ++ "/* " ++ cd) $
failWith "Cannot copy the selected template"
readConfig :: IO SystemConfig
readConfig = do
let configFile = "system.yaml"
unlessM (doesFileExist configFile) $
failWith $ "Cannot find \"" ++ configFile ++ "\""
mconfig <- readSystemConfig configFile
case mconfig of
Left e -> failWith $ "Cannot parse \"" ++ configFile ++ "\": " ++ show e
Right c -> return c
buildCommand :: BuildOptions -> IO ()
buildCommand opts = do
config' <- readConfig
-- override config
let config = if buildOptInit opts /= ""
-- TODO: use lenses
then config'
{ ramdiskConfig = (ramdiskConfig config')
{ ramdiskInit = Text.pack (buildOptInit opts)
}
}
else config'
showStatus config
gmpMain
linuxMain (linuxConfig config)
_ <- syslinuxMain (syslinuxConfig config)
stackBuild
testCommand :: TestOptions -> IO ()
testCommand opts = do
config' <- readConfig
-- override config
let config = if testOptInit opts /= ""
-- TODO: use lenses
then config'
{ ramdiskConfig = (ramdiskConfig config')
{ ramdiskInit = Text.pack (testOptInit opts)
}
}
else config'
showStatus config
gmpMain
linuxMain (linuxConfig config)
stackBuild
ramdiskMain (ramdiskConfig config)
qemuExecRamdisk config
showStatus :: SystemConfig -> IO ()
showStatus config = do
let linuxVersion' = Text.unpack (linuxConfigVersion (linuxConfig config))
let syslinuxVersion' = config
|> syslinuxConfig
|> syslinuxVersion
|> Text.unpack
let initProgram = config
|> ramdiskConfig
|> ramdiskInit
|> Text.unpack
ghcVersion <- stackGetGHCVersion
stackResolver <- stackGetResolver
putStrLn "==================================================="
putStrLn " Haskus system - build config"
putStrLn "---------------------------------------------------"
putStrLn ("GHC version: " ++ ghcVersion)
putStrLn ("Stack resolver: " ++ stackResolver)
putStrLn ("Linux version: " ++ linuxVersion')
putStrLn ("Syslinux version: " ++ syslinuxVersion')
putStrLn ("Init program: " ++ initProgram)
putStrLn "==================================================="
makeISOCommand :: IO ()
makeISOCommand = do
config <- readConfig
showStatus config
gmpMain
linuxMain (linuxConfig config)
stackBuild
ramdiskMain (ramdiskConfig config)
_ <- isoMake config
return ()
makeDiskCommand :: MakeDiskOptions -> IO ()
makeDiskCommand opts = do
config <- readConfig
showStatus config
gmpMain
linuxMain (linuxConfig config)
stackBuild
ramdiskMain (ramdiskConfig config)
makeDisk config (diskOptPath opts)
testISOCommand :: IO ()
testISOCommand = do
config <- readConfig
showStatus config
gmpMain
linuxMain (linuxConfig config)
stackBuild
ramdiskMain (ramdiskConfig config)
isoFile <- isoMake config
qemuExecISO config isoFile
makeDeviceCommand :: MakeDeviceOptions -> IO ()
makeDeviceCommand opts = do
config <- readConfig
showStatus config
gmpMain
linuxMain (linuxConfig config)
stackBuild
ramdiskMain (ramdiskConfig config)
makeDevice config (deviceOptPath opts)
| hsyl20/ViperVM | haskus-system-build/src/apps/Haskus/Apps/System/Build/Main.hs | bsd-3-clause | 6,532 | 0 | 18 | 2,024 | 1,364 | 657 | 707 | 169 | 2 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1994-1998
UniqFM: Specialised finite maps, for things with @Uniques@.
Basically, the things need to be in class @Uniquable@, and we use the
@getUnique@ method to grab their @Uniques@.
(A similar thing to @UniqSet@, as opposed to @Set@.)
The interface is based on @FiniteMap@s, but the implementation uses
@Data.IntMap@, which is both maintained and faster than the past
implementation (see commit log).
The @UniqFM@ interface maps directly to Data.IntMap, only
``Data.IntMap.union'' is left-biased and ``plusUFM'' right-biased
and ``addToUFM\_C'' and ``Data.IntMap.insertWith'' differ in the order
of arguments of combining function.
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# OPTIONS_GHC -Wall #-}
module ETA.Utils.UniqFM (
-- * Unique-keyed mappings
UniqFM, -- abstract type
-- ** Manipulating those mappings
emptyUFM,
unitUFM,
unitDirectlyUFM,
listToUFM,
listToUFM_Directly,
listToUFM_C,
addToUFM,addToUFM_C,addToUFM_Acc,
addListToUFM,addListToUFM_C,
addToUFM_Directly,
addListToUFM_Directly,
adjustUFM, alterUFM,
adjustUFM_Directly,
delFromUFM,
delFromUFM_Directly,
delListFromUFM,
delListFromUFM_Directly,
plusUFM,
plusUFM_C,
plusUFM_CD,
plusMaybeUFM_C,
plusUFMList,
minusUFM,
intersectUFM,
intersectUFM_C,
disjointUFM,
nonDetFoldUFM, foldUFM, nonDetFoldUFM_Directly,
anyUFM, allUFM, seqEltsUFM,
mapUFM, mapUFM_Directly,
elemUFM, elemUFM_Directly,
filterUFM, filterUFM_Directly, partitionUFM,
sizeUFM,
isNullUFM,
lookupUFM, lookupUFM_Directly,
lookupWithDefaultUFM, lookupWithDefaultUFM_Directly,
nonDetEltsUFM, eltsUFM, nonDetKeysUFM,
ufmToSet_Directly,
nonDetUFMToList, ufmToIntMap,
pprUniqFM, pprUFM, pprUFMWithKeys, pluralUFM
) where
import ETA.BasicTypes.Unique ( Uniquable(..), Unique, getKey )
import ETA.Utils.Outputable
import Data.List (foldl')
import qualified Data.IntMap as M
import qualified Data.IntSet as S
import Data.Typeable
import Data.Data
#if __GLASGOW_HASKELL__ > 710
import Data.Semigroup ( Semigroup )
import qualified Data.Semigroup as Semigroup
#endif
newtype UniqFM ele = UFM (M.IntMap ele)
deriving (Data, Eq, Functor, Typeable)
-- We used to derive Traversable and Foldable, but they were nondeterministic
-- and not obvious at the call site. You can use explicit nonDetEltsUFM
-- and fold a list if needed.
-- See Note [Deterministic UniqFM] in UniqDFM to learn about determinism.
emptyUFM :: UniqFM elt
emptyUFM = UFM M.empty
isNullUFM :: UniqFM elt -> Bool
isNullUFM (UFM m) = M.null m
unitUFM :: Uniquable key => key -> elt -> UniqFM elt
unitUFM k v = UFM (M.singleton (getKey $ getUnique k) v)
-- when you've got the Unique already
unitDirectlyUFM :: Unique -> elt -> UniqFM elt
unitDirectlyUFM u v = UFM (M.singleton (getKey u) v)
listToUFM :: Uniquable key => [(key,elt)] -> UniqFM elt
listToUFM = foldl (\m (k, v) -> addToUFM m k v) emptyUFM
listToUFM_Directly :: [(Unique, elt)] -> UniqFM elt
listToUFM_Directly = foldl (\m (u, v) -> addToUFM_Directly m u v) emptyUFM
listToUFM_C
:: Uniquable key
=> (elt -> elt -> elt)
-> [(key, elt)]
-> UniqFM elt
listToUFM_C f = foldl (\m (k, v) -> addToUFM_C f m k v) emptyUFM
addToUFM :: Uniquable key => UniqFM elt -> key -> elt -> UniqFM elt
addToUFM (UFM m) k v = UFM (M.insert (getKey $ getUnique k) v m)
addListToUFM :: Uniquable key => UniqFM elt -> [(key,elt)] -> UniqFM elt
addListToUFM = foldl (\m (k, v) -> addToUFM m k v)
addListToUFM_Directly :: UniqFM elt -> [(Unique,elt)] -> UniqFM elt
addListToUFM_Directly = foldl (\m (k, v) -> addToUFM_Directly m k v)
addToUFM_Directly :: UniqFM elt -> Unique -> elt -> UniqFM elt
addToUFM_Directly (UFM m) u v = UFM (M.insert (getKey u) v m)
addToUFM_C
:: Uniquable key
=> (elt -> elt -> elt) -- old -> new -> result
-> UniqFM elt -- old
-> key -> elt -- new
-> UniqFM elt -- result
-- Arguments of combining function of M.insertWith and addToUFM_C are flipped.
addToUFM_C f (UFM m) k v =
UFM (M.insertWith (flip f) (getKey $ getUnique k) v m)
addToUFM_Acc
:: Uniquable key
=> (elt -> elts -> elts) -- Add to existing
-> (elt -> elts) -- New element
-> UniqFM elts -- old
-> key -> elt -- new
-> UniqFM elts -- result
addToUFM_Acc exi new (UFM m) k v =
UFM (M.insertWith (\_new old -> exi v old) (getKey $ getUnique k) (new v) m)
alterUFM
:: Uniquable key
=> (Maybe elt -> Maybe elt) -- How to adjust
-> UniqFM elt -- old
-> key -- new
-> UniqFM elt -- result
alterUFM f (UFM m) k = UFM (M.alter f (getKey $ getUnique k) m)
addListToUFM_C
:: Uniquable key
=> (elt -> elt -> elt)
-> UniqFM elt -> [(key,elt)]
-> UniqFM elt
addListToUFM_C f = foldl (\m (k, v) -> addToUFM_C f m k v)
adjustUFM :: Uniquable key => (elt -> elt) -> UniqFM elt -> key -> UniqFM elt
adjustUFM f (UFM m) k = UFM (M.adjust f (getKey $ getUnique k) m)
adjustUFM_Directly :: (elt -> elt) -> UniqFM elt -> Unique -> UniqFM elt
adjustUFM_Directly f (UFM m) u = UFM (M.adjust f (getKey u) m)
delFromUFM :: Uniquable key => UniqFM elt -> key -> UniqFM elt
delFromUFM (UFM m) k = UFM (M.delete (getKey $ getUnique k) m)
delListFromUFM :: Uniquable key => UniqFM elt -> [key] -> UniqFM elt
delListFromUFM = foldl delFromUFM
delListFromUFM_Directly :: UniqFM elt -> [Unique] -> UniqFM elt
delListFromUFM_Directly = foldl delFromUFM_Directly
delFromUFM_Directly :: UniqFM elt -> Unique -> UniqFM elt
delFromUFM_Directly (UFM m) u = UFM (M.delete (getKey u) m)
-- Bindings in right argument shadow those in the left
plusUFM :: UniqFM elt -> UniqFM elt -> UniqFM elt
-- M.union is left-biased, plusUFM should be right-biased.
plusUFM (UFM x) (UFM y) = UFM (M.union y x)
-- Note (M.union y x), with arguments flipped
-- M.union is left-biased, plusUFM should be right-biased.
plusUFM_C :: (elt -> elt -> elt) -> UniqFM elt -> UniqFM elt -> UniqFM elt
plusUFM_C f (UFM x) (UFM y) = UFM (M.unionWith f x y)
-- | `plusUFM_CD f m1 d1 m2 d2` merges the maps using `f` as the
-- combinding function and `d1` resp. `d2` as the default value if
-- there is no entry in `m1` reps. `m2`. The domain is the union of
-- the domains of `m1` and `m2`.
--
-- Representative example:
--
-- @
-- plusUFM_CD f {A: 1, B: 2} 23 {B: 3, C: 4} 42
-- == {A: f 1 42, B: f 2 3, C: f 23 4 }
-- @
plusUFM_CD
:: (elt -> elt -> elt)
-> UniqFM elt -- map X
-> elt -- default for X
-> UniqFM elt -- map Y
-> elt -- default for Y
-> UniqFM elt
plusUFM_CD f (UFM xm) dx (UFM ym) dy
= UFM $ M.mergeWithKey
(\_ x y -> Just (x `f` y))
(M.map (\x -> x `f` dy))
(M.map (\y -> dx `f` y))
xm ym
plusMaybeUFM_C :: (elt -> elt -> Maybe elt)
-> UniqFM elt -> UniqFM elt -> UniqFM elt
plusMaybeUFM_C f (UFM xm) (UFM ym)
= UFM $ M.mergeWithKey
(\_ x y -> x `f` y)
id
id
xm ym
plusUFMList :: [UniqFM elt] -> UniqFM elt
plusUFMList = foldl' plusUFM emptyUFM
minusUFM :: UniqFM elt1 -> UniqFM elt2 -> UniqFM elt1
minusUFM (UFM x) (UFM y) = UFM (M.difference x y)
intersectUFM :: UniqFM elt1 -> UniqFM elt2 -> UniqFM elt1
intersectUFM (UFM x) (UFM y) = UFM (M.intersection x y)
intersectUFM_C
:: (elt1 -> elt2 -> elt3)
-> UniqFM elt1
-> UniqFM elt2
-> UniqFM elt3
intersectUFM_C f (UFM x) (UFM y) = UFM (M.intersectionWith f x y)
disjointUFM :: UniqFM elt1 -> UniqFM elt2 -> Bool
disjointUFM (UFM x) (UFM y) = M.null (M.intersection x y)
foldUFM :: (elt -> a -> a) -> a -> UniqFM elt -> a
foldUFM k z (UFM m) = M.foldr k z m
mapUFM :: (elt1 -> elt2) -> UniqFM elt1 -> UniqFM elt2
mapUFM f (UFM m) = UFM (M.map f m)
mapUFM_Directly :: (Unique -> elt1 -> elt2) -> UniqFM elt1 -> UniqFM elt2
mapUFM_Directly f (UFM m) = UFM (M.mapWithKey (f . getUnique) m)
filterUFM :: (elt -> Bool) -> UniqFM elt -> UniqFM elt
filterUFM p (UFM m) = UFM (M.filter p m)
filterUFM_Directly :: (Unique -> elt -> Bool) -> UniqFM elt -> UniqFM elt
filterUFM_Directly p (UFM m) = UFM (M.filterWithKey (p . getUnique) m)
partitionUFM :: (elt -> Bool) -> UniqFM elt -> (UniqFM elt, UniqFM elt)
partitionUFM p (UFM m) =
case M.partition p m of
(left, right) -> (UFM left, UFM right)
sizeUFM :: UniqFM elt -> Int
sizeUFM (UFM m) = M.size m
elemUFM :: Uniquable key => key -> UniqFM elt -> Bool
elemUFM k (UFM m) = M.member (getKey $ getUnique k) m
elemUFM_Directly :: Unique -> UniqFM elt -> Bool
elemUFM_Directly u (UFM m) = M.member (getKey u) m
lookupUFM :: Uniquable key => UniqFM elt -> key -> Maybe elt
lookupUFM (UFM m) k = M.lookup (getKey $ getUnique k) m
-- when you've got the Unique already
lookupUFM_Directly :: UniqFM elt -> Unique -> Maybe elt
lookupUFM_Directly (UFM m) u = M.lookup (getKey u) m
lookupWithDefaultUFM :: Uniquable key => UniqFM elt -> elt -> key -> elt
lookupWithDefaultUFM (UFM m) v k = M.findWithDefault v (getKey $ getUnique k) m
lookupWithDefaultUFM_Directly :: UniqFM elt -> elt -> Unique -> elt
lookupWithDefaultUFM_Directly (UFM m) v u = M.findWithDefault v (getKey u) m
eltsUFM :: UniqFM elt -> [elt]
eltsUFM (UFM m) = M.elems m
ufmToSet_Directly :: UniqFM elt -> S.IntSet
ufmToSet_Directly (UFM m) = M.keysSet m
anyUFM :: (elt -> Bool) -> UniqFM elt -> Bool
anyUFM p (UFM m) = M.foldr ((||) . p) False m
allUFM :: (elt -> Bool) -> UniqFM elt -> Bool
allUFM p (UFM m) = M.foldr ((&&) . p) True m
seqEltsUFM :: ([elt] -> ()) -> UniqFM elt -> ()
seqEltsUFM seqList = seqList . nonDetEltsUFM
-- It's OK to use nonDetEltsUFM here because the type guarantees that
-- the only interesting thing this function can do is to force the
-- elements.
-- See Note [Deterministic UniqFM] to learn about nondeterminism.
-- If you use this please provide a justification why it doesn't introduce
-- nondeterminism.
nonDetEltsUFM :: UniqFM elt -> [elt]
nonDetEltsUFM (UFM m) = M.elems m
-- See Note [Deterministic UniqFM] to learn about nondeterminism.
-- If you use this please provide a justification why it doesn't introduce
-- nondeterminism.
nonDetKeysUFM :: UniqFM elt -> [Unique]
nonDetKeysUFM (UFM m) = map getUnique $ M.keys m
-- See Note [Deterministic UniqFM] to learn about nondeterminism.
-- If you use this please provide a justification why it doesn't introduce
-- nondeterminism.
nonDetFoldUFM :: (elt -> a -> a) -> a -> UniqFM elt -> a
nonDetFoldUFM k z (UFM m) = M.foldr k z m
-- See Note [Deterministic UniqFM] to learn about nondeterminism.
-- If you use this please provide a justification why it doesn't introduce
-- nondeterminism.
nonDetFoldUFM_Directly:: (Unique -> elt -> a -> a) -> a -> UniqFM elt -> a
nonDetFoldUFM_Directly k z (UFM m) = M.foldrWithKey (k . getUnique) z m
-- See Note [Deterministic UniqFM] to learn about nondeterminism.
-- If you use this please provide a justification why it doesn't introduce
-- nondeterminism.
nonDetUFMToList :: UniqFM elt -> [(Unique, elt)]
nonDetUFMToList (UFM m) = map (\(k, v) -> (getUnique k, v)) $ M.toList m
ufmToIntMap :: UniqFM elt -> M.IntMap elt
ufmToIntMap (UFM m) = m
-- Instances
#if __GLASGOW_HASKELL__ > 710
instance Semigroup (UniqFM a) where
(<>) = plusUFM
#endif
instance Monoid (UniqFM a) where
mempty = emptyUFM
mappend = plusUFM
-- Output-ery
instance Outputable a => Outputable (UniqFM a) where
ppr ufm = pprUniqFM ppr ufm
pprUniqFM :: (a -> SDoc) -> UniqFM a -> SDoc
pprUniqFM ppr_elt ufm
= brackets $ fsep $ punctuate comma $
[ ppr uq <+> text ":->" <+> ppr_elt elt
| (uq, elt) <- nonDetUFMToList ufm ]
-- It's OK to use nonDetUFMToList here because we only use it for
-- pretty-printing.
-- | Pretty-print a non-deterministic set.
-- The order of variables is non-deterministic and for pretty-printing that
-- shouldn't be a problem.
-- Having this function helps contain the non-determinism created with
-- nonDetEltsUFM.
pprUFM :: UniqFM a -- ^ The things to be pretty printed
-> ([a] -> SDoc) -- ^ The pretty printing function to use on the elements
-> SDoc -- ^ 'SDoc' where the things have been pretty
-- printed
pprUFM ufm pp = pp (nonDetEltsUFM ufm)
-- | Pretty-print a non-deterministic set.
-- The order of variables is non-deterministic and for pretty-printing that
-- shouldn't be a problem.
-- Having this function helps contain the non-determinism created with
-- nonDetUFMToList.
pprUFMWithKeys
:: UniqFM a -- ^ The things to be pretty printed
-> ([(Unique, a)] -> SDoc) -- ^ The pretty printing function to use on the elements
-> SDoc -- ^ 'SDoc' where the things have been pretty
-- printed
pprUFMWithKeys ufm pp = pp (nonDetUFMToList ufm)
-- | Determines the pluralisation suffix appropriate for the length of a set
-- in the same way that plural from Outputable does for lists.
pluralUFM :: UniqFM a -> SDoc
pluralUFM ufm
| sizeUFM ufm == 1 = empty
| otherwise = char 's'
| pparkkin/eta | compiler/ETA/Utils/UniqFM.hs | bsd-3-clause | 13,405 | 0 | 11 | 3,074 | 3,970 | 2,079 | 1,891 | 233 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
------------------------------------------------------------------------------
module Snap.Internal.Http.Server.TLS
( TLSException(..)
, withTLS
, bindHttps
, httpsAcceptFunc
, sendFileFunc
) where
------------------------------------------------------------------------------
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import Data.Typeable (Typeable)
import Network.Socket (Socket)
#ifdef OPENSSL
import Control.Exception (Exception, bracketOnError, finally, onException, throwIO)
import Control.Monad (when)
import Data.ByteString.Builder (byteString)
import qualified Network.Socket as Socket
import OpenSSL (withOpenSSL)
import OpenSSL.Session (SSL, SSLContext)
import qualified OpenSSL.Session as SSL
import Prelude (Bool, FilePath, IO, Int, Maybe (..), Monad (..), Show, flip, fromIntegral, fst, not, ($), ($!), (.))
import Snap.Internal.Http.Server.Address (getAddress, getSockAddr)
import Snap.Internal.Http.Server.Socket (acceptAndInitialize)
import qualified System.IO.Streams as Streams
import qualified System.IO.Streams.SSL as SStreams
#else
import Control.Exception (Exception, throwIO)
import Prelude (Bool, FilePath, IO, Int, Show, id, ($))
#endif
------------------------------------------------------------------------------
import Snap.Internal.Http.Server.Types (AcceptFunc (..), SendFileHandler)
------------------------------------------------------------------------------
data TLSException = TLSException S.ByteString
deriving (Show, Typeable)
instance Exception TLSException
#ifndef OPENSSL
type SSLContext = ()
type SSL = ()
------------------------------------------------------------------------------
sslNotSupportedException :: TLSException
sslNotSupportedException = TLSException $ S.concat [
"This version of snap-server was not built with SSL "
, "support.\n"
, "Please compile snap-server with -fopenssl to enable it."
]
------------------------------------------------------------------------------
withTLS :: IO a -> IO a
withTLS = id
------------------------------------------------------------------------------
barf :: IO a
barf = throwIO sslNotSupportedException
------------------------------------------------------------------------------
bindHttps :: ByteString -> Int -> FilePath -> Bool -> FilePath
-> IO (Socket, SSLContext)
bindHttps _ _ _ _ _ = barf
------------------------------------------------------------------------------
httpsAcceptFunc :: Socket -> SSLContext -> AcceptFunc
httpsAcceptFunc _ _ = AcceptFunc $ \restore -> restore barf
------------------------------------------------------------------------------
sendFileFunc :: SSL -> Socket -> SendFileHandler
sendFileFunc _ _ _ _ _ _ _ = barf
#else
------------------------------------------------------------------------------
withTLS :: IO a -> IO a
withTLS = withOpenSSL
------------------------------------------------------------------------------
bindHttps :: ByteString
-> Int
-> FilePath
-> Bool
-> FilePath
-> IO (Socket, SSLContext)
bindHttps bindAddress bindPort cert chainCert key =
withTLS $
bracketOnError
(do (family, addr) <- getSockAddr bindPort bindAddress
sock <- Socket.socket family Socket.Stream 0
return (sock, addr)
)
(Socket.close . fst)
$ \(sock, addr) -> do
Socket.setSocketOption sock Socket.ReuseAddr 1
Socket.bindSocket sock addr
Socket.listen sock 150
ctx <- SSL.context
SSL.contextSetPrivateKeyFile ctx key
if chainCert
then SSL.contextSetCertificateChainFile ctx cert
else SSL.contextSetCertificateFile ctx cert
certOK <- SSL.contextCheckPrivateKey ctx
when (not certOK) $ do
throwIO $ TLSException certificateError
return (sock, ctx)
where
certificateError =
"OpenSSL says that the certificate doesn't match the private key!"
------------------------------------------------------------------------------
httpsAcceptFunc :: Socket
-> SSLContext
-> AcceptFunc
httpsAcceptFunc boundSocket ctx =
AcceptFunc $ \restore ->
acceptAndInitialize boundSocket restore $ \(sock, remoteAddr) -> do
localAddr <- Socket.getSocketName sock
(localPort, localHost) <- getAddress localAddr
(remotePort, remoteHost) <- getAddress remoteAddr
ssl <- restore (SSL.connection ctx sock)
restore (SSL.accept ssl) `onException` Socket.close sock
(readEnd, writeEnd) <- SStreams.sslToStreams ssl
let cleanup = (do Streams.write Nothing writeEnd
SSL.shutdown ssl $! SSL.Unidirectional)
`finally` Socket.close sock
return $! ( sendFileFunc ssl
, localHost
, localPort
, remoteHost
, remotePort
, readEnd
, writeEnd
, cleanup
)
------------------------------------------------------------------------------
sendFileFunc :: SSL -> SendFileHandler
sendFileFunc ssl buffer builder fPath offset nbytes = do
Streams.unsafeWithFileAsInputStartingAt (fromIntegral offset) fPath $ \fileInput0 -> do
fileInput <- Streams.takeBytes (fromIntegral nbytes) fileInput0 >>=
Streams.map byteString
input <- Streams.fromList [builder] >>=
flip Streams.appendInputStream fileInput
output <- Streams.makeOutputStream sendChunk >>=
Streams.unsafeBuilderStream (return buffer)
Streams.supply input output
Streams.write Nothing output
where
sendChunk (Just s) = SSL.write ssl s
sendChunk Nothing = return $! ()
#endif
| 23Skidoo/snap-server | src/Snap/Internal/Http/Server/TLS.hs | bsd-3-clause | 6,551 | 0 | 11 | 1,812 | 526 | 331 | 195 | 38 | 1 |
{-# OPTIONS -fglasgow-exts #-}
{-# OPTIONS -fallow-overlapping-instances #-}
{-# OPTIONS -fallow-incoherent-instances #-}
{-
Built in functions provided by 'host'
-}
module HJS.Interpreter.Host where
import HJS.Interpreter.InterpMDecl
import HJS.Interpreter.InterpM
import HJS.Interpreter.Interp
import HJS.Interpreter.ObjectBasic
import HJS.Interpreter.Object
import HJS.Interpreter.Array
import HJS.Interpreter.Function
import HJS.Interpreter.Error
import HJS.Interpreter.String
import HJS.Interpreter.Regex
import Control.Monad.State
globalObj = ObjId 1
objPrototype = ObjId 2
print' :: InterpM Value
print' = do
args' <- getArgs
op <- getProperty globalObj "_output"
args <- mapM toRealString args'
op' <- toRealString op
let
prefix = if isUndefined op then "" else (op' ++ "\n")
s = concat (prefix:args)
putProperty globalObj "_output" (inj s)
return (inj Undefined)
print'' :: InterpM Value
print'' = do
args' <- getArgs
op <- getProperty globalObj "_output"
args <- mapM toRealString args'
liftIO $ putStrLn $ concat args
return undefinedValue
putBuiltIn :: ObjId -> String -> [String] -> InterpM Value -> InterpM ()
putBuiltIn obj name args f = do
fo <- newBuiltInFunction args f
putProperty obj name (inj fo)
objectConstructor :: InterpM Value
objectConstructor = do
o <- newObject "Object"
return $ inj o
newClassObject name = do
obj <- newObject "Object"
putProperty globalObj name (inj obj)
fo <- newBuiltInFunction [] objectConstructor
o <- newObject "Object"
putProperty obj "prototype" (inj o)
putProperty obj "Construct" (inj fo)
constructorConstructor :: InterpM Value
constructorConstructor = defaultConstructor "Object"
--objectWithClassConstructor klass = do
-- o <- newObject klass
-- (((_,_,t):_), _) <- get
-- args <- getArgs
-- p <- getProperty t "prototype"
-- putObjectProperty o "__proto__" p
-- return $ inj o
-- Creates a new constructor with supplied constructor
newConstructorWith :: String -> InterpM Value -> InterpM ObjId
newConstructorWith name c = do
fo <- newFuncObject [] [] c
putObjectProperty fo "name" (inj name)
putObjectProperty globalObj name (inj fo)
return fo
-- Creates a new constructor
newConstructor name = do
fo <- newFuncObject [] [] (defaultConstructor name)
putObjectProperty fo "name" (inj name)
putObjectProperty globalObj name (inj fo)
return fo
addBuiltIn :: InterpM ()
addBuiltIn = do
fo <- newBuiltInFunction ["arg1"] print''
putProperty globalObj "print" (inj fo)
addObjectBuiltIn newConstructor putBuiltIn
addFunctionBuiltIn newConstructor putBuiltIn callFunction
addErrorBuiltIn newConstructorWith putBuiltIn
addArrayBuiltIn newConstructorWith putBuiltIn
addStringBuiltIn newConstructorWith
addRegexBuiltIn newConstructorWith putBuiltIn
return ()
initEnvironment = do
go <- newObjectRaw "global"
op <- newObjectRaw "Object"
putPropertyInternal go "__proto__" (inj op)
putPropertyInternal op "__parent__" (inj go)
pushContext ([go],go,go, ObjIdNull)
addBuiltIn
| disnet/jscheck | src/HJS/Interpreter/Host.hs | bsd-3-clause | 3,987 | 6 | 12 | 1,442 | 825 | 405 | 420 | 81 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
-- | Tests on individual query combinators.
module Database.DSH.Tests.CombinatorTests
( typeTests
, booleanTests
, tupleTests
, numericTests
, maybeTests
, eitherTests
, listTests
, liftedTests
, distTests
, hunitCombinatorTests
, otherTests
) where
import qualified Data.Decimal as D
import Data.Either
import Data.List
import Data.Maybe
import qualified Data.Scientific as S
import Data.Text (Text)
import qualified Data.Time.Calendar as C
import Data.Word
import GHC.Exts
import Test.QuickCheck
import Test.Tasty
import qualified Test.Tasty.HUnit as TH
import qualified Database.DSH as Q
import Database.DSH.Backend
import Database.DSH.Common.VectorLang
import Database.DSH.Compiler
import Database.DSH.Tests.Common
{-# ANN module "HLint: ignore Use camelCase" #-}
{-# ANN module "HLint: ignore Avoid lambda" #-}
{-
data D0 = C01 deriving (Eq,Ord,Show)
derive makeArbitrary ''D0
Q.deriveDSH ''D0
data D1 a = C11 a deriving (Eq,Ord,Show)
derive makeArbitrary ''D1
Q.deriveDSH ''D1
data D2 a b = C21 a b b a deriving (Eq,Ord,Show)
derive makeArbitrary ''D2
Q.deriveDSH ''D2
data D3 = C31
| C32
deriving (Eq,Ord,Show)
derive makeArbitrary ''D3
Q.deriveDSH ''D3
data D4 a = C41 a
| C42
deriving (Eq,Ord,Show)
derive makeArbitrary ''D4
Q.deriveDSH ''D4
data D5 a = C51 a
| C52
| C53 a a
| C54 a a a
deriving (Eq,Ord,Show)
derive makeArbitrary ''D5
Q.deriveDSH ''D5
data D6 a b c d e = C61 { c611 :: a, c612 :: (a,b,c,d) }
| C62
| C63 a b
| C64 (a,b,c)
| C65 a b c d e
deriving (Eq,Ord,Show)
derive makeArbitrary ''D6
Q.deriveDSH ''D6
-}
typeTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
typeTests codeGen conn = testGroup "Supported Types"
[ testPropertyConn codeGen conn "()" prop_unit
, testPropertyConn codeGen conn "Bool" prop_bool
, testPropertyConn codeGen conn "Char" prop_char
, testPropertyConn codeGen conn "Text" prop_text
, testPropertyConn codeGen conn "Day" prop_day
, testPropertyConn codeGen conn "Decimal" prop_decimal
, testPropertyConn codeGen conn "Scientific" prop_scientific
, testPropertyConn codeGen conn "Integer" prop_integer
, testPropertyConn codeGen conn "Double" prop_double
, testPropertyConn codeGen conn "[Integer]" prop_list_integer_1
, testPropertyConn codeGen conn "[[Integer]]" prop_list_integer_2
, testPropertyConn codeGen conn "[[[Integer]]]" prop_list_integer_3
, testPropertyConn codeGen conn "[(Integer, Integer)]" prop_list_tuple_integer
, testPropertyConn codeGen conn "([], [])" prop_tuple_list_integer2
, testPropertyConn codeGen conn "([], [], [])" prop_tuple_list_integer3
, testPropertyConn codeGen conn "(,[])" prop_tuple_integer_list
, testPropertyConn codeGen conn "(,[],)" prop_tuple_integer_list_integer
, testPropertyConn codeGen conn "Maybe Integer" prop_maybe_integer
, testPropertyConn codeGen conn "Either Integer Integer" prop_either_integer
, testPropertyConn codeGen conn "(Int, Int, Int, Int)" prop_tuple4
, testPropertyConn codeGen conn "(Int, Int, Int, Int, Int)" prop_tuple5
{-
, testProperty "D0" $ prop_d0
, testProperty "D1" $ prop_d1
, testProperty "D2" $ prop_d2
, testProperty "D3" $ prop_d3
, testProperty "D4" $ prop_d4
, testProperty "D5" $ prop_d5
, testProperty "D6" $ prop_d6
-}
]
booleanTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
booleanTests codeGen conn = testGroup "Equality, Boolean Logic and Ordering"
[ testPropertyConn codeGen conn "&&" prop_infix_and
, testPropertyConn codeGen conn "||" prop_infix_or
, testPropertyConn codeGen conn "not" prop_not
, testPropertyConn codeGen conn "eq" prop_eq
, testPropertyConn codeGen conn "neq" prop_neq
, testPropertyConn codeGen conn "cond" prop_cond
, testPropertyConn codeGen conn "cond tuples" prop_cond_tuples
, testPropertyConn codeGen conn "cond ([[Integer]], [[Integer]])" prop_cond_list_tuples
, testPropertyConn codeGen conn "lt" prop_lt
, testPropertyConn codeGen conn "lte" prop_lte
, testPropertyConn codeGen conn "gt" prop_gt
, testPropertyConn codeGen conn "gte" prop_gte
, testPropertyConn codeGen conn "min_integer" prop_min_integer
, testPropertyConn codeGen conn "min_double" prop_min_double
, testPropertyConn codeGen conn "max_integer" prop_max_integer
, testPropertyConn codeGen conn "max_double" prop_max_double
]
tupleTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
tupleTests codeGen conn = testGroup "Tuples"
[ testPropertyConn codeGen conn "fst" prop_fst
, testPropertyConn codeGen conn "snd" prop_snd
, testPropertyConn codeGen conn "fst ([], [])" prop_fst_nested
, testPropertyConn codeGen conn "snd ([], [])" prop_snd_nested
, testPropertyConn codeGen conn "tup3_1" prop_tup3_1
, testPropertyConn codeGen conn "tup3_2" prop_tup3_2
, testPropertyConn codeGen conn "tup3_3" prop_tup3_3
, testPropertyConn codeGen conn "tup4_2" prop_tup4_2
, testPropertyConn codeGen conn "tup4_4" prop_tup4_4
, testPropertyConn codeGen conn "tup3_nested" prop_tup3_nested
, testPropertyConn codeGen conn "tup4_tup3" prop_tup4_tup3
, testPropertyConn codeGen conn "agg tuple" prop_agg_tuple
]
numericTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
numericTests codeGen conn = testGroup "Numerics"
[ testPropertyConn codeGen conn "add_integer" prop_add_integer
, testPropertyConn codeGen conn "add_integer_sums" prop_add_integer_sums
, testPropertyConn codeGen conn "add_double" prop_add_double
, testPropertyConn codeGen conn "mul_integer" prop_mul_integer
, testPropertyConn codeGen conn "mul_double" prop_mul_double
, testPropertyConn codeGen conn "div_double" prop_div_double
, testPropertyConn codeGen conn "integer_to_double" prop_integer_to_double
, testPropertyConn codeGen conn "integer_to_double_+" prop_integer_to_double_arith
, testPropertyConn codeGen conn "abs_integer" prop_abs_integer
, testPropertyConn codeGen conn "abs_double" prop_abs_double
, testPropertyConn codeGen conn "signum_integer" prop_signum_integer
, testPropertyConn codeGen conn "signum_double" prop_signum_double
, testPropertyConn codeGen conn "negate_integer" prop_negate_integer
, testPropertyConn codeGen conn "negate_double" prop_negate_double
, testPropertyConn codeGen conn "trig_sin" prop_trig_sin
, testPropertyConn codeGen conn "trig_cos" prop_trig_cos
, testPropertyConn codeGen conn "trig_tan" prop_trig_tan
, testPropertyConn codeGen conn "trig_asin" prop_trig_asin
, testPropertyConn codeGen conn "trig_acos" prop_trig_acos
, testPropertyConn codeGen conn "trig_atan" prop_trig_atan
, testPropertyConn codeGen conn "sqrt" prop_sqrt
, testPropertyConn codeGen conn "log" prop_log
, testPropertyConn codeGen conn "exp" prop_exp
, testPropertyConn codeGen conn "rem" prop_rem
]
maybeTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
maybeTests codeGen conn = testGroup "Maybe"
[ testPropertyConn codeGen conn "maybe" prop_maybe
, testPropertyConn codeGen conn "just" prop_just
, testPropertyConn codeGen conn "isJust" prop_isJust
, testPropertyConn codeGen conn "isNothing" prop_isNothing
, testPropertyConn codeGen conn "fromJust" prop_fromJust
, testPropertyConn codeGen conn "fromMaybe" prop_fromMaybe
, testPropertyConn codeGen conn "listToMaybe" prop_listToMaybe
, testPropertyConn codeGen conn "maybeToList" prop_maybeToList
, testPropertyConn codeGen conn "catMaybes" prop_catMaybes
, testPropertyConn codeGen conn "mapMaybe" prop_mapMaybe
]
eitherTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
eitherTests codeGen conn = testGroup "Either"
[ testPropertyConn codeGen conn "left" prop_left
, testPropertyConn codeGen conn "right" prop_right
, testPropertyConn codeGen conn "isLeft" prop_isLeft
, testPropertyConn codeGen conn "isRight" prop_isRight
, testPropertyConn codeGen conn "either" prop_either
, testPropertyConn codeGen conn "lefts" prop_lefts
, testPropertyConn codeGen conn "rights" prop_rights
, testPropertyConn codeGen conn "partitionEithers" prop_partitionEithers
]
listTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
listTests codeGen conn = testGroup "Lists"
[ testPropertyConn codeGen conn "singleton" prop_singleton
, testPropertyConn codeGen conn "head" prop_head
, testPropertyConn codeGen conn "tail" prop_tail
, testPropertyConn codeGen conn "cons" prop_cons
, testPropertyConn codeGen conn "snoc" prop_snoc
, testPropertyConn codeGen conn "take" prop_take
, testPropertyConn codeGen conn "drop" prop_drop
, testPropertyConn codeGen conn "take ++ drop" prop_takedrop
, testPropertyConn codeGen conn "map" prop_map
, testPropertyConn codeGen conn "filter" prop_filter
, testPropertyConn codeGen conn "filter > 42" prop_filter_gt
, testPropertyConn codeGen conn "filter > 42 (,[])" prop_filter_gt_nested
, testPropertyConn codeGen conn "the" prop_the
, testPropertyConn codeGen conn "last" prop_last
, testPropertyConn codeGen conn "init" prop_init
, testPropertyConn codeGen conn "null" prop_null
, testPropertyConn codeGen conn "length" prop_length
, testPropertyConn codeGen conn "length tuple list" prop_length_tuple
, testPropertyConn codeGen conn "index [Integer]" prop_index
, testPropertyConn codeGen conn "index [(Integer, [Integer])]" prop_index_pair
, testPropertyConn codeGen conn "index [[]]" prop_index_nest
, testPropertyConn codeGen conn "reverse" prop_reverse
, testPropertyConn codeGen conn "reverse [[]]" prop_reverse_nest
, testPropertyConn codeGen conn "append" prop_append
, testPropertyConn codeGen conn "append nest" prop_append_nest
, testPropertyConn codeGen conn "groupWith" prop_groupWith
, testPropertyConn codeGen conn "groupWithKey" prop_groupWithKey
, testPropertyConn codeGen conn "groupWith length" prop_groupWith_length
, testPropertyConn codeGen conn "groupWithKey length" prop_groupWithKey_length
, testPropertyConn codeGen conn "groupWith length nested" prop_groupWith_length_nest
, testPropertyConn codeGen conn "groupWithKey length nested" prop_groupWithKey_length_nest
, testPropertyConn codeGen conn "groupagg sum" prop_groupagg_sum
, testPropertyConn codeGen conn "groupagg (sum, length)" prop_groupagg_sum_length
, testPropertyConn codeGen conn "groupagg key (sum, length)" prop_groupaggkey_sum_length
, testPropertyConn codeGen conn "groupagg (sum, length, max)" prop_groupagg_sum_length_max
, testPropertyConn codeGen conn "groupagg key sum" prop_groupaggkey_sum
, testPropertyConn codeGen conn "groupagg sum exp" prop_groupagg_sum_exp
, testPropertyConn codeGen conn "groupagg length" prop_groupagg_length
, testPropertyConn codeGen conn "groupagg minimum" prop_groupagg_minimum
, testPropertyConn codeGen conn "groupagg maximum" prop_groupagg_maximum
, testPropertyConn codeGen conn "groupagg avg" prop_groupagg_avg
, testPropertyConn codeGen conn "sortWith" prop_sortWith
, testPropertyConn codeGen conn "sortWith [(,)]" prop_sortWith_pair
, testPropertyConn codeGen conn "sortWith [(Char,)]" prop_sortWith_pair_stable
, testPropertyConn codeGen conn "sortWith [(,[])]" prop_sortWith_nest
, testPropertyConn codeGen conn "Sortwith length nested" prop_sortWith_length_nest
, testPropertyConn codeGen conn "and" prop_and
, testPropertyConn codeGen conn "or" prop_or
, testPropertyConn codeGen conn "any_zero" prop_any_zero
, testPropertyConn codeGen conn "all_zero" prop_all_zero
, testPropertyConn codeGen conn "sum_integer" prop_sum_integer
, testPropertyConn codeGen conn "sum_double" prop_sum_double
, testPropertyConn codeGen conn "avg_double" prop_avg_double
, testPropertyConn codeGen conn "concat" prop_concat
, testPropertyConn codeGen conn "concatMap" prop_concatMap
, testPropertyConn codeGen conn "maximum" prop_maximum
, testPropertyConn codeGen conn "minimum" prop_minimum
, testPropertyConn codeGen conn "splitAt" prop_splitAt
, testPropertyConn codeGen conn "takeWhile" prop_takeWhile
, testPropertyConn codeGen conn "dropWhile" prop_dropWhile
, testPropertyConn codeGen conn "span" prop_span
, testPropertyConn codeGen conn "break" prop_break
, testPropertyConn codeGen conn "elem" prop_elem
, testPropertyConn codeGen conn "notElem" prop_notElem
, testPropertyConn codeGen conn "lookup" prop_lookup
, testPropertyConn codeGen conn "zip" prop_zip
, testPropertyConn codeGen conn "zip tuple1" prop_zip_tuple1
, testPropertyConn codeGen conn "zip tuple2" prop_zip_tuple2
, testPropertyConn codeGen conn "zip nested" prop_zip_nested
, testPropertyConn codeGen conn "zip3" prop_zip3
, testPropertyConn codeGen conn "zipWith" prop_zipWith
, testPropertyConn codeGen conn "zipWith3" prop_zipWith3
, testPropertyConn codeGen conn "unzip" prop_unzip
, testPropertyConn codeGen conn "unzip3" prop_unzip3
, testPropertyConn codeGen conn "nub" prop_nub
, testPropertyConn codeGen conn "number" prop_number
]
liftedTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
liftedTests codeGen conn = testGroup "Lifted operations"
[ testPropertyConn codeGen conn "Lifted &&" prop_infix_map_and
, testPropertyConn codeGen conn "Lifted ||" prop_infix_map_or
, testPropertyConn codeGen conn "Lifted not" prop_map_not
, testPropertyConn codeGen conn "Lifted eq" prop_map_eq
, testPropertyConn codeGen conn "Lifted neq" prop_map_neq
, testPropertyConn codeGen conn "Lifted cond" prop_map_cond
, testPropertyConn codeGen conn "Lifted cond tuples" prop_map_cond_tuples
, testPropertyConn codeGen conn "Lifted cond + concat" prop_concatmapcond
, testPropertyConn codeGen conn "Lifted lt" prop_map_lt
, testPropertyConn codeGen conn "Lifted lte" prop_map_lte
, testPropertyConn codeGen conn "Lifted gt" prop_map_gt
, testPropertyConn codeGen conn "Lifted gte" prop_map_gte
, testPropertyConn codeGen conn "Lifted cons" prop_map_cons
, testPropertyConn codeGen conn "Lifted concat" prop_map_concat
, testPropertyConn codeGen conn "Lifted concat 2" prop_map_concat2
, testPropertyConn codeGen conn "Lifted fst" prop_map_fst
, testPropertyConn codeGen conn "Lifted snd" prop_map_snd
, testPropertyConn codeGen conn "Lifted the" prop_map_the
, testPropertyConn codeGen conn "map (map (*2))" prop_map_map_mul
, testPropertyConn codeGen conn "map (map (map (*2)))" prop_map_map_map_mul
, testPropertyConn codeGen conn "map (\\x -> map (\\y -> x + y) ..) .." prop_map_map_add
, testPropertyConn codeGen conn "map groupWith" prop_map_groupWith
, testPropertyConn codeGen conn "map groupWith rem 10" prop_map_groupWith_rem
, testPropertyConn codeGen conn "map groupWithKey" prop_map_groupWithKey
, testPropertyConn codeGen conn "map groupagg (sum, length)" prop_map_groupagg_sum_length
, testPropertyConn codeGen conn "map groupagg key (sum, length)" prop_map_groupaggkey_sum_length
, testPropertyConn codeGen conn "map groupagg (sum, length, max)" prop_map_groupagg_sum_length_max
, testPropertyConn codeGen conn "map groupagg sum" prop_map_groupagg_sum
, testPropertyConn codeGen conn "map groupagg key sum" prop_map_groupaggkey_sum
, testPropertyConn codeGen conn "map groupagg sum exp" prop_map_groupagg_sum_exp
, testPropertyConn codeGen conn "map groupagg length" prop_map_groupagg_length
, testPropertyConn codeGen conn "map groupagg minimum" prop_map_groupagg_minimum
, testPropertyConn codeGen conn "map groupagg maximum" prop_map_groupagg_maximum
, testPropertyConn codeGen conn "Lifted sortWith" prop_map_sortWith
, testPropertyConn codeGen conn "Lifted sortWith [(,)]" prop_map_sortWith_pair
, testPropertyConn codeGen conn "Lifted sortWith [(,[])]" prop_map_sortWith_nest
, testPropertyConn codeGen conn "Lifted sortWith length" prop_map_sortWith_length
, testPropertyConn codeGen conn "Lifted groupWith length" prop_map_groupWith_length
, testPropertyConn codeGen conn "Lifted groupWithKey length" prop_map_groupWithKey_length
, testPropertyConn codeGen conn "Lifted length" prop_map_length
, testPropertyConn codeGen conn "Lifted length on [[(a,b)]]" prop_map_length_tuple
, testPropertyConn codeGen conn "Lift minimum" prop_map_minimum
, testPropertyConn codeGen conn "map (map minimum)" prop_map_map_minimum
, testPropertyConn codeGen conn "Lift maximum" prop_map_maximum
, testPropertyConn codeGen conn "map (map maximum)" prop_map_map_maximum
, testPropertyConn codeGen conn "map integer_to_double" prop_map_integer_to_double
, testPropertyConn codeGen conn "map tail" prop_map_tail
, testPropertyConn codeGen conn "map unzip" prop_map_unzip
, testPropertyConn codeGen conn "map reverse" prop_map_reverse
, testPropertyConn codeGen conn "map reverse [[]]" prop_map_reverse_nest
, testPropertyConn codeGen conn "map and" prop_map_and
, testPropertyConn codeGen conn "map (map and)" prop_map_map_and
, testPropertyConn codeGen conn "map sum" prop_map_sum
, testPropertyConn codeGen conn "map avg" prop_map_avg
, testPropertyConn codeGen conn "map (map sum)" prop_map_map_sum
, testPropertyConn codeGen conn "map or" prop_map_or
, testPropertyConn codeGen conn "map (map or)" prop_map_map_or
, testPropertyConn codeGen conn "map any zero" prop_map_any_zero
, testPropertyConn codeGen conn "map all zero" prop_map_all_zero
, testPropertyConn codeGen conn "map filter" prop_map_filter
, testPropertyConn codeGen conn "map filter > 42" prop_map_filter_gt
, testPropertyConn codeGen conn "map filter > 42 (,[])" prop_map_filter_gt_nested
, testPropertyConn codeGen conn "map append" prop_map_append
, testPropertyConn codeGen conn "map index" prop_map_index
, testPropertyConn codeGen conn "map index2" prop_map_index2
, testPropertyConn codeGen conn "map index [[]]" prop_map_index_nest
, testPropertyConn codeGen conn "map init" prop_map_init
, testPropertyConn codeGen conn "map last" prop_map_last
, testPropertyConn codeGen conn "map null" prop_map_null
, testPropertyConn codeGen conn "map nub" prop_map_nub
, testPropertyConn codeGen conn "map snoc" prop_map_snoc
, testPropertyConn codeGen conn "map take" prop_map_take
, testPropertyConn codeGen conn "map drop" prop_map_drop
, testPropertyConn codeGen conn "map zip" prop_map_zip
, testPropertyConn codeGen conn "map takeWhile" prop_map_takeWhile
, testPropertyConn codeGen conn "map dropWhile" prop_map_dropWhile
, testPropertyConn codeGen conn "map span" prop_map_span
, testPropertyConn codeGen conn "map break" prop_map_break
, testPropertyConn codeGen conn "map number" prop_map_number
, testPropertyConn codeGen conn "map sin" prop_map_trig_sin
, testPropertyConn codeGen conn "map cos" prop_map_trig_cos
, testPropertyConn codeGen conn "map tan" prop_map_trig_tan
, testPropertyConn codeGen conn "map asin" prop_map_trig_asin
, testPropertyConn codeGen conn "map acos" prop_map_trig_acos
, testPropertyConn codeGen conn "map atan" prop_map_trig_atan
, testPropertyConn codeGen conn "map log" prop_map_log
, testPropertyConn codeGen conn "map exp" prop_map_exp
, testPropertyConn codeGen conn "map sqrt" prop_map_sqrt
, testPropertyConn codeGen conn "map rem" prop_map_rem
]
distTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
distTests codeGen conn = testGroup "Value replication"
[ testPropertyConn codeGen conn "dist scalar" prop_dist_scalar
, testPropertyConn codeGen conn "dist list1" prop_dist_list1
, testPropertyConn codeGen conn "dist list2" prop_dist_list2
, TH.testCase "dist lift" (test_dist_lift codeGen conn)
]
otherTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
otherTests codeGen conn = testGroup "Combinations of operators"
[ testPropertyConn codeGen conn "map elem + sort" prop_elem_sort
, testPropertyConn codeGen conn "filter elem + sort" prop_elem_sort2
, testPropertyConn codeGen conn "length . nub" prop_nub_length
, testPropertyConn codeGen conn "map (length . nub)" prop_map_nub_length
]
hunitCombinatorTests :: (BackendVector b, VectorLang v) => DSHTestTree (v TExpr TExpr) b
hunitCombinatorTests codeGen conn = testGroup "HUnit combinators"
[ TH.testCase "hnegative_sum" (hnegative_sum codeGen conn)
, TH.testCase "hnegative_map_sum" (hnegative_map_sum codeGen conn)
]
-- * Supported Types
prop_unit :: (BackendVector b, VectorLang v) => () -> DSHProperty (v TExpr TExpr) b
prop_unit = makePropEq id id
prop_bool :: (BackendVector b, VectorLang v) => Bool -> DSHProperty (v TExpr TExpr) b
prop_bool = makePropEq id id
prop_integer :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_integer = makePropEq id id
prop_double :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_double d = makePropDouble id id (getFixed d)
prop_char :: (BackendVector b, VectorLang v) => Char -> DSHProperty (v TExpr TExpr) b
prop_char c codeGen conn = c /= '\0' ==> makePropEq id id c codeGen conn
prop_text :: (BackendVector b, VectorLang v) => Text -> DSHProperty (v TExpr TExpr) b
prop_text t = makePropEq id id (filterNullChar t)
prop_day :: (BackendVector b, VectorLang v) => C.Day -> DSHProperty (v TExpr TExpr) b
prop_day = makePropEq id id
prop_decimal :: (BackendVector b, VectorLang v) => (Positive Word8, Integer) -> DSHProperty (v TExpr TExpr) b
prop_decimal (p, m) = makePropEq id id (D.Decimal (getPositive p) m)
prop_scientific :: (BackendVector b, VectorLang v) => (Integer, Int) -> DSHProperty (v TExpr TExpr) b
prop_scientific (p, m) = makePropEq id id (S.scientific p m)
prop_list_integer_1 :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_list_integer_1 = makePropEq id id
prop_list_integer_2 :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_list_integer_2 = makePropEq id id
prop_list_integer_3 :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_list_integer_3 = makePropEq id id
prop_list_tuple_integer :: (BackendVector b, VectorLang v) => [(Integer, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_list_tuple_integer = makePropEq id id
prop_maybe_integer :: (BackendVector b, VectorLang v) => Maybe Integer -> DSHProperty (v TExpr TExpr) b
prop_maybe_integer = makePropEq id id
prop_tuple_list_integer2 :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_tuple_list_integer2 = makePropEq id id
prop_tuple_list_integer3 :: (BackendVector b, VectorLang v) => ([Integer], [Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_tuple_list_integer3 = makePropEq id id
prop_tuple_integer_list :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_tuple_integer_list = makePropEq id id
prop_tuple_integer_list_integer :: (BackendVector b, VectorLang v) => (Integer, [Integer], Integer) -> DSHProperty (v TExpr TExpr) b
prop_tuple_integer_list_integer = makePropEq id id
prop_either_integer :: (BackendVector b, VectorLang v) => Either Integer Integer -> DSHProperty (v TExpr TExpr) b
prop_either_integer = makePropEq id id
prop_tuple4 :: (BackendVector b, VectorLang v) => [(Integer, Integer, Integer, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_tuple4 = makePropEq (Q.map (\(Q.view -> (a, b, c, d)) -> Q.tup4 (a + c) (b - d) b d))
(map (\(a, b, c, d) -> (a + c, b - d, b, d)))
prop_tuple5 :: (BackendVector b, VectorLang v) => [(Integer, Integer, Integer, Integer, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_tuple5 = makePropEq (Q.map (\(Q.view -> (a, _, c, _, e)) -> Q.tup3 a c e))
(map (\(a, _, c, _, e) -> (a, c, e)))
-- {-
-- prop_d0 :: (BackendVector b, VectorLang v) => D0 -> DSHProperty (v TExpr TExpr) b
-- prop_d0 = makePropEq id id
-- prop_d1 :: (BackendVector b, VectorLang v) => D1 Integer -> DSHProperty (v TExpr TExpr) b
-- prop_d1 = makePropEq id id
-- prop_d2 :: (BackendVector b, VectorLang v) => D2 Integer Integer -> DSHProperty (v TExpr TExpr) b
-- prop_d2 = makePropEq id id
-- prop_d3 :: (BackendVector b, VectorLang v) => D3 -> DSHProperty (v TExpr TExpr) b
-- prop_d3 = makePropEq id id
-- prop_d4 :: (BackendVector b, VectorLang v) => D4 Integer -> DSHProperty (v TExpr TExpr) b
-- prop_d4 = makePropEq id id
-- prop_d5 :: (BackendVector b, VectorLang v) => D5 Integer -> DSHProperty (v TExpr TExpr) b
-- prop_d5 = makePropEq id id
-- prop_d6 :: (BackendVector b, VectorLang v) => D6 Integer Integer Integer Integer Integer -> DSHProperty (v TExpr TExpr) b
-- prop_d6 = makePropEq id id
-- -}
-- * Equality, Boolean Logic and Ordering
prop_infix_and :: (BackendVector b, VectorLang v) => (Bool,Bool) -> DSHProperty (v TExpr TExpr) b
prop_infix_and = makePropEq (uncurryQ (Q.&&)) (uncurry (&&))
prop_infix_map_and :: (BackendVector b, VectorLang v) => (Bool, [Bool]) -> DSHProperty (v TExpr TExpr) b
prop_infix_map_and = makePropEq (\x -> Q.map (Q.fst x Q.&&) $ Q.snd x) (\(x,xs) -> map (x &&) xs)
prop_infix_or :: (BackendVector b, VectorLang v) => (Bool,Bool) -> DSHProperty (v TExpr TExpr) b
prop_infix_or = makePropEq (uncurryQ (Q.||)) (uncurry (||))
prop_infix_map_or :: (BackendVector b, VectorLang v) => (Bool, [Bool]) -> DSHProperty (v TExpr TExpr) b
prop_infix_map_or = makePropEq (\x -> Q.map (Q.fst x Q.||) $ Q.snd x) (\(x,xs) -> map (x ||) xs)
prop_not :: (BackendVector b, VectorLang v) => Bool -> DSHProperty (v TExpr TExpr) b
prop_not = makePropEq Q.not not
prop_map_not :: (BackendVector b, VectorLang v) => [Bool] -> DSHProperty (v TExpr TExpr) b
prop_map_not = makePropEq (Q.map Q.not) (map not)
prop_eq :: (BackendVector b, VectorLang v) => (Integer,Integer) -> DSHProperty (v TExpr TExpr) b
prop_eq = makePropEq (uncurryQ (Q.==)) (uncurry (==))
prop_map_eq :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_eq = makePropEq (\x -> Q.map (Q.fst x Q.==) $ Q.snd x) (\(x,xs) -> map (x ==) xs)
prop_neq :: (BackendVector b, VectorLang v) => (Integer,Integer) -> DSHProperty (v TExpr TExpr) b
prop_neq = makePropEq (uncurryQ (Q./=)) (uncurry (/=))
prop_map_neq :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_neq = makePropEq (\x -> Q.map (Q.fst x Q./=) $ Q.snd x) (\(x,xs) -> map (x /=) xs)
prop_cond :: (BackendVector b, VectorLang v) => Bool -> DSHProperty (v TExpr TExpr) b
prop_cond = makePropEq (\b -> Q.cond b 0 1) (\b -> if b then (0 :: Integer) else 1)
prop_cond_tuples :: (BackendVector b, VectorLang v) => (Bool, (Integer, Integer)) -> DSHProperty (v TExpr TExpr) b
prop_cond_tuples = makePropEq (\b -> Q.cond (Q.fst b)
(Q.pair (Q.fst $ Q.snd b) (Q.fst $ Q.snd b))
(Q.pair (Q.snd $ Q.snd b) (Q.snd $ Q.snd b)))
(\b -> if fst b
then (fst $ snd b, fst $ snd b)
else (snd $ snd b, snd $ snd b))
prop_cond_list_tuples :: (BackendVector b, VectorLang v) => (Bool, ([[Integer]], [[Integer]])) -> DSHProperty (v TExpr TExpr) b
prop_cond_list_tuples = makePropEq (\b -> Q.cond (Q.fst b)
(Q.pair (Q.fst $ Q.snd b) (Q.fst $ Q.snd b))
(Q.pair (Q.snd $ Q.snd b) (Q.snd $ Q.snd b)))
(\b -> if fst b
then (fst $ snd b, fst $ snd b)
else (snd $ snd b, snd $ snd b))
prop_map_cond :: (BackendVector b, VectorLang v) => [Bool] -> DSHProperty (v TExpr TExpr) b
prop_map_cond = makePropEq (Q.map (\b -> Q.cond b (0 :: Q.Q Integer) 1))
(map (\b -> if b then 0 else 1))
prop_map_cond_tuples :: (BackendVector b, VectorLang v) => [Bool] -> DSHProperty (v TExpr TExpr) b
prop_map_cond_tuples = makePropEq (Q.map (\b -> Q.cond b
(Q.toQ (0, 10) :: Q.Q (Integer, Integer))
(Q.toQ (1, 11))))
(map (\b -> if b
then (0, 10)
else (1, 11)))
prop_concatmapcond :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_concatmapcond =
makePropEq q n
where q l = Q.concatMap (\x -> Q.cond ((Q.>) x (Q.toQ 0)) (x Q.<| el) el) l
n l = concatMap (\x -> if x > 0 then [x] else []) l
el = Q.toQ []
prop_lt :: (BackendVector b, VectorLang v) => (Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_lt = makePropEq (uncurryQ (Q.<)) (uncurry (<))
prop_map_lt :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_lt = makePropEq (\x -> Q.map (Q.fst x Q.<) $ Q.snd x) (\(x,xs) -> map (x <) xs)
prop_lte :: (BackendVector b, VectorLang v) => (Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_lte = makePropEq (uncurryQ (Q.<=)) (uncurry (<=))
prop_map_lte :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_lte = makePropEq (\x -> Q.map (Q.fst x Q.<=) $ Q.snd x) (\(x,xs) -> map (x <=) xs)
prop_gt :: (BackendVector b, VectorLang v) => (Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_gt = makePropEq (uncurryQ (Q.>)) (uncurry (>))
prop_map_gt :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_gt = makePropEq (\x -> Q.map (Q.fst x Q.>) $ Q.snd x) (\(x,xs) -> map (x >) xs)
prop_gte :: (BackendVector b, VectorLang v) => (Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_gte = makePropEq (uncurryQ (Q.>=)) (uncurry (>=))
prop_map_gte :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_gte = makePropEq (\x -> Q.map (Q.fst x Q.>=) $ Q.snd x) (\(x,xs) -> map (x >=) xs)
prop_min_integer :: (BackendVector b, VectorLang v) => (Integer,Integer) -> DSHProperty (v TExpr TExpr) b
prop_min_integer = makePropEq (uncurryQ Q.min) (uncurry min)
prop_max_integer :: (BackendVector b, VectorLang v) => (Integer,Integer) -> DSHProperty (v TExpr TExpr) b
prop_max_integer = makePropEq (uncurryQ Q.max) (uncurry max)
prop_min_double :: (BackendVector b, VectorLang v) => (Fixed Double, Fixed Double) -> DSHProperty (v TExpr TExpr) b
prop_min_double (d1, d2) = makePropDouble (uncurryQ Q.min) (uncurry min) (getFixed d1, getFixed d2)
prop_max_double :: (BackendVector b, VectorLang v) => (Fixed Double, Fixed Double) -> DSHProperty (v TExpr TExpr) b
prop_max_double (d1, d2) = makePropDouble (uncurryQ Q.max) (uncurry max) (getFixed d1, getFixed d2)
-- * Maybe
prop_maybe :: (BackendVector b, VectorLang v) => (Integer, Maybe Integer) -> DSHProperty (v TExpr TExpr) b
prop_maybe = makePropEq (\a -> Q.maybe (Q.fst a) id (Q.snd a)) (\(i,mi) -> maybe i id mi)
prop_just :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_just = makePropEq Q.just Just
prop_isJust :: (BackendVector b, VectorLang v) => Maybe Integer -> DSHProperty (v TExpr TExpr) b
prop_isJust = makePropEq Q.isJust isJust
prop_isNothing :: (BackendVector b, VectorLang v) => Maybe Integer -> DSHProperty (v TExpr TExpr) b
prop_isNothing = makePropEq Q.isNothing isNothing
prop_fromJust :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_fromJust i = makePropEq Q.fromJust fromJust (Just i)
prop_fromMaybe :: (BackendVector b, VectorLang v) => (Integer,Maybe Integer) -> DSHProperty (v TExpr TExpr) b
prop_fromMaybe = makePropEq (uncurryQ Q.fromMaybe) (uncurry fromMaybe)
prop_listToMaybe :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_listToMaybe = makePropEq Q.listToMaybe listToMaybe
prop_maybeToList :: (BackendVector b, VectorLang v) => Maybe Integer -> DSHProperty (v TExpr TExpr) b
prop_maybeToList = makePropEq Q.maybeToList maybeToList
prop_catMaybes :: (BackendVector b, VectorLang v) => [Maybe Integer] -> DSHProperty (v TExpr TExpr) b
prop_catMaybes = makePropEq Q.catMaybes catMaybes
prop_mapMaybe :: (BackendVector b, VectorLang v) => [Maybe Integer] -> DSHProperty (v TExpr TExpr) b
prop_mapMaybe = makePropEq (Q.mapMaybe id) (mapMaybe id)
-- * Either
prop_left :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_left = makePropEq (Q.left :: Q.Q Integer -> Q.Q (Either Integer Integer)) Left
prop_right :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_right = makePropEq (Q.right :: Q.Q Integer -> Q.Q (Either Integer Integer)) Right
prop_isLeft :: (BackendVector b, VectorLang v) => Either Integer Integer -> DSHProperty (v TExpr TExpr) b
prop_isLeft = makePropEq Q.isLeft (\e -> case e of {Left _ -> True; Right _ -> False;})
prop_isRight :: (BackendVector b, VectorLang v) => Either Integer Integer -> DSHProperty (v TExpr TExpr) b
prop_isRight = makePropEq Q.isRight (\e -> case e of {Left _ -> False; Right _ -> True;})
prop_either :: (BackendVector b, VectorLang v) => Either Integer Integer -> DSHProperty (v TExpr TExpr) b
prop_either = makePropEq (Q.either id id) (either id id)
prop_lefts :: (BackendVector b, VectorLang v) => [Either Integer Integer] -> DSHProperty (v TExpr TExpr) b
prop_lefts = makePropEq Q.lefts lefts
prop_rights :: (BackendVector b, VectorLang v) => [Either Integer Integer] -> DSHProperty (v TExpr TExpr) b
prop_rights = makePropEq Q.rights rights
prop_partitionEithers :: (BackendVector b, VectorLang v) => [Either Integer Integer] -> DSHProperty (v TExpr TExpr) b
prop_partitionEithers = makePropEq Q.partitionEithers partitionEithers
-- * Lists
prop_cons :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_cons = makePropEq (uncurryQ (Q.<|)) (uncurry (:))
prop_map_cons :: (BackendVector b, VectorLang v) => (Integer, [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_map_cons = makePropEq (\x -> Q.map (Q.fst x Q.<|) $ Q.snd x)
(\(x,xs) -> map (x:) xs)
prop_snoc :: (BackendVector b, VectorLang v) => ([Integer], Integer) -> DSHProperty (v TExpr TExpr) b
prop_snoc = makePropEq (uncurryQ (Q.|>)) (\(a,b) -> a ++ [b])
prop_map_snoc :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_snoc = makePropEq (\z -> Q.map (Q.fst z Q.|>) (Q.snd z)) (\(a,b) -> map (\z -> a ++ [z]) b)
prop_singleton :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_singleton = makePropEq Q.singleton (: [])
prop_head :: (BackendVector b, VectorLang v) => NonEmptyList Integer -> DSHProperty (v TExpr TExpr) b
prop_head (NonEmpty is) = makePropEq Q.head head is
prop_tail :: (BackendVector b, VectorLang v) => NonEmptyList Integer -> DSHProperty (v TExpr TExpr) b
prop_tail (NonEmpty is) = makePropEq Q.tail tail is
prop_last :: (BackendVector b, VectorLang v) => NonEmptyList Integer -> DSHProperty (v TExpr TExpr) b
prop_last (NonEmpty is) = makePropEq Q.last last is
prop_map_last :: (BackendVector b, VectorLang v) => [NonEmptyList Integer] -> DSHProperty (v TExpr TExpr) b
prop_map_last ps =
makePropEq (Q.map Q.last) (map last) (map getNonEmpty ps)
prop_init :: (BackendVector b, VectorLang v) => NonEmptyList Integer -> DSHProperty (v TExpr TExpr) b
prop_init (NonEmpty is) = makePropEq Q.init init is
prop_map_init :: (BackendVector b, VectorLang v) => [NonEmptyList Integer] -> DSHProperty (v TExpr TExpr) b
prop_map_init ps =
makePropEq (Q.map Q.init) (map init) (map getNonEmpty ps)
prop_the :: (BackendVector b, VectorLang v) => (Positive Int, Integer) -> DSHProperty (v TExpr TExpr) b
prop_the (n, i) =
makePropEq Q.head the l
where
l = replicate (getPositive n) i
prop_map_the :: (BackendVector b, VectorLang v) => [(Positive Int, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_map_the ps =
makePropEq (Q.map Q.head) (map the) xss
where
xss = map (\(Positive n, i) -> replicate n i) ps
prop_map_tail :: (BackendVector b, VectorLang v) => [NonEmptyList Integer] -> DSHProperty (v TExpr TExpr) b
prop_map_tail ps =
makePropEq (Q.map Q.tail) (map tail) (map getNonEmpty ps)
prop_index :: (BackendVector b, VectorLang v) => ([Integer], NonNegative Integer) -> DSHProperty (v TExpr TExpr) b
prop_index (l, NonNegative i) codeGen conn =
i < fromIntegral (length l)
==>
makePropEq (uncurryQ (Q.!!))
(\(a,b) -> a !! fromIntegral b)
(l, i)
codeGen conn
prop_index_pair :: (BackendVector b, VectorLang v) => ([(Integer, [Integer])], NonNegative Integer) -> DSHProperty (v TExpr TExpr) b
prop_index_pair (l, NonNegative i) codeGen conn =
i < fromIntegral (length l)
==>
makePropEq (uncurryQ (Q.!!))
(\(a,b) -> a !! fromIntegral b)
(l, i)
codeGen conn
prop_index_nest :: (BackendVector b, VectorLang v) => ([[Integer]], NonNegative Integer) -> DSHProperty (v TExpr TExpr) b
prop_index_nest (l, NonNegative i) codeGen conn =
i < fromIntegral (length l)
==>
makePropEq (uncurryQ (Q.!!))
(\(a,b) -> a !! fromIntegral b)
(l, i)
codeGen conn
prop_map_index2 :: (BackendVector b, VectorLang v) => (NonEmptyList Integer, [NonNegative Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_index2 (nl, is) =
makePropEq (\z -> Q.map (\i -> Q.fst z Q.!! i) (Q.snd z))
(\z -> map (\i -> (fst z) !! fromIntegral i) $ snd z)
(l, is')
where
l = getNonEmpty nl
is' = map ((`mod` fromIntegral (length l)) . getNonNegative) is
prop_map_index :: (BackendVector b, VectorLang v) => ([Integer], [NonNegative Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_index (l, is) codeGen conn =
and [i < 3 * fromIntegral (length l) | NonNegative i <- is]
==>
makePropEq (\z -> Q.map ((Q.fst z Q.++ Q.fst z Q.++ Q.fst z) Q.!!)
(Q.snd z))
(\(a,b) -> map (((a ++ a ++ a) !!) . fromIntegral) b)
(l, map getNonNegative is)
codeGen conn
prop_map_index_nest :: (BackendVector b, VectorLang v) => ([[Integer]], [NonNegative Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_index_nest (l, is) codeGen conn =
and [i < 3 * fromIntegral (length l) | NonNegative i <- is]
==> makePropEq (\z -> Q.map (((Q.fst z) Q.++ (Q.fst z) Q.++ (Q.fst z)) Q.!!)
(Q.snd z))
(\(a,b) -> map ((a ++ a ++ a) !!) (map fromIntegral b))
(l, map getNonNegative is)
codeGen conn
prop_take :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_take = makePropEq (uncurryQ Q.take) (\(n,l) -> take (fromIntegral n) l)
prop_map_take :: (BackendVector b, VectorLang v) => (Integer, [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_map_take = makePropEq (\z -> Q.map (Q.take $ Q.fst z) $ Q.snd z)
(\(n,l) -> map (take (fromIntegral n)) l)
prop_drop :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_drop = makePropEq (uncurryQ Q.drop) (\(n,l) -> drop (fromIntegral n) l)
prop_map_drop :: (BackendVector b, VectorLang v) => (Integer, [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_map_drop = makePropEq (\z -> Q.map (Q.drop $ Q.fst z) $ Q.snd z)
(\(n,l) -> map (drop (fromIntegral n)) l)
prop_takedrop :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_takedrop = makePropEq takedrop_q takedrop
where
takedrop_q p = Q.append ((Q.take (Q.fst p)) (Q.snd p))
((Q.drop (Q.fst p)) (Q.snd p))
takedrop (n, l) = (take (fromIntegral n) l)
++
(drop (fromIntegral n) l)
prop_map :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_map = makePropEq (Q.map id) (map id)
prop_map_map_mul :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_map_mul = makePropEq (Q.map (Q.map (*2))) (map (map (*2)))
prop_map_map_add :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_map_add = makePropEq (\z -> Q.map (\x -> (Q.map (\y -> x + y) $ Q.snd z))
(Q.fst z))
(\(l,r) -> map (\x -> map (\y -> x + y) r) l)
prop_map_map_map_mul :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_map_map_map_mul = makePropEq (Q.map (Q.map (Q.map (*2)))) (map (map (map (*2))))
prop_append :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_append = makePropEq (uncurryQ (Q.++)) (uncurry (++))
prop_append_nest :: (BackendVector b, VectorLang v) => ([[Integer]], [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_append_nest = makePropEq (uncurryQ (Q.append)) (\(a,b) -> a ++ b)
prop_map_append :: (BackendVector b, VectorLang v) => ([Integer], [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_map_append = makePropEq (\z -> Q.map (Q.fst z Q.++) (Q.snd z)) (\(a,b) -> map (a ++) b)
prop_filter :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_filter = makePropEq (Q.filter (const $ Q.toQ True)) (filter $ const True)
prop_filter_gt :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_filter_gt = makePropEq (Q.filter (Q.> 42)) (filter (> 42))
prop_filter_gt_nested :: (BackendVector b, VectorLang v) => [(Integer, [Integer])] -> DSHProperty (v TExpr TExpr) b
prop_filter_gt_nested = makePropEq (Q.filter ((Q.> 42) . Q.fst)) (filter ((> 42) . fst))
prop_map_filter :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_filter = makePropEq (Q.map (Q.filter (const $ Q.toQ True))) (map (filter $ const True))
prop_map_filter_gt :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_filter_gt = makePropEq (Q.map (Q.filter (Q.> 42))) (map (filter (> 42)))
prop_map_filter_gt_nested :: (BackendVector b, VectorLang v) => [[(Integer, [Integer])]] -> DSHProperty (v TExpr TExpr) b
prop_map_filter_gt_nested = makePropEq (Q.map (Q.filter ((Q.> 42) . Q.fst))) (map (filter ((> 42) . fst)))
prop_groupWith :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_groupWith = makePropEq (Q.groupWith id) (groupWith id)
groupWithKey :: Ord b => (a -> b) -> [a] -> [(b, [a])]
groupWithKey p as = map (\g -> (the $ map p g, g)) $ groupWith p as
prop_groupWithKey :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_groupWithKey = makePropEq (Q.groupWithKey id) (groupWithKey id)
prop_map_groupWith_rem :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupWith_rem = makePropEq (Q.map (Q.groupWith (`Q.rem` 10)))
(map (groupWith (`rem` 10)))
prop_map_groupWith :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupWith = makePropEq (Q.map (Q.groupWith id)) (map (groupWith id))
prop_map_groupWithKey :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupWithKey = makePropEq (Q.map (Q.groupWithKey id)) (map (groupWithKey id))
prop_groupWith_length :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_groupWith_length = makePropEq (Q.groupWith Q.length) (groupWith length)
prop_groupWithKey_length :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_groupWithKey_length = makePropEq (Q.groupWithKey Q.length) (groupWithKey (fromIntegral . length))
prop_groupagg_sum :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_groupagg_sum = makePropEq (Q.map Q.sum . Q.groupWith (`Q.rem` 10))
(map sum . groupWith (`rem` 10))
prop_groupaggkey_sum :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_groupaggkey_sum = makePropEq (Q.map (\(Q.view -> (k, g)) -> Q.pair k (Q.sum g)) . Q.groupWithKey (`Q.rem` 10))
(map (\(k, g) -> (k, sum g)) . groupWithKey (`rem` 10))
prop_groupagg_sum_exp :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_groupagg_sum_exp = makePropEq (Q.map Q.sum . Q.map (Q.map (* 3)) . Q.groupWith (`Q.rem` 10))
(map sum . map (map (* 3)) . groupWith (`rem` 10))
prop_groupagg_length :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_groupagg_length = makePropEq (Q.map Q.length . Q.groupWith (`Q.rem` 10))
(map (fromIntegral . length) . groupWith (`rem` 10))
prop_groupagg_minimum :: (BackendVector b, VectorLang v) => NonEmptyList Integer -> DSHProperty (v TExpr TExpr) b
prop_groupagg_minimum is = makePropEq (Q.map Q.minimum . Q.groupWith (`Q.rem` 10))
(map minimum . groupWith (`rem` 10))
(getNonEmpty is)
prop_groupagg_maximum :: (BackendVector b, VectorLang v) => NonEmptyList Integer -> DSHProperty (v TExpr TExpr) b
prop_groupagg_maximum is = makePropEq (Q.map Q.maximum . Q.groupWith (`Q.rem` 10))
(map maximum . groupWith (`rem` 10))
(getNonEmpty is)
prop_groupagg_avg :: (BackendVector b, VectorLang v) => NonEmptyList Double -> DSHProperty (v TExpr TExpr) b
prop_groupagg_avg is = makePropDoubles (Q.map Q.avg . Q.groupWith (Q.> 0))
(map avgDouble . groupWith (> 0))
(getNonEmpty is)
prop_groupagg_sum_length :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_groupagg_sum_length = makePropEq (Q.map (\g -> Q.tup2 (Q.sum g) (Q.length g)) . Q.groupWith (`Q.rem` 10))
(map (\g -> (sum g, fromIntegral $ length g)) . groupWith (`rem` 10))
prop_groupaggkey_sum_length :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_groupaggkey_sum_length = makePropEq (Q.map (\(Q.view -> (k, g)) -> Q.tup3 k (Q.sum g) (Q.length g)) . Q.groupWithKey (`Q.rem` 10))
(map (\(k, g) -> (k, sum g, fromIntegral $ length g)) . groupWithKey (`rem` 10))
prop_groupagg_sum_length_max :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_groupagg_sum_length_max = makePropEq (Q.map (\g -> Q.tup3 (Q.sum g) (Q.length g) (Q.maximum g)) . Q.groupWith (`Q.rem` 10))
(map (\g -> (sum g, fromIntegral $ length g, maximum g)) . groupWith (`rem` 10))
prop_sortWith :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_sortWith = makePropEq (Q.sortWith id) (sortWith id)
prop_sortWith_pair :: (BackendVector b, VectorLang v) => [(Integer, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_sortWith_pair = makePropEq (Q.sortWith Q.fst) (sortWith fst)
-- Test whether we keep the stable sorting semantics of sortWith.
prop_sortWith_pair_stable :: (BackendVector b, VectorLang v) => [(Char, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_sortWith_pair_stable = makePropEq (Q.sortWith Q.fst) (sortWith fst)
prop_sortWith_nest :: (BackendVector b, VectorLang v) => [(Integer, [Integer])] -> DSHProperty (v TExpr TExpr) b
prop_sortWith_nest = makePropEq (Q.sortWith Q.fst) (sortWith fst)
prop_map_sortWith :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_sortWith = makePropEq (Q.map (Q.sortWith id)) (map (sortWith id))
prop_map_sortWith_pair :: (BackendVector b, VectorLang v) => [[(Integer, Integer)]] -> DSHProperty (v TExpr TExpr) b
prop_map_sortWith_pair = makePropEq (Q.map (Q.sortWith Q.fst)) (map (sortWith fst))
prop_map_sortWith_nest :: (BackendVector b, VectorLang v) => [[(Integer, [Integer])]] -> DSHProperty (v TExpr TExpr) b
prop_map_sortWith_nest = makePropEq (Q.map (Q.sortWith Q.fst)) (map (sortWith fst))
prop_map_sortWith_length :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_map_sortWith_length = makePropEq (Q.map (Q.sortWith Q.length)) (map (sortWith length))
prop_map_groupWith_length :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupWith_length = makePropEq (Q.map (Q.groupWith Q.length)) (map (groupWith length))
prop_map_groupWithKey_length :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupWithKey_length = makePropEq (Q.map (Q.groupWithKey Q.length))
(map (groupWithKey (fromIntegral . length)))
prop_map_groupagg_sum :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupagg_sum = makePropEq (Q.map (Q.map Q.sum) . Q.map (Q.groupWith (`Q.rem` 10)))
(map (map sum) . map (groupWith (`rem` 10)))
prop_map_groupaggkey_sum :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupaggkey_sum = makePropEq (Q.map (Q.map (\(Q.view -> (k, g)) -> Q.pair k (Q.sum g))) . Q.map (Q.groupWithKey (`Q.rem` 10)))
(map (map (\(k, g) -> (k, sum g))) . map (groupWithKey (`rem` 10)))
prop_map_groupagg_sum_exp :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupagg_sum_exp = makePropEq (Q.map (Q.map Q.sum) . Q.map (Q.map (Q.map (* 3))) . Q.map (Q.groupWith (`Q.rem` 10)))
(map (map sum) . map (map (map (* 3))) . map (groupWith (`rem` 10)))
prop_map_groupagg_length :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupagg_length = makePropEq (Q.map (Q.map Q.length) . Q.map (Q.groupWith (`Q.rem` 10)))
(map (map (fromIntegral . length)) . map (groupWith (`rem` 10)))
prop_map_groupagg_minimum :: (BackendVector b, VectorLang v) => [NonEmptyList Integer] -> DSHProperty (v TExpr TExpr) b
prop_map_groupagg_minimum is = makePropEq (Q.map (Q.map Q.minimum) . Q.map (Q.groupWith (`Q.rem` 10)))
(map (map minimum) . map (groupWith (`rem` 10)))
(map getNonEmpty is)
prop_map_groupagg_maximum :: (BackendVector b, VectorLang v) => [NonEmptyList Integer] -> DSHProperty (v TExpr TExpr) b
prop_map_groupagg_maximum is = makePropEq (Q.map (Q.map Q.maximum) . Q.map (Q.groupWith (`Q.rem` 10)))
(map (map maximum) . map (groupWith (`rem` 10)))
(map getNonEmpty is)
prop_map_groupagg_sum_length :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupagg_sum_length = makePropEq (Q.map (Q.map (\g -> Q.tup2 (Q.sum g) (Q.length g))) . Q.map (Q.groupWith (`Q.rem` 10)))
(map (map (\g -> (sum g, fromIntegral $ length g))) . map (groupWith (`rem` 10)))
prop_map_groupaggkey_sum_length :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupaggkey_sum_length = makePropEq (Q.map (Q.map (\(Q.view -> (k, g)) -> Q.tup3 k (Q.sum g) (Q.length g))) . Q.map (Q.groupWithKey (`Q.rem` 10)))
(map (map (\(k, g) -> (k, sum g, fromIntegral $ length g))) . map (groupWithKey (`rem` 10)))
prop_map_groupagg_sum_length_max :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_groupagg_sum_length_max = makePropEq (Q.map (Q.map (\g -> Q.tup3 (Q.sum g) (Q.length g) (Q.maximum g))) . Q.map (Q.groupWith (`Q.rem` 10)))
(map (map (\g -> (sum g, fromIntegral $ length g, maximum g))) . map (groupWith (`rem` 10)))
prop_sortWith_length_nest :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_sortWith_length_nest = makePropEq (Q.sortWith Q.length) (sortWith length)
prop_groupWith_length_nest :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_groupWith_length_nest = makePropEq (Q.groupWith Q.length) (groupWith length)
prop_groupWithKey_length_nest :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_groupWithKey_length_nest = makePropEq (Q.groupWithKey Q.length)
(groupWithKey (fromIntegral . length))
prop_null :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_null = makePropEq Q.null null
prop_map_null :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_null = makePropEq (Q.map Q.null) (map null)
prop_length :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_length = makePropEq Q.length ((fromIntegral :: Int -> Integer) . length)
prop_length_tuple :: (BackendVector b, VectorLang v) => [(Integer, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_length_tuple = makePropEq Q.length (fromIntegral . length)
prop_map_length :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_length = makePropEq (Q.map Q.length) (map (fromIntegral . length))
prop_map_minimum :: (BackendVector b, VectorLang v) => [NonEmptyList Integer] -> DSHProperty (v TExpr TExpr) b
prop_map_minimum ps conn =
makePropEq (Q.map Q.minimum)
(map (fromIntegral . minimum))
(map getNonEmpty ps)
conn
prop_map_maximum :: (BackendVector b, VectorLang v) => [NonEmptyList Integer] -> DSHProperty (v TExpr TExpr) b
prop_map_maximum ps conn =
makePropEq (Q.map Q.maximum)
(map (fromIntegral . maximum))
(map getNonEmpty ps)
conn
prop_map_map_minimum :: (BackendVector b, VectorLang v) => [[NonEmptyList Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_map_minimum ps conn =
makePropEq (Q.map (Q.map Q.minimum))
(map (map(fromIntegral . minimum)))
(map (map getNonEmpty) ps)
conn
prop_map_map_maximum :: (BackendVector b, VectorLang v) => [[NonEmptyList Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_map_maximum ps conn =
makePropEq (Q.map (Q.map Q.maximum))
(map (map(fromIntegral . maximum)))
(map (map getNonEmpty) ps)
conn
prop_map_length_tuple :: (BackendVector b, VectorLang v) => [[(Integer, Integer)]] -> DSHProperty (v TExpr TExpr) b
prop_map_length_tuple = makePropEq (Q.map Q.length) (map (fromIntegral . length))
prop_reverse :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_reverse = makePropEq Q.reverse reverse
prop_reverse_nest :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_reverse_nest = makePropEq Q.reverse reverse
prop_map_reverse :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_reverse = makePropEq (Q.map Q.reverse) (map reverse)
prop_map_reverse_nest :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_map_reverse_nest = makePropEq (Q.map Q.reverse) (map reverse)
prop_and :: (BackendVector b, VectorLang v) => [Bool] -> DSHProperty (v TExpr TExpr) b
prop_and = makePropEq Q.and and
prop_map_and :: (BackendVector b, VectorLang v) => [[Bool]] -> DSHProperty (v TExpr TExpr) b
prop_map_and = makePropEq (Q.map Q.and) (map and)
prop_map_map_and :: (BackendVector b, VectorLang v) => [[[Bool]]] -> DSHProperty (v TExpr TExpr) b
prop_map_map_and = makePropEq (Q.map (Q.map Q.and)) (map (map and))
prop_or :: (BackendVector b, VectorLang v) => [Bool] -> DSHProperty (v TExpr TExpr) b
prop_or = makePropEq Q.or or
prop_map_or :: (BackendVector b, VectorLang v) => [[Bool]] -> DSHProperty (v TExpr TExpr) b
prop_map_or = makePropEq (Q.map Q.or) (map or)
prop_map_map_or :: (BackendVector b, VectorLang v) => [[[Bool]]] -> DSHProperty (v TExpr TExpr) b
prop_map_map_or = makePropEq (Q.map (Q.map Q.or)) (map (map or))
prop_any_zero :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_any_zero = makePropEq (Q.any (Q.== 0)) (any (== 0))
prop_map_any_zero :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_any_zero = makePropEq (Q.map (Q.any (Q.== 0))) (map (any (== 0)))
prop_all_zero :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_all_zero = makePropEq (Q.all (Q.== 0)) (all (== 0))
prop_map_all_zero :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_all_zero = makePropEq (Q.map (Q.all (Q.== 0))) (map (all (== 0)))
prop_sum_integer :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_sum_integer = makePropEq Q.sum sum
prop_map_sum :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_sum = makePropEq (Q.map Q.sum) (map sum)
prop_map_avg :: (BackendVector b, VectorLang v) => [NonEmptyList (Fixed Double)] -> DSHProperty (v TExpr TExpr) b
prop_map_avg is =
makePropDoubles (Q.map Q.avg) (map avgDouble) (map (map getFixed . getNonEmpty) is)
prop_map_map_sum :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_map_map_sum = makePropEq (Q.map (Q.map Q.sum)) (map (map sum))
-- prop_map_map_avg :: (BackendVector b, VectorLang v) => [[NonEmptyList Integer]] -> DSHProperty (v TExpr TExpr) b
-- prop_map_map_avg is conn =
-- makePropEq (Q.map (Q.map Q.avg))
-- (map (map avgInt))
-- (map (map getNonEmpty) is)
-- conn
prop_sum_double :: (BackendVector b, VectorLang v) => [Fixed Double] -> DSHProperty (v TExpr TExpr) b
prop_sum_double d = makePropDouble Q.sum sum (map getFixed d)
avgDouble :: [Double] -> Double
avgDouble ds = sum ds / (fromIntegral $ length ds)
prop_avg_double :: (BackendVector b, VectorLang v) => NonEmptyList (Fixed Double) -> DSHProperty (v TExpr TExpr) b
prop_avg_double ds conn = makePropDouble Q.avg avgDouble (map getFixed $ getNonEmpty ds) conn
prop_concat :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_concat = makePropEq Q.concat concat
prop_map_concat :: (BackendVector b, VectorLang v) => [[[Integer]]] -> DSHProperty (v TExpr TExpr) b
prop_map_concat = makePropEq (Q.map Q.concat) (map concat)
-- Test segment merging in a case with per-segment order for the natural-key SQL
-- backend.
prop_map_concat2 :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_map_concat2 = makePropEq db heap
where
db (Q.view -> (ys, zs)) = Q.map Q.concat $ Q.map (const (Q.map (const zs) ys)) zs
heap (ys, zs) = map concat $ map (const (map (const zs) ys)) zs
prop_concatMap :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_concatMap = makePropEq (Q.concatMap Q.singleton) (concatMap (: []))
prop_maximum :: (BackendVector b, VectorLang v) => NonEmptyList Integer -> DSHProperty (v TExpr TExpr) b
prop_maximum (NonEmpty is) = makePropEq Q.maximum maximum is
prop_minimum :: (BackendVector b, VectorLang v) => NonEmptyList Integer -> DSHProperty (v TExpr TExpr) b
prop_minimum (NonEmpty is) = makePropEq Q.minimum minimum is
prop_splitAt :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_splitAt = makePropEq (uncurryQ Q.splitAt) (\(a,b) -> splitAt (fromIntegral a) b)
prop_takeWhile :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_takeWhile = makePropEq (uncurryQ $ Q.takeWhile . (Q.==))
(uncurry $ takeWhile . (==))
prop_dropWhile :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_dropWhile = makePropEq (uncurryQ $ Q.dropWhile . (Q.==))
(uncurry $ dropWhile . (==))
prop_map_takeWhile :: (BackendVector b, VectorLang v) => (Integer, [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_map_takeWhile = makePropEq (\z -> Q.map (Q.takeWhile (Q.fst z Q.==)) (Q.snd z))
(\z -> map (takeWhile (fst z ==)) (snd z))
prop_map_dropWhile :: (BackendVector b, VectorLang v) => (Integer, [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_map_dropWhile = makePropEq (\z -> Q.map (Q.dropWhile (Q.fst z Q.==)) (Q.snd z))
(\z -> map (dropWhile (fst z ==)) (snd z))
prop_span :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_span = makePropEq (uncurryQ $ Q.span . (Q.==))
(uncurry $ span . (==) . fromIntegral)
prop_map_span :: (BackendVector b, VectorLang v) => (Integer, [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_map_span = makePropEq (\z -> Q.map (Q.span ((Q.fst z) Q.==)) (Q.snd z))
(\z -> map (span (fst z ==)) (snd z))
prop_break :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_break = makePropEq (uncurryQ $ Q.break . (Q.==))
(uncurry $ break . (==) . fromIntegral)
prop_map_break :: (BackendVector b, VectorLang v) => (Integer, [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_map_break = makePropEq (\z -> Q.map (Q.break ((Q.fst z) Q.==)) (Q.snd z))
(\z -> map (break (fst z ==)) (snd z))
prop_elem :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_elem = makePropEq (uncurryQ Q.elem)
(uncurry elem)
prop_notElem :: (BackendVector b, VectorLang v) => (Integer, [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_notElem = makePropEq (uncurryQ Q.notElem)
(uncurry notElem)
prop_lookup :: (BackendVector b, VectorLang v) => (Integer, [(Integer,Integer)]) -> DSHProperty (v TExpr TExpr) b
prop_lookup = makePropEq (uncurryQ Q.lookup)
(uncurry lookup)
prop_zip :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_zip = makePropEq (uncurryQ Q.zip) (uncurry zip)
prop_zip_nested :: (BackendVector b, VectorLang v) => ([Integer], [(Integer, [Integer])]) -> DSHProperty (v TExpr TExpr) b
prop_zip_nested = makePropEq (uncurryQ Q.zip) (uncurry zip)
prop_zip_tuple1 :: (BackendVector b, VectorLang v) => ([Integer], [(Text, Integer)]) -> DSHProperty (v TExpr TExpr) b
prop_zip_tuple1 (xs, tds) =
makePropEq (uncurryQ Q.zip) (uncurry zip) (xs, tds')
where
tds' = map (\(t, d) -> (filterNullChar t, d)) tds
prop_zip_tuple2 :: (BackendVector b, VectorLang v)
=> ([(Integer, Integer)], [(Text, Integer)])
-> DSHProperty (v TExpr TExpr) b
prop_zip_tuple2 (xs, tds) =
makePropEq (uncurryQ Q.zip) (uncurry zip) (xs, tds')
where
tds' = map (\(t, d) -> (filterNullChar t, d)) tds
prop_map_zip :: (BackendVector b, VectorLang v) => ([Integer], [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_map_zip = makePropEq (\z -> Q.map (Q.zip $ Q.fst z) $ Q.snd z) (\(x, y) -> map (zip x) y)
prop_zipWith :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_zipWith = makePropEq (uncurryQ $ Q.zipWith (+)) (uncurry $ zipWith (+))
prop_unzip :: (BackendVector b, VectorLang v) => [(Integer, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_unzip = makePropEq Q.unzip unzip
prop_map_unzip :: (BackendVector b, VectorLang v) => [[(Integer, Integer)]] -> DSHProperty (v TExpr TExpr) b
prop_map_unzip = makePropEq (Q.map Q.unzip) (map unzip)
prop_zip3 :: (BackendVector b, VectorLang v) => ([Integer], [Integer],[Integer]) -> DSHProperty (v TExpr TExpr) b
prop_zip3 = makePropEq (\q -> (case Q.view q of (as,bs,cs) -> Q.zip3 as bs cs))
(\(as,bs,cs) -> zip3 as bs cs)
prop_zipWith3 :: (BackendVector b, VectorLang v) => ([Integer], [Integer],[Integer]) -> DSHProperty (v TExpr TExpr) b
prop_zipWith3 = makePropEq (\q -> (case Q.view q of (as,bs,cs) -> Q.zipWith3 (\a b c -> a + b + c) as bs cs))
(\(as,bs,cs) -> zipWith3 (\a b c -> a + b + c) as bs cs)
prop_unzip3 :: (BackendVector b, VectorLang v) => [(Integer, Integer, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_unzip3 = makePropEq Q.unzip3 unzip3
prop_nub :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_nub = makePropEq Q.nub nub
prop_map_nub :: (BackendVector b, VectorLang v) => [[(Integer, Integer)]] -> DSHProperty (v TExpr TExpr) b
prop_map_nub = makePropEq (Q.map Q.nub) (map nub)
-- * Tuples
prop_fst :: (BackendVector b, VectorLang v) => (Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_fst = makePropEq Q.fst fst
prop_fst_nested :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_fst_nested = makePropEq Q.fst fst
prop_map_fst :: (BackendVector b, VectorLang v) => [(Integer, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_map_fst = makePropEq (Q.map Q.fst) (map fst)
prop_snd :: (BackendVector b, VectorLang v) => (Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_snd = makePropEq Q.snd snd
prop_map_snd :: (BackendVector b, VectorLang v) => [(Integer, Integer)] -> DSHProperty (v TExpr TExpr) b
prop_map_snd = makePropEq (Q.map Q.snd) (map snd)
prop_snd_nested :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_snd_nested = makePropEq Q.snd snd
prop_tup3_1 :: (BackendVector b, VectorLang v) => (Integer, Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_tup3_1 = makePropEq (\q -> case Q.view q of (a, _, _) -> a) (\(a, _, _) -> a)
prop_tup3_2 :: (BackendVector b, VectorLang v) => (Integer, Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_tup3_2 = makePropEq (\q -> case Q.view q of (_, b, _) -> b) (\(_, b, _) -> b)
prop_tup3_3 :: (BackendVector b, VectorLang v) => (Integer, Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_tup3_3 = makePropEq (\q -> case Q.view q of (_, _, c) -> c) (\(_, _, c) -> c)
prop_tup4_2 :: (BackendVector b, VectorLang v) => (Integer, Integer, Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_tup4_2 = makePropEq (\q -> case Q.view q of (_, b, _, _) -> b) (\(_, b, _, _) -> b)
prop_tup4_4 :: (BackendVector b, VectorLang v) => (Integer, Integer, Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_tup4_4 = makePropEq (\q -> case Q.view q of (_, _, _, d) -> d) (\(_, _, _, d) -> d)
prop_tup3_nested :: (BackendVector b, VectorLang v) => (Integer, [Integer], Integer) -> DSHProperty (v TExpr TExpr) b
prop_tup3_nested = makePropEq (\q -> case Q.view q of (_, b, _) -> b) (\(_, b, _) -> b)
prop_tup4_tup3 :: (BackendVector b, VectorLang v) => (Integer, Integer, Integer, Integer) -> DSHProperty (v TExpr TExpr) b
prop_tup4_tup3 = makePropEq (\q -> case Q.view q of (a, b, _, d) -> Q.tup3 a b d)
(\(a, b, _, d) -> (a, b, d))
prop_agg_tuple :: (BackendVector b, VectorLang v) => NonEmptyList Integer -> DSHProperty (v TExpr TExpr) b
prop_agg_tuple nxs = makePropEq (\is -> Q.tup3 (Q.sum is) (Q.maximum is) (Q.minimum is))
(\is -> (sum is, maximum is, minimum is))
xs
where
xs = getNonEmpty nxs
-- * Numerics
prop_add_integer :: (BackendVector b, VectorLang v) => (Integer,Integer) -> DSHProperty (v TExpr TExpr) b
prop_add_integer = makePropEq (uncurryQ (+)) (uncurry (+))
prop_add_integer_sums :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_add_integer_sums = makePropEq (\p -> Q.sum (Q.fst p) + Q.sum (Q.snd p))
(\p -> sum (fst p) + sum (snd p))
prop_add_double :: (BackendVector b, VectorLang v) => (Fixed Double, Fixed Double) -> DSHProperty (v TExpr TExpr) b
prop_add_double (d1, d2) = makePropDouble (uncurryQ (+)) (uncurry (+)) (getFixed d1, getFixed d2)
prop_mul_integer :: (BackendVector b, VectorLang v) => (Integer,Integer) -> DSHProperty (v TExpr TExpr) b
prop_mul_integer = makePropEq (uncurryQ (*)) (uncurry (*))
prop_mul_double :: (BackendVector b, VectorLang v) => (Fixed Double, Fixed Double) -> DSHProperty (v TExpr TExpr) b
prop_mul_double (d1, d2) = makePropDouble (uncurryQ (*)) (uncurry (*)) (getFixed d1, getFixed d2)
prop_div_double :: (BackendVector b, VectorLang v) => (Fixed Double, Fixed (NonZero Double)) -> DSHProperty (v TExpr TExpr) b
prop_div_double (Fixed x, Fixed (NonZero y)) =
makePropDouble (uncurryQ (/)) (uncurry (/)) (x,y)
prop_integer_to_double :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_integer_to_double = makePropDouble Q.integerToDouble fromInteger
prop_integer_to_double_arith :: (BackendVector b, VectorLang v) => (Integer, Fixed Double) -> DSHProperty (v TExpr TExpr) b
prop_integer_to_double_arith (i, d) = makePropDouble (\x -> (Q.integerToDouble (Q.fst x)) + (Q.snd x))
(\(ni, nd) -> fromInteger ni + nd)
(i, getFixed d)
prop_map_integer_to_double :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_map_integer_to_double = makePropDoubles (Q.map Q.integerToDouble) (map fromInteger)
prop_abs_integer :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_abs_integer = makePropEq Q.abs abs
prop_abs_double :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_abs_double d = makePropDouble Q.abs abs (getFixed d)
prop_signum_integer :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_signum_integer = makePropEq Q.signum signum
prop_signum_double :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_signum_double d = makePropDouble Q.signum signum (getFixed d)
prop_negate_integer :: (BackendVector b, VectorLang v) => Integer -> DSHProperty (v TExpr TExpr) b
prop_negate_integer = makePropEq Q.negate negate
prop_negate_double :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_negate_double d = makePropDouble Q.negate negate (getFixed d)
prop_trig_sin :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_trig_sin d = makePropDouble Q.sin sin (getFixed d)
prop_trig_cos :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_trig_cos d = makePropDouble Q.cos cos (getFixed d)
prop_trig_tan :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_trig_tan d = makePropDouble Q.tan tan (getFixed d)
prop_exp :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_exp d codeGen conn = d >= (-5) && d <= 5 ==> makePropDouble Q.exp exp (getFixed d) codeGen conn
prop_rem :: (BackendVector b, VectorLang v) => Fixed Integer -> DSHProperty (v TExpr TExpr) b
prop_rem d = makePropEq (`Q.rem` 10) (`rem` 10) (getFixed d)
prop_log :: (BackendVector b, VectorLang v) => Fixed (Positive Double) -> DSHProperty (v TExpr TExpr) b
prop_log d = makePropDouble Q.log log (getPositive $ getFixed d)
prop_sqrt :: (BackendVector b, VectorLang v) => Fixed (Positive Double) -> DSHProperty (v TExpr TExpr) b
prop_sqrt d = makePropDouble Q.sqrt sqrt (getPositive $ getFixed d)
arc :: (Ord a, Num a) => a -> Bool
arc d = d >= -1 && d <= 1
prop_trig_asin :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_trig_asin d codeGen conn = arc d ==> makePropDouble Q.asin asin (getFixed d) codeGen conn
prop_trig_acos :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_trig_acos d codeGen conn = arc d ==> makePropDouble Q.acos acos (getFixed d) codeGen conn
prop_trig_atan :: (BackendVector b, VectorLang v) => Fixed Double -> DSHProperty (v TExpr TExpr) b
prop_trig_atan d = makePropDouble Q.atan atan (getFixed d)
prop_number :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_number = makePropEq (Q.map Q.snd . Q.number) (\xs -> map snd $ zip xs [1..])
prop_map_number :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_number = makePropEq (Q.map (Q.map Q.snd . Q.number))
(map (\xs -> map snd $ zip xs [1..]))
prop_map_trig_sin :: (BackendVector b, VectorLang v) => [Fixed Double] -> DSHProperty (v TExpr TExpr) b
prop_map_trig_sin ds = makePropDoubles (Q.map Q.sin) (map sin) (map getFixed ds)
prop_map_trig_cos :: (BackendVector b, VectorLang v) => [Fixed Double] -> DSHProperty (v TExpr TExpr) b
prop_map_trig_cos ds = makePropDoubles (Q.map Q.cos) (map cos) (map getFixed ds)
prop_map_trig_tan :: (BackendVector b, VectorLang v) => [Fixed Double] -> DSHProperty (v TExpr TExpr) b
prop_map_trig_tan ds = makePropDoubles (Q.map Q.tan) (map tan) (map getFixed ds)
prop_map_trig_asin :: (BackendVector b, VectorLang v) => [Fixed Double] -> DSHProperty (v TExpr TExpr) b
prop_map_trig_asin ds codeGen conn =
all arc ds
==>
makePropDoubles (Q.map Q.asin) (map asin) (map getFixed ds) codeGen conn
prop_map_trig_acos :: (BackendVector b, VectorLang v) => [Fixed Double] -> DSHProperty (v TExpr TExpr) b
prop_map_trig_acos ds codeGen conn =
all arc ds
==>
makePropDoubles (Q.map Q.acos) (map acos) (map getFixed ds) codeGen conn
prop_map_trig_atan :: (BackendVector b, VectorLang v) => [Fixed Double] -> DSHProperty (v TExpr TExpr) b
prop_map_trig_atan ds = makePropDoubles (Q.map Q.atan) (map atan) (map getFixed ds)
prop_map_exp :: (BackendVector b, VectorLang v) => [Fixed Double] -> DSHProperty (v TExpr TExpr) b
prop_map_exp ds codeGen conn =
all (\d -> d >= (-5) && d <= 5) ds
==>
makePropDoubles (Q.map Q.exp) (map exp) (map getFixed ds) codeGen conn
prop_map_rem :: (BackendVector b, VectorLang v) => [Fixed Integer] -> DSHProperty (v TExpr TExpr) b
prop_map_rem d = makePropEq (Q.map (`Q.rem` 10)) (map (`rem` 10)) (map getFixed d)
prop_map_log :: (BackendVector b, VectorLang v) => [Fixed (Positive Double)] -> DSHProperty (v TExpr TExpr) b
prop_map_log ds = makePropDoubles (Q.map Q.log) (map log) (map (getPositive . getFixed) ds)
prop_map_sqrt :: (BackendVector b, VectorLang v) => [Fixed (Positive Double)] -> DSHProperty (v TExpr TExpr) b
prop_map_sqrt ds =
makePropDoubles (Q.map Q.sqrt) (map sqrt) (map (getPositive . getFixed) ds)
prop_dist_scalar :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_dist_scalar = makePropEq (\p -> Q.map (\i -> Q.sum (Q.fst p) + i) (Q.snd p))
(\p -> map (\i -> sum (fst p) + i) (snd p))
prop_dist_list1 :: (BackendVector b, VectorLang v) => ([Integer], [[Integer]]) -> DSHProperty (v TExpr TExpr) b
prop_dist_list1 = makePropEq (\p -> Q.map (\xs -> (Q.fst p) Q.++ xs) (Q.snd p))
(\p -> map (\xs -> (fst p) ++ xs) (snd p))
prop_dist_list2 :: (BackendVector b, VectorLang v) => ([Integer], [Integer]) -> DSHProperty (v TExpr TExpr) b
prop_dist_list2 = makePropEq (\p -> Q.map (\i -> Q.take i (Q.fst p)) (Q.snd p))
(\p -> map (\i -> take (fromIntegral i) (fst p)) (snd p))
-- Testcase for lifted disting. This is a first-order version of the running
-- example in Lippmeier et al's paper "Work-Efficient Higher Order
-- Vectorisation" (ICFP 2012).
test_dist_lift :: (BackendVector b, VectorLang v) => DSHAssertion (v TExpr TExpr) b
test_dist_lift = makeEqAssertion "dist lift"
(Q.zipWith (\xs is -> Q.map (\i -> xs Q.!! i) is) (Q.toQ xss) (Q.toQ iss))
(zipWith (\xs is -> map (\i -> xs !! fromIntegral i) is) xss iss)
where
xss = [['a', 'b'], ['c', 'd', 'e'], ['f', 'g'], ['h']]
iss = [[1,0,1], [2], [1,0], [0]] :: [[Integer]]
hnegative_sum :: (BackendVector b, VectorLang v) => DSHAssertion (v TExpr TExpr) b
hnegative_sum = makeEqAssertion "hnegative_sum" (Q.sum (Q.toQ xs)) (sum xs)
where
xs :: [Integer]
xs = [-1, -4, -5, 2]
hnegative_map_sum :: (BackendVector b, VectorLang v) => DSHAssertion (v TExpr TExpr) b
hnegative_map_sum = makeEqAssertion "hnegative_map_sum"
(Q.map Q.sum (Q.toQ xss))
(map sum xss)
where
xss :: [[Integer]]
xss = [[10, 20, 30], [-10, -20, -30], [], [0]]
prop_nub_length :: (BackendVector b, VectorLang v) => [Integer] -> DSHProperty (v TExpr TExpr) b
prop_nub_length = makePropEq (Q.length . Q.nub) (fromIntegral . length . nub)
prop_map_nub_length :: (BackendVector b, VectorLang v) => [[Integer]] -> DSHProperty (v TExpr TExpr) b
prop_map_nub_length = makePropEq (Q.map (Q.length . Q.nub)) (map (fromIntegral . length . nub))
prop_elem_sort :: (BackendVector b, VectorLang v) => ([Integer], [(Integer, Char)]) -> DSHProperty (v TExpr TExpr) b
prop_elem_sort = makePropEq (\(Q.view -> (xs, ys)) -> Q.map (\x -> Q.fst x `Q.elem` xs) $ Q.sortWith Q.snd ys)
(\(xs, ys) -> map (\x -> fst x `elem` xs) $ sortWith snd ys)
prop_elem_sort2 :: (BackendVector b, VectorLang v) => ([Integer], [(Integer, Char)]) -> DSHProperty (v TExpr TExpr) b
prop_elem_sort2 = makePropEq (\(Q.view -> (xs, ys)) -> Q.filter (\x -> Q.fst x `Q.elem` xs) $ Q.sortWith Q.snd ys)
(\(xs, ys) -> filter (\x -> fst x `elem` xs) $ sortWith snd ys)
| ulricha/dsh | src/Database/DSH/Tests/CombinatorTests.hs | bsd-3-clause | 83,992 | 0 | 16 | 20,480 | 28,980 | 15,307 | 13,673 | 1,037 | 2 |
{-# LANGUAGE CPP, GADTs, FlexibleContexts, FlexibleInstances #-}
{-# LANGUAGE TypeOperators, TypeFamilies #-}
-- |
-- Module : Data.Array.Accelerate.Array.Representation
-- Copyright : [2008..2011] Manuel M T Chakravarty, Gabriele Keller, Sean Lee, Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.Array.Representation (
-- * Array shapes, indices, and slices
Shape(..), Slice(..), SliceIndex(..),
) where
-- friends
import Data.Array.Accelerate.Type
#include "accelerate.h"
-- |Index representation
--
-- |Class of index representations (which are nested pairs)
--
class (Eq sh, Slice sh) => Shape sh where
-- user-facing methods
dim :: sh -> Int -- ^number of dimensions (>= 0); rank of the array
size :: sh -> Int -- ^total number of elements in an array of this /shape/
-- internal methods
intersect :: sh -> sh -> sh -- yield the intersection of two shapes
ignore :: sh -- identifies ignored elements in 'permute'
index :: sh -> sh -> Int -- yield the index position in a linear, row-major representation of
-- the array (first argument is the shape)
bound :: sh -> sh -> Boundary e -> Either e sh
-- apply a boundary condition to an index
iter :: sh -> (sh -> a) -> (a -> a -> a) -> a -> a
-- iterate through the entire shape, applying the function in the
-- second argument; third argument combines results and fourth is an
-- initial value that is combined with the results; the index space
-- is traversed in row-major order
iter1 :: sh -> (sh -> a) -> (a -> a -> a) -> a
-- variant of 'iter' without an initial value
-- operations to facilitate conversion with IArray
rangeToShape :: (sh, sh) -> sh -- convert a minpoint-maxpoint index
-- into a shape
shapeToRange :: sh -> (sh, sh) -- ...the converse
-- other conversions
shapeToList :: sh -> [Int] -- convert a shape into its list of dimensions
listToShape :: [Int] -> sh -- convert a list of dimensions into a shape
instance Shape () where
dim () = 0
size () = 1
() `intersect` () = ()
ignore = ()
index () () = 0
bound () () _ = Right ()
iter () f c e = e `c` f ()
iter1 () f _ = f ()
rangeToShape ((), ()) = ()
shapeToRange () = ((), ())
shapeToList () = []
listToShape [] = ()
listToShape _ = INTERNAL_ERROR(error) "listToShape" "non-empty list when converting to unit"
instance Shape sh => Shape (sh, Int) where
dim (sh, _) = dim sh + 1
size (sh, sz) = size sh * sz
(sh1, sz1) `intersect` (sh2, sz2) = (sh1 `intersect` sh2, sz1 `min` sz2)
ignore = (ignore, -1)
index (sh, sz) (ix, i) = BOUNDS_CHECK(checkIndex) "index" i sz
$ index sh ix * sz + i
bound (sh, sz) (ix, i) bndy
| i < 0 = case bndy of
Clamp -> bound sh ix bndy `addDim` 0
Mirror -> bound sh ix bndy `addDim` (-i)
Wrap -> bound sh ix bndy `addDim` (sz+i)
Constant e -> Left e
| i >= sz = case bndy of
Clamp -> bound sh ix bndy `addDim` (sz-1)
Mirror -> bound sh ix bndy `addDim` (sz-(i-sz+2))
Wrap -> bound sh ix bndy `addDim` (i-sz)
Constant e -> Left e
| otherwise = bound sh ix bndy `addDim` i
where
Right ds `addDim` d = Right (ds, d)
Left e `addDim` _ = Left e
iter (sh, sz) f c r = iter sh (\ix -> iter' (ix,0)) c r
where
iter' (ix,i) | i >= sz = r
| otherwise = f (ix,i) `c` iter' (ix,i+1)
iter1 (_, 0) _ _ = BOUNDS_ERROR(error) "iter1" "empty iteration space"
iter1 (sh, sz) f c = iter1 sh (\ix -> iter1' (ix,0)) c
where
iter1' (ix,i) | i == sz-1 = f (ix,i)
| otherwise = f (ix,i) `c` iter1' (ix,i+1)
rangeToShape ((sh1, sz1), (sh2, sz2))
= (rangeToShape (sh1, sh2), sz2 - sz1 + 1)
shapeToRange (sh, sz)
= let (low, high) = shapeToRange sh
in
((low, 0), (high, sz - 1))
shapeToList (sh,sz) = sz : shapeToList sh
listToShape [] = INTERNAL_ERROR(error) "listToShape" "empty list when converting to Ix"
listToShape (x:xs) = (listToShape xs,x)
-- |Slice representation
--
-- |Class of slice representations (which are nested pairs)
--
class Slice sl where
type SliceShape sl -- the projected slice
type CoSliceShape sl -- the complement of the slice
type FullShape sl -- the combined dimension
-- argument *value* not used; it's just a phantom value to fix the type
sliceIndex :: {-dummy-} sl -> SliceIndex sl (SliceShape sl) (CoSliceShape sl) (FullShape sl)
instance Slice () where
type SliceShape () = ()
type CoSliceShape () = ()
type FullShape () = ()
sliceIndex _ = SliceNil
instance Slice sl => Slice (sl, ()) where
type SliceShape (sl, ()) = (SliceShape sl, Int)
type CoSliceShape (sl, ()) = CoSliceShape sl
type FullShape (sl, ()) = (FullShape sl, Int)
sliceIndex _ = SliceAll (sliceIndex (undefined::sl))
instance Slice sl => Slice (sl, Int) where
type SliceShape (sl, Int) = SliceShape sl
type CoSliceShape (sl, Int) = (CoSliceShape sl, Int)
type FullShape (sl, Int) = (FullShape sl, Int)
sliceIndex _ = SliceFixed (sliceIndex (undefined::sl))
-- |Generalised array index, which may index only in a subset of the dimensions
-- of a shape.
--
data SliceIndex ix slice coSlice sliceDim where
SliceNil :: SliceIndex () () () ()
SliceAll ::
SliceIndex ix slice co dim -> SliceIndex (ix, ()) (slice, Int) co (dim, Int)
SliceFixed ::
SliceIndex ix slice co dim -> SliceIndex (ix, Int) slice (co, Int) (dim, Int)
instance Show (SliceIndex ix slice coSlice sliceDim) where
show SliceNil = "SliceNil"
show (SliceAll rest) = "SliceAll ("++ show rest ++ ")"
show (SliceFixed rest) = "SliceFixed (" ++ show rest ++ ")"
| wilbowma/accelerate | Data/Array/Accelerate/Array/Representation.hs | bsd-3-clause | 6,707 | 0 | 15 | 2,278 | 1,979 | 1,092 | 887 | 98 | 0 |
{-# language ScopedTypeVariables, MultiParamTypeClasses, FlexibleInstances, DeriveDataTypeable #-}
module Sorts.Robots.Cannon where
import Data.Typeable
import Data.Abelian
import Data.Maybe
import Data.Accessor
import Control.Arrow
import Control.Applicative
import System.FilePath
import Physics.Hipmunk as Hipmunk hiding (initChipmunk, body)
import Physics.Chipmunk as CM
import Graphics.Qt as Qt
import Utils
import Base
import Sorts.Robots.Configuration
import Sorts.Robots.Eyes
-- * configuration
-- | angle that the barrel has initially
barrelInitialAngle = - tau / 8
-- | angular velocity with which the barrel can be controlled (radians per second)
barrelAngleVelocity = tau * 0.25
-- | mass of one uber-pixel of a cannonball
cannonballMaterialMass = 50
-- | velocity of a cannonball after being shot
cannonballVelocity = 1500
-- | After a cannonball has been around for its lifespan, it gets removed.
cannonballLifeSpan :: Seconds = 10
-- | how long the robot will keep its eyes closed after shooting
eyesClosedTime :: Seconds = 0.3
-- * sort loading
sorts :: [RM (Maybe Sort_)]
sorts =
singleton $ Just <$> Sort_ <$>
(CannonSort <$>
(loadPix "base-standard_00") <*>
(loadPix "cannon-standard_00") <*>
loadRobotEyesPixmaps <*>
(mkAnimation <$>
mapM loadPix ("cannonball-standard_00" :
"cannonball-standard_01" :
"cannonball-standard_02" :
"cannonball-standard_03" :
[]) <*>
pure cannonballFrameTimes) <*>
(loadSound ("game" </> "cannon_shot") 8) <*>
(loadSound ("game" </> "cannonball_disappear") 8)
)
where
loadPix :: String -> RM Pixmap
loadPix name = do
path <- getDataFileName (pngDir </> "robots" </> "cannon" </> name <.> "png")
loadSymmetricPixmap (Position 1 1) path
data CannonSort = CannonSort {
basePix :: Pixmap,
barrelPix :: Pixmap,
robotEyes :: RobotEyesPixmaps,
ballPixmaps :: Animation Pixmap,
shootSound :: PolySound,
disappearSound :: PolySound
}
deriving (Show, Typeable)
data Cannon
= Cannon {
base :: Chipmunk,
barrel :: Chipmunk,
controlled_ :: Bool,
shotTime_ :: Maybe Seconds,
barrelAngle_ :: Angle,
barrelAngleSetter :: Angle -> IO (),
cannonballs_ :: [Cannonball]
}
deriving (Show, Typeable)
controlled :: Accessor Cannon Bool
controlled = accessor controlled_ (\ a r -> r{controlled_ = a})
shotTime :: Accessor Cannon (Maybe Seconds)
shotTime = accessor shotTime_ (\ a r -> r{shotTime_ = a})
barrelAngle :: Accessor Cannon Angle
barrelAngle = accessor barrelAngle_ (\ a r -> r{barrelAngle_ = a})
cannonballs :: Accessor Cannon [Cannonball]
cannonballs = accessor cannonballs_ (\ a r -> r{cannonballs_ = a})
instance Show (CpFloat -> IO ()) where
show _ = "<CpFloat -> IO ()>"
mapMChipmunks :: (Applicative f, Monad f) => (Chipmunk -> f Chipmunk) -> Cannon -> f Cannon
mapMChipmunks f (Cannon base barrel controlled shotTime angle angleSetter cannonballs) =
Cannon <$>
f base <*>
f barrel <*>
pure controlled <*>
pure shotTime <*>
pure angle <*>
pure angleSetter <*>
fmapM (secondKleisli f) cannonballs
type Cannonball = (Seconds, Chipmunk)
-- | size of the whole robot (background pix)
robotSize = fmap fromUber $ Size 31 28
-- | size of the base of the cannon
baseSize = fmap fromUber $ Size 31 21
baseOffset = size2position (robotSize -~ baseSize)
pinOffset = vmap fromUber $ Vector 8 (- 16)
-- | size of the upright barrel
barrelSize :: Size CpFloat
barrelSize = fmap fromUber $ Size 11 12
barrelOffset = fmap fromUber $ Position 18 (- 24)
maxBarrelAngle = tau / 4
eyesOffset = fmap fromUber $ Position 2 3
-- | offset of newly created cannonballs relative to the barrel
cannonballOffset :: Qt.Position CpFloat
cannonballOffset =
Position (fromUber 5.5) (height barrelSize - barrelChamfer - fromUber 3.5)
instance Sort CannonSort Cannon where
sortId _ = SortId "robots/cannon"
freeSort (CannonSort a b c d e f) =
fmapM_ freePolySound [e, f]
size _ = robotSize
renderIconified sort ptr =
renderPixmapSimple ptr (basePix sort)
initialize app _ Nothing sort ep Nothing _ = do
let baryCenterOffset = size2vector $ fmap (/ 2) $ size sort
position = epToPosition (size sort) ep
base = ImmutableChipmunk position 0 baryCenterOffset []
barrelBaryCenterOffset = size2vector $ fmap (realToFrac . (/ 2)) $ barrelSize
barrel = ImmutableChipmunk (position +~ barrelOffset) barrelInitialAngle barrelBaryCenterOffset []
noopSetter _ = return ()
return $ Cannon base barrel False Nothing barrelInitialAngle noopSetter []
initialize app _ (Just space) sort ep Nothing _ = io $ do
(base, pin) <- initBase space ep
barrel <- initBarrel space ep
angleSetter <- initConstraint space pin base barrel
return $ Cannon base barrel False Nothing barrelInitialAngle angleSetter []
immutableCopy =
mapMChipmunks CM.immutableCopy
chipmunks (Cannon base barrel _ _ _ _ cannonballs) =
base : barrel : map snd cannonballs
getControlledChipmunk _ c = base c -- fromMaybe (base c) (c ^. followedBall)
isUpdating = const True
updateNoSceneChange sort _ config space _ now _ (False, _) =
return . (controlled ^= False) >=>
destroyCannonballs config space now sort >=>
-- passThrough debug >=>
return
updateNoSceneChange sort _ config space scene now contacts (True, cd) =
return . (controlled ^= True) >=>
return . updateAngleState (config ^. controls) cd >=>
passThrough setAngle >=>
destroyCannonballs config space now sort >=>
shootCannonball config space now cd sort >=>
-- passThrough debug >=>
return
renderObject _ _ cannon sort ptr offset now = do
(basePosition, baseAngle) <- getRenderPositionAndAngle (base cannon)
(barrelPosition, barrelAngle) <- getRenderPositionAndAngle $ barrel cannon
let base = RenderPixmap (basePix sort)
(basePosition -~ rotatePosition (realToFrac baseAngle) baseOffset)
(Just baseAngle)
barrel = RenderPixmap (barrelPix sort) barrelPosition (Just barrelAngle)
eyes = renderRobotEyes (robotEyes sort) basePosition baseAngle eyesOffset
(robotEyesState now cannon) now
cannonballs <- fmapM (mkCannonballRenderPixmap sort) (cannon ^. cannonballs)
return (cannonballs ++ barrel : base : eyes : [])
debug c =
debugChipmunk (base c) >>
debugChipmunk (barrel c) >>
fmapM_ debugChipmunk (map snd $ (c ^. cannonballs)) >>
ppp (c ^. shotTime) >>
debugBarrelAngle (barrel c)
debugChipmunk chip = do
(pos, angle) <- first position2vector <$> getRenderPositionAndAngle chip
debugPoint yellow pos
debugPoint pink (rotateVector angle (baryCenterOffset chip) +~ pos)
debugBarrelAngle barrel = do
(p, a) <- first position2vector <$> getRenderPositionAndAngle barrel
let av = vmap (* (cannonballVelocity * 100))
(fromAngle (a -~ tau / 4))
debugLine yellow p (p +~ av)
shapeAttributes = robotShapeAttributes
initBase space ep = do
let baryCenterOffset = size2vector $ fmap (/ 2) baseSize
start = negateAbelian end
end = baryCenterOffset
shapeType = mkRectFromPositions start end
shape = mkShapeDescription shapeAttributes shapeType
pos = position2vector (epToPosition robotSize ep)
+~ baryCenterOffset +~ position2vector baseOffset
pin = pos +~ pinOffset
attributes =
mkMaterialBodyAttributes robotMaterialMass [shapeType] pos
c <- initChipmunk space attributes [shape] baryCenterOffset
return (c, pin)
initBarrel space ep = do
let baryCenterOffset = size2vector $ fmap (realToFrac . (/ 2)) barrelSize
start = negateAbelian baryCenterOffset
shapeTypes = barrelShapeTypes start
shapes = map (mkShapeDescription shapeAttributes) shapeTypes
pos = position2vector (epToPosition (fmap realToFrac barrelSize) ep)
+~ baryCenterOffset +~ position2vector barrelOffset
attributes =
inertia ^: (* 100) $
mkMaterialBodyAttributes robotMaterialMass shapeTypes pos
c <- initChipmunk space attributes shapes baryCenterOffset
return c
barrelShapeTypes start =
leftSide :
bottom :
rightSide :
[]
where
leftSide = side start
rightSide = side (start +~ Vector (width - wallThickness) 0)
side start = Polygon (
start :
start +~ Vector 0 (height - barrelChamfer) :
start +~ Vector wallThickness (height - barrelChamfer) :
start +~ Vector wallThickness 0 :
[])
bottom = Polygon (
start +~ Vector 0 (height - barrelChamfer) :
start +~ Vector barrelChamfer height :
start +~ Vector (width - barrelChamfer) height :
start +~ Vector width (height - barrelChamfer) :
[])
wallThickness = fromUber 1
size@(Vector width height) = size2vector $ fmap realToFrac barrelSize
barrelChamfer = fromUber 3
initConstraint :: Space -> Vector -> Chipmunk -> Chipmunk -> IO (Angle -> IO ())
initConstraint space pin base barrel = do
pivot <- newConstraint (body base) (body barrel) (Pivot1 pin)
spaceAdd space pivot
let consValues = DampedRotarySpring {
dampedRotRestAngle = barrelInitialAngle,
dampedRotStiffness = 8000000000,
dampedRotDamping = 80000000
}
rotary <- newConstraint (body base) (body barrel) consValues
spaceAdd space rotary
rotateBarrel barrel pin
let setter angle =
redefineC rotary consValues{dampedRotRestAngle = angle}
return setter
-- | rotates the barrel in its initial position, specified by barrelInitialAngle
rotateBarrel barrel pin = do
pos <- getPosition barrel
angle (body barrel) $= (- barrelInitialAngle)
Hipmunk.position (body barrel) $= (rotateVectorAround pin (- barrelInitialAngle) pos)
-- * updating
updateAngleState :: Controls -> ControlData -> Cannon -> Cannon
updateAngleState controls cd =
if isGameLeftHeld controls cd then
barrelAngle ^: ((+ angleStep) >>> clipAngle)
else if isGameRightHeld controls cd then
barrelAngle ^: ((subtract angleStep) >>> clipAngle)
else
id
where
clipAngle a = min maxBarrelAngle $ max (- maxBarrelAngle) a
angleStep = barrelAngleVelocity * subStepQuantum
setAngle :: Cannon -> IO ()
setAngle c =
barrelAngleSetter c (c ^. barrelAngle)
-- * eyes
robotEyesState :: Seconds -> Cannon -> RobotEyesState
robotEyesState now cannon = case (cannon ^. controlled, cannon ^. shotTime) of
(True, Just shotTime) ->
if now - shotTime < eyesClosedTime then Closed else Active
(True, Nothing) -> Active
(False, _) -> Closed
-- * cannon balls
-- | Removes cannonballs after their lifetime exceeded.
destroyCannonballs :: Configuration -> Space -> Seconds -> CannonSort -> Cannon -> IO Cannon
destroyCannonballs config space now sort =
cannonballs ^^: (\ bs -> catMaybes <$> mapM inner bs)
where
inner :: Cannonball -> IO (Maybe Cannonball)
inner cb@(time, chip) =
if now - time > cannonballLifeSpan then do
-- cannonball gets removed
playDisappearSound config sort
removeChipmunk chip
return Nothing
else
return $ Just cb
shootCannonball :: Configuration -> Space -> Seconds -> ControlData
-> CannonSort -> Cannon -> IO Cannon
shootCannonball config space now cd sort cannon | isRobotActionPressed (config ^. controls) cd = do
playShootSound config sort
ball <- mkCannonball space cannon
return $
shotTime ^= Just now $
cannonballs ^: ((now, ball) :) $
cannon
shootCannonball _ _ _ _ _ c = return c
mkCannonball :: Space -> Cannon -> IO Chipmunk
mkCannonball space cannon = do
(barrelPosition, barrelAngle) <- getRenderPositionAndAngle (barrel cannon)
let ball = Circle (fromUber 3.5)
ballDesc = mkShapeDescription cannonballShapeAttributes ball
baryCenterOffset = vmap fromUber (Vector 3.5 3.5)
pos = position2vector
(barrelPosition +~ rotatePosition (realToFrac barrelAngle)
(fmap realToFrac cannonballOffset))
cannonballAttributes =
mkMaterialBodyAttributes cannonballMaterialMass [ball] pos
cMass = CM.mass cannonballAttributes
chip <- initChipmunk space cannonballAttributes [ballDesc] baryCenterOffset
let impulse = vmap (* (cannonballVelocity * cMass))
(fromAngle (barrelAngle -~ tau / 4))
modifyApplyImpulse chip impulse
-- apply a backstroke to the barrel
modifyApplyImpulse (barrel cannon) (negateAbelian impulse)
return chip
cannonballShapeAttributes = ShapeAttributes{
CM.elasticity = 0.4,
CM.friction = 0.2,
CM.collisionType = RobotCT
}
mkCannonballRenderPixmap :: CannonSort -> Cannonball -> IO RenderPixmap
mkCannonballRenderPixmap sort (_, chip) = do
(chipPos, angle) <- getChipmunkPosition chip
let renderPos = vector2position chipPos -~ baryCenterOffset
pixmap = pickAnimationFrame (ballPixmaps sort) angle
return $ RenderPixmap pixmap renderPos Nothing
where
baryCenterOffset = fmap fromUber $ Position 3.5 3.5
-- | Cannonball pixmaps are not rotated, cannonballs have animated spec lights.
-- This is the angular range for one animation frame.
specAngleRange = tau / (specAnimationFrameNumber * 2) -- doubled animation speed
specAnimationFrameNumber = 4
cannonballFrameTimes = [specAngleRange]
-- * Sounds
playShootSound :: Configuration -> CannonSort -> IO ()
playShootSound c = triggerSound c . shootSound
playDisappearSound :: Configuration -> CannonSort -> IO ()
playDisappearSound c = triggerSound c . disappearSound
| geocurnoff/nikki | src/Sorts/Robots/Cannon.hs | lgpl-3.0 | 14,185 | 0 | 19 | 3,496 | 3,912 | 1,997 | 1,915 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="es-ES">
<title>>Run Applications | ZAP Extensions</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Índice</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Buscar</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/invoke/src/main/javahelp/org/zaproxy/zap/extension/invoke/resources/help_es_ES/helpset_es_ES.hs | apache-2.0 | 984 | 76 | 55 | 159 | 419 | 211 | 208 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pl-PL">
<title>Directory List v1.0</title>
<maps>
<homeID>directorylistv1</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/directorylistv1/src/main/javahelp/help_pl_PL/helpset_pl_PL.hs | apache-2.0 | 976 | 78 | 66 | 157 | 412 | 209 | 203 | -1 | -1 |
module A3 where
import Control.Parallel.Strategies (rpar, runEval)
f = n1_2 + n2 + 1
where
n1 = fib 23
n2 = fib 24
fib n | n <= 1 = 1
| otherwise = fib (n-1) + fib (n-2) + 1
n1_2
=
runEval
(do n1_2 <- rpar n1
return n1_2)
| RefactoringTools/HaRe | old/testing/evalMonad/A3_TokOut.hs | bsd-3-clause | 306 | 0 | 12 | 135 | 131 | 66 | 65 | 12 | 1 |
{-# language ConstraintKinds, FlexibleContexts, TypeFamilies,
UndecidableInstances, DeriveFunctor #-}
module T13320 where
import GHC.Exts (Constraint)
data QCGen
newtype Gen a = MkGen { unGen :: QCGen -> Int -> a }
deriving Functor
sized :: (Int -> Gen a) -> Gen a
sized f = MkGen (\r n -> let MkGen m = f n in m r n)
class Arbitrary a where
arbitrary :: Gen a
type family X_Var ξ
data TermX ξ = Var (X_Var ξ)
type ForallX (φ :: * -> Constraint) ξ = ( φ (X_Var ξ) )
-- This type signature used to be necessary to prevent the
-- type checker from looping.
-- genTerm :: ForallX Arbitrary ξ => Int -> Gen (TermX ξ)
genTerm 0 = Var <$> arbitrary
genTerm n = Var <$> genTerm (n - 1)
instance ForallX Arbitrary ξ => Arbitrary (TermX ξ) where
arbitrary = sized genTerm
| ezyang/ghc | testsuite/tests/typecheck/should_fail/T13320.hs | bsd-3-clause | 802 | 0 | 12 | 175 | 246 | 133 | 113 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_HADDOCK hide #-}
module Distribution.Compat.Internal.TempFile (
openTempFile,
openBinaryTempFile,
openNewBinaryFile,
createTempDirectory,
) where
import Distribution.Compat.Exception
import System.FilePath ((</>))
import Foreign.C (CInt, eEXIST, getErrno, errnoToIOError)
import System.IO (Handle, openTempFile, openBinaryTempFile)
import Data.Bits ((.|.))
import System.Posix.Internals (c_open, c_close, o_CREAT, o_EXCL, o_RDWR,
o_BINARY, o_NONBLOCK, o_NOCTTY,
withFilePath, c_getpid)
import System.IO.Error (isAlreadyExistsError)
import GHC.IO.Handle.FD (fdToHandle)
import Control.Exception (onException)
#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS)
import System.Directory ( createDirectory )
#else
import qualified System.Posix
#endif
-- ------------------------------------------------------------
-- * temporary files
-- ------------------------------------------------------------
-- This is here for Haskell implementations that do not come with
-- System.IO.openTempFile. This includes nhc-1.20, hugs-2006.9.
-- TODO: Not sure about JHC
-- TODO: This file should probably be removed.
-- This is a copy/paste of the openBinaryTempFile definition, but
-- if uses 666 rather than 600 for the permissions. The base library
-- needs to be changed to make this better.
openNewBinaryFile :: FilePath -> String -> IO (FilePath, Handle)
openNewBinaryFile dir template = do
pid <- c_getpid
findTempName pid
where
-- We split off the last extension, so we can use .foo.ext files
-- for temporary files (hidden on Unix OSes). Unfortunately we're
-- below file path in the hierarchy here.
(prefix,suffix) =
case break (== '.') $ reverse template of
-- First case: template contains no '.'s. Just re-reverse it.
(rev_suffix, "") -> (reverse rev_suffix, "")
-- Second case: template contains at least one '.'. Strip the
-- dot from the prefix and prepend it to the suffix (if we don't
-- do this, the unique number will get added after the '.' and
-- thus be part of the extension, which is wrong.)
(rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
-- Otherwise, something is wrong, because (break (== '.')) should
-- always return a pair with either the empty string or a string
-- beginning with '.' as the second component.
_ -> error "bug in System.IO.openTempFile"
oflags = rw_flags .|. o_EXCL .|. o_BINARY
findTempName x = do
fd <- withFilePath filepath $ \ f ->
c_open f oflags 0o666
if fd < 0
then do
errno <- getErrno
if errno == eEXIST
then findTempName (x+1)
else ioError (errnoToIOError "openNewBinaryFile" errno Nothing (Just dir))
else do
-- TODO: We want to tell fdToHandle what the file path is,
-- as any exceptions etc will only be able to report the
-- FD currently
h <- fdToHandle fd `onException` c_close fd
return (filepath, h)
where
filename = prefix ++ show x ++ suffix
filepath = dir `combine` filename
-- FIXME: bits copied from System.FilePath
combine a b
| null b = a
| null a = b
| last a == pathSeparator = a ++ b
| otherwise = a ++ [pathSeparator] ++ b
-- FIXME: Should use System.FilePath library
pathSeparator :: Char
#ifdef mingw32_HOST_OS
pathSeparator = '\\'
#else
pathSeparator = '/'
#endif
-- FIXME: Copied from GHC.Handle
std_flags, output_flags, rw_flags :: CInt
std_flags = o_NONBLOCK .|. o_NOCTTY
output_flags = std_flags .|. o_CREAT
rw_flags = output_flags .|. o_RDWR
createTempDirectory :: FilePath -> String -> IO FilePath
createTempDirectory dir template = do
pid <- c_getpid
findTempName pid
where
findTempName x = do
let dirpath = dir </> template ++ "-" ++ show x
r <- tryIO $ mkPrivateDir dirpath
case r of
Right _ -> return dirpath
Left e | isAlreadyExistsError e -> findTempName (x+1)
| otherwise -> ioError e
mkPrivateDir :: String -> IO ()
#if defined(mingw32_HOST_OS) || defined(ghcjs_HOST_OS)
mkPrivateDir s = createDirectory s
#else
mkPrivateDir s = System.Posix.createDirectory s 0o700
#endif
| tolysz/prepare-ghcjs | spec-lts8/cabal/Cabal/Distribution/Compat/Internal/TempFile.hs | bsd-3-clause | 4,558 | 0 | 17 | 1,230 | 809 | 445 | 364 | 67 | 5 |
{-# LANGUAGE QuasiQuotes #-}
module Test where
import QQ
f :: [pq| foo |] -- Expands to Int -> Int
[pq| blah |] -- Expands to f x = x
h [pq| foo |] = f [$pq| blah |] * 8
-- Expands to h (Just x) = f (x+1) * 8
| urbanslug/ghc | testsuite/tests/quasiquotation/qq008/Test.hs | bsd-3-clause | 225 | 1 | 8 | 68 | 56 | 37 | 19 | 6 | 1 |
module Main (main) where
import C
main :: IO ()
main = putStrLn c
| urbanslug/ghc | testsuite/tests/driver/dynamicToo/dynamicToo004/prog.hs | bsd-3-clause | 69 | 0 | 6 | 17 | 30 | 17 | 13 | 4 | 1 |
module ShouldSucceed where
j = 2
k = 1:j:l
l = 0:k
m = j+j
| urbanslug/ghc | testsuite/tests/typecheck/should_compile/tc007.hs | bsd-3-clause | 63 | 0 | 6 | 19 | 40 | 23 | 17 | 5 | 1 |
{-
Copyright (C) 2015 Braden Walters
This file is licensed under the MIT Expat License. See LICENSE.txt.
-}
module FollowTable
( FollowTableEntry(..)
, FollowTable(..)
, buildFollowTable
, searchByKey
) where
import Data.Functor
import Data.List
import Data.Maybe
import Rules
import StartEndTable
data FollowTableEntry =
FollowTableEntry
{ followKey :: Regex
, followVal :: [Regex] }
newtype FollowTable = FollowTable { followTableEntries :: [FollowTableEntry] }
instance Show FollowTableEntry where
show entry@(FollowTableEntry key gotos) =
showRegexType key ++ " | " ++ concat ((++ " ") <$> showRegexType <$> gotos)
instance Show FollowTable where
show table@(FollowTable (x:xs)) = show x ++ "\n" ++ (show $ FollowTable xs)
show table@(FollowTable []) = []
buildFollowTable :: StartEndTable -> FollowTable
buildFollowTable seTable@(StartEndTable entries) =
let partialFollowTables = map seEntryToFollow entries
in mergeTables partialFollowTables
seEntryToFollow :: StartEndTableEntry -> FollowTable
seEntryToFollow entry@(StartEndTableEntry rx@(RxAnd r1 r2) _ _ _) =
let r1Last = lastRx r1
r2First = firstRx r2
in FollowTable $ map (\key -> FollowTableEntry key r2First) r1Last
seEntryToFollow entry@(StartEndTableEntry rx@(RxMany r) _ _ _) =
let rLast = lastRx r
rFirst = firstRx r
in FollowTable $ map (\key -> FollowTableEntry key rFirst) rLast
seEntryToFollow entry@(StartEndTableEntry rx@(RxSome r) _ _ _) =
let rLast = lastRx r
rFirst = firstRx r
in FollowTable $ map (\key -> FollowTableEntry key rFirst) rLast
seEntryToFollow _ = FollowTable []
mergeTables :: [FollowTable] -> FollowTable
mergeTables tables =
let entriesByKey = groupedEntriesByKey $ allEntries tables
entryResults = catMaybes $ map mergeEntriesOfOneKey entriesByKey
in FollowTable entryResults
allEntries :: [FollowTable] -> [FollowTableEntry]
allEntries tables = concat $ map (\table@(FollowTable e) -> e) tables
groupedEntriesByKey :: [FollowTableEntry] -> [[FollowTableEntry]]
groupedEntriesByKey entries =
let groupFunc (FollowTableEntry l _) (FollowTableEntry r _) = l == r
in filter (not . null) $ groupUnsortedBy groupFunc entries
groupUnsortedBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupUnsortedBy f [] = []
groupUnsortedBy f (cur:rest) =
let (same, different) = partition (f cur) rest
in (cur:same):(groupUnsortedBy f different)
mergeEntriesOfOneKey :: [FollowTableEntry] -> Maybe FollowTableEntry
mergeEntriesOfOneKey [] = Nothing
mergeEntriesOfOneKey entries =
let (FollowTableEntry key _) = head entries
gotos = nub $ concat $ map (\(FollowTableEntry _ g) -> g) entries
in Just $ FollowTableEntry key gotos
searchByKey :: FollowTable -> Regex -> Maybe FollowTableEntry
searchByKey (FollowTable followTableEntries) regex =
let searchEntries [] _ = Nothing
searchEntries (entry@(FollowTableEntry key _):rest) regex =
if key == regex then Just entry else searchEntries rest regex
in searchEntries followTableEntries regex
| meoblast001/lexical-analyser-generator | src/FollowTable.hs | mit | 3,019 | 0 | 14 | 508 | 1,014 | 527 | 487 | 67 | 3 |
module Main where
import LI11718
import qualified Tarefa3_2017li1g186 as T3
import System.Environment
import Text.Read
main = do
args <- getArgs
case args of
["movimenta"] -> do
str <- getContents
let params = readMaybe str
case params of
Nothing -> error "parâmetros inválidos"
Just (mapa,tempo,carro) -> print $ T3.movimenta mapa tempo carro
["testes"] -> print $ T3.testesT3
otherwise -> error "RunT3 argumentos inválidos" | hpacheco/HAAP | examples/plab/svn/2017li1g186/src/RunT3.hs | mit | 531 | 0 | 17 | 164 | 141 | 73 | 68 | 16 | 4 |
{-|
Module : EU4.Modifiers
Description : Country, ruler, province and opinion modifiers
-}
module EU4.Modifiers (
parseEU4Modifiers, writeEU4Modifiers
, parseEU4OpinionModifiers, writeEU4OpinionModifiers
) where
import Control.Arrow ((&&&))
import Control.Monad (foldM, forM, join)
import Control.Monad.Except (MonadError (..))
import Control.Monad.Trans (MonadIO (..))
import Data.Maybe (fromJust, catMaybes)
import Data.Monoid ((<>))
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import Data.Text (Text)
import qualified Data.Text as T
import Abstract -- everything
import QQ (pdx)
import SettingsTypes ( PPT{-, Settings (..)-}{-, Game (..)-}
{-, IsGame (..)-}, IsGameData (..), IsGameState (..), GameState (..)
{-, getGameL10n-}, getGameL10nIfPresent
, setCurrentFile, withCurrentFile
, hoistErrors, hoistExceptions)
import EU4.Types -- everything
import Debug.Trace (trace, traceM)
parseEU4Modifiers :: (IsGameData (GameData g), IsGameState (GameState g), Monad m) =>
HashMap String GenericScript -> PPT g m (HashMap Text EU4Modifier)
parseEU4Modifiers scripts = HM.unions . HM.elems <$> do
tryParse <- hoistExceptions $
HM.traverseWithKey
(\sourceFile scr ->
setCurrentFile sourceFile $ mapM parseEU4Modifier scr)
scripts
case tryParse of
Left err -> do
traceM $ "Completely failed parsing modifiers: " ++ T.unpack err
return HM.empty
Right modifiersFilesOrErrors ->
flip HM.traverseWithKey modifiersFilesOrErrors $ \sourceFile emods ->
fmap (mkModMap . catMaybes) . forM emods $ \case
Left err -> do
traceM $ "Error parsing modifiers in " ++ sourceFile
++ ": " ++ T.unpack err
return Nothing
Right mmod -> return mmod
where mkModMap :: [EU4Modifier] -> HashMap Text EU4Modifier
mkModMap = HM.fromList . map (modName &&& id)
parseEU4Modifier :: (IsGameData (GameData g), IsGameState (GameState g), MonadError Text m) =>
GenericStatement -> PPT g m (Either Text (Maybe EU4Modifier))
parseEU4Modifier [pdx| $modid = @effects |]
= withCurrentFile $ \file -> do
mlocid <- getGameL10nIfPresent modid
return . Right . Just $ EU4Modifier {
modName = modid
, modLocName = mlocid
, modPath = file
, modEffects = effects
}
parseEU4Modifier _ = withCurrentFile $ \file ->
throwError ("unrecognised form for modifier in " <> T.pack file)
-- | Present the parsed modifiers as wiki text and write them to the
-- appropriate files.
writeEU4Modifiers :: (EU4Info g, MonadError Text m, MonadIO m) => PPT g m ()
writeEU4Modifiers = throwError "Sorry, writing all modifiers currently not supported."
parseEU4OpinionModifiers :: (IsGameState (GameState g), IsGameData (GameData g), Monad m) =>
HashMap String GenericScript -> PPT g m (HashMap Text EU4OpinionModifier)
parseEU4OpinionModifiers scripts = HM.unions . HM.elems <$> do
tryParse <- hoistExceptions $
HM.traverseWithKey
(\sourceFile scr ->
setCurrentFile sourceFile $ mapM parseEU4OpinionModifier scr)
scripts
case tryParse of
Left err -> do
traceM $ "Completely failed parsing opinion modifiers: " ++ T.unpack err
return HM.empty
Right modifiersFilesOrErrors ->
flip HM.traverseWithKey modifiersFilesOrErrors $ \sourceFile emods ->
fmap (mkModMap . catMaybes) . forM emods $ \case
Left err -> do
traceM $ "Error parsing modifiers in " ++ sourceFile
++ ": " ++ T.unpack err
return Nothing
Right mmod -> return mmod
where mkModMap :: [EU4OpinionModifier] -> HashMap Text EU4OpinionModifier
mkModMap = HM.fromList . map (omodName &&& id)
newEU4OpinionModifier id locid path = EU4OpinionModifier id locid path Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- | Parse a statement in an opinion modifiers file. Some statements aren't
-- modifiers; for those, and for any obvious errors, return Right Nothing.
parseEU4OpinionModifier :: (IsGameState (GameState g), IsGameData (GameData g), MonadError Text m) =>
GenericStatement -> PPT g m (Either Text (Maybe EU4OpinionModifier))
parseEU4OpinionModifier (StatementBare _) = throwError "bare statement at top level"
parseEU4OpinionModifier [pdx| %left = %right |] = case right of
CompoundRhs parts -> case left of
CustomLhs _ -> throwError "internal error: custom lhs"
IntLhs _ -> throwError "int lhs at top level"
AtLhs _ -> return (Right Nothing)
GenericLhs id [] -> withCurrentFile $ \file -> do
locid <- getGameL10nIfPresent id
mmod <- hoistErrors $ foldM opinionModifierAddSection
(Just (newEU4OpinionModifier id locid file))
parts
case mmod of
Left err -> return (Left err)
Right Nothing -> return (Right Nothing)
Right (Just mod) -> withCurrentFile $ \file ->
return (Right (Just mod ))
_ -> throwError "unrecognized form for opinion modifier"
_ -> throwError "unrecognized form for opinion modifier"
parseEU4OpinionModifier _ = withCurrentFile $ \file ->
throwError ("unrecognised form for opinion modifier in " <> T.pack file)
-- | Interpret one section of an opinion modifier. If understood, add it to the
-- event data. If not understood, throw an exception.
opinionModifierAddSection :: (IsGameState (GameState g), MonadError Text m) =>
Maybe EU4OpinionModifier -> GenericStatement -> PPT g m (Maybe EU4OpinionModifier)
opinionModifierAddSection Nothing _ = return Nothing
opinionModifierAddSection mmod stmt
= sequence (opinionModifierAddSection' <$> mmod <*> pure stmt)
where
opinionModifierAddSection' mod stmt@[pdx| opinion = !rhs |]
= return (mod { omodOpinion = Just rhs })
opinionModifierAddSection' mod stmt@[pdx| max = !rhs |]
= return (mod { omodMax = Just rhs })
opinionModifierAddSection' mod stmt@[pdx| min = !rhs |]
= return (mod { omodMin = Just rhs })
opinionModifierAddSection' mod stmt@[pdx| yearly_decay = !rhs |]
= return (mod { omodYearlyDecay = Just rhs })
opinionModifierAddSection' mod stmt@[pdx| months = !rhs |]
= return (mod { omodMonths = Just rhs })
opinionModifierAddSection' mod stmt@[pdx| years = !rhs |]
= return (mod { omodYears = Just rhs })
opinionModifierAddSection' mod stmt@[pdx| max_vassal = !rhs |]
= return (mod { omodMaxVassal = Just rhs })
opinionModifierAddSection' mod stmt@[pdx| max_in_other_direction = !rhs |]
= return (mod { omodMaxInOtherDirection = Just rhs })
opinionModifierAddSection' mod [pdx| $other = %_ |]
= trace ("unknown opinion modifier section: " ++ T.unpack other) $ return mod
opinionModifierAddSection' mod _
= trace ("unrecognised form for opinion modifier section") $ return mod
writeEU4OpinionModifiers :: (IsGameState (GameState g), MonadError Text m) =>
GenericStatement -> PPT g m (Either Text (Maybe EU4OpinionModifier))
writeEU4OpinionModifiers _ = throwError "Sorry, writing all opinion modifiers not yet supported."
| HairyDude/pdxparse | src/EU4/Modifiers.hs | mit | 7,795 | 0 | 24 | 2,172 | 1,922 | 1,008 | 914 | -1 | -1 |
module Weapons.Rifles where
import Weapon
import Damage
amprex :: Weapon
amprex = Weapon {
accuracy=1.0,
capacity=540,
critChance=0.5,
critMultiplier=2.0,
damage=[Damage 7.5 Electricity],
fireRate=20,
magazine=100,
multishot=0,
name="Amprex",
reload=2.7,
status=0.011,
weaponType=Rifle
}
boltorPrime :: Weapon
boltorPrime = Weapon {
accuracy=0.5,
capacity=540,
critChance=0.05,
critMultiplier=2.0,
damage=[Damage 5.5 Impact, Damage 49.5 Puncture],
fireRate=10.0,
magazine=60,
multishot=0,
name="Boltor Prime",
reload=2.4,
status=0.10,
weaponType=Rifle
}
bratonPrime :: Weapon
bratonPrime = Weapon {
accuracy=0.286,
capacity=540,
critChance=0.1,
critMultiplier=1.5,
damage=[Damage 1.3 Impact, Damage 8.8 Puncture, Damage 15 Slash],
fireRate=8.8,
magazine=50,
multishot=0,
name="Braton Prime",
reload=2.2,
status=0.1,
weaponType=Rifle
}
dera :: Weapon
dera = Weapon {
accuracy=1,
capacity=540,
critChance=0.025,
critMultiplier=1.5,
damage=[Damage 1.1 Slash, Damage 16.5 Puncture, Damage 4.4 Impact],
fireRate=11.3,
magazine=45,
multishot=0,
name="Dera",
reload=2.37,
status=0.1,
weaponType=Rifle
}
dread :: Weapon
dread = Weapon {
accuracy=1.0,
capacity=72,
critChance=0.50,
critMultiplier=2.0,
damage=[Damage 10 Impact, Damage 10 Puncture, Damage 180 Slash],
fireRate=0.5,
magazine=1,
multishot=0,
name="Dread",
reload=0.8,
status=0.20,
weaponType=Bow
}
glaxion :: Weapon
glaxion = Weapon {
accuracy=0.125,
capacity=1500,
critChance=0.05,
critMultiplier=2.0,
damage=[Damage 12.5 Cold],
fireRate=20.0,
magazine=300,
multishot=0,
name="Glaxion",
reload=1.5,
status=0.04,
weaponType=Rifle
}
grakata :: Weapon
grakata = Weapon {
accuracy=0.286,
capacity=800,
critChance=0.25,
critMultiplier=2,
damage=[Damage 2.9 Slash, Damage 3.7 Puncture, Damage 4.4 Impact],
fireRate=20,
magazine=60,
multishot=0,
name="Grakata",
reload=2.4,
status=0.2,
weaponType=Rifle
}
karak :: Weapon
karak = Weapon {
accuracy=0.286,
capacity=540,
critChance=0.025,
critMultiplier=1.5,
damage=[Damage 6.8 Slash, Damage 8.1 Puncture, Damage 12.1 Impact],
fireRate=11.7,
magazine=30,
multishot=0,
name="Karak",
reload=2.0,
status=0.075,
weaponType=Rifle
}
lanka :: Weapon
lanka = Weapon {
accuracy=1.0,
capacity=72,
critChance=0.25,
critMultiplier=2.0,
damage=[Damage 300 Electricity],
fireRate=0.7,
magazine=10,
multishot=0,
name="Lanka",
reload=2.0,
status=0.25,
weaponType=Sniper
}
latron :: Weapon
latron = Weapon {
accuracy=0.286,
capacity=540,
critChance=0.1,
critMultiplier=2,
damage=[Damage 8 Impact, Damage 38 Puncture, Damage 8 Slash],
fireRate=4.2,
magazine=15,
multishot=0,
name="Latron",
reload=2.4,
status=0.1,
weaponType=Rifle
}
latronWraith :: Weapon
latronWraith = Weapon {
accuracy=0.286,
capacity=540,
critChance=0.25,
critMultiplier=2.5,
damage=[Damage 13.8 Impact, Damage 38.5 Puncture, Damage 2.7 Slash],
fireRate=5.4,
magazine=15,
multishot=0,
name="Latron Wraith",
reload=2.4,
status=0.20,
weaponType=Rifle
}
opticor :: Weapon
opticor = Weapon {
accuracy=1.0,
capacity=540,
critChance=0.15,
critMultiplier=2.0,
damage=[Damage 50 Slash, Damage 850 Puncture, Damage 100 Impact],
-- damage=[Damage 25 Slash, Damage 425 Puncture, Damage 50 Impact],
fireRate=0.3,
-- fireRate=0.6,
magazine=5,
multishot=0,
name="Opticor",
reload=2.0,
status=0.15,
weaponType=Rifle
}
parisPrime :: Weapon
parisPrime = Weapon {
accuracy=1.0,
capacity=72,
critChance=0.45,
critMultiplier=2.0,
damage=[Damage 5 Impact, Damage 160 Puncture, Damage 35 Slash],
fireRate=0.5,
magazine=1,
multishot=0,
name="Paris Prime",
reload=0.7,
status=0.20,
weaponType=Bow
}
quanta :: Weapon
quanta = Weapon {
accuracy=1.0,
capacity=540,
critChance=0.10,
critMultiplier=2.0,
damage=[Damage 220 Electricity],
fireRate=1.0,
magazine=60,
multishot=0,
name="Quanta",
reload=2.0,
status=0.1,
weaponType=Rifle
}
quantaDetonate :: Weapon
quantaDetonate = Weapon {
accuracy=1.0,
capacity=540,
critChance=0.10,
critMultiplier=2.0,
damage=[Damage 400 Blast],
fireRate=1.0,
magazine=5,
multishot=0,
name="Quanta",
reload=2.0,
status=0.1,
weaponType=Rifle
}
soma :: Weapon
soma = Weapon {
accuracy=0.286,
capacity=540,
critChance=0.3,
critMultiplier=3,
damage=[Damage 5 Slash, Damage 4 Puncture, Damage 1 Impact],
fireRate=15,
magazine=100,
multishot=0,
name="Soma",
reload=3,
status=0.07,
weaponType=Rifle
}
snipetronVandal :: Weapon
snipetronVandal = Weapon {
accuracy=0.133,
capacity=72,
critChance=0.25,
critMultiplier=2.0,
damage=[Damage 7.5 Impact, Damage 135 Puncture, Damage 7.5 Slash],
fireRate=1.5,
magazine=6,
multishot=0,
name="Snipetron Vandal",
reload=2.0,
status=0.25,
weaponType=Sniper
}
synapse :: Weapon
synapse = Weapon {
accuracy=0.125,
capacity=540,
critChance=0.50,
critMultiplier=2.0,
damage=[Damage 12.5 Electricity],
fireRate=10,
magazine=100,
multishot=0,
name="Synapse",
reload=1.0,
status=0.025,
weaponType=Rifle
}
tiberion :: Weapon
tiberion = Weapon {
accuracy=0.333,
capacity=540,
critChance=0.05,
critMultiplier=2,
damage=[Damage 15 Slash, Damage 30 Puncture, Damage 15 Impact],
fireRate=6.7,
magazine=30,
multishot=0,
name="Tiberion",
reload=2.3,
status=0.025,
weaponType=Rifle
}
vectis :: Weapon
vectis = Weapon {
accuracy=0.133,
capacity=72,
critChance=0.25,
critMultiplier=2.0,
damage=[Damage 90 Impact, Damage 78.8 Puncture, Damage 56.3 Slash],
fireRate=1.5,
magazine=1,
multishot=0,
name="Vectis",
reload=0.9,
status=0.30,
weaponType=Sniper
}
vulkar :: Weapon
vulkar = Weapon {
accuracy=0.133,
capacity=72,
critChance=0.20,
critMultiplier=2.0,
damage=[Damage 160 Impact, Damage 30 Puncture, Damage 10 Slash],
fireRate=1.5,
magazine=6,
multishot=0,
name="Vulkar",
reload=3.0,
status=0.25,
weaponType=Sniper
}
| m4rw3r/warframe-dmg-hs | src/weapons/rifles.hs | mit | 6,688 | 0 | 8 | 1,678 | 2,178 | 1,365 | 813 | 297 | 1 |
{-# LANGUAGE DeriveGeneric #-}
------------------------------------------------------------------------------
-- |
-- Module : Mahjong.Kyoku.Internal
-- Copyright : (C) 2014 Samuli Thomasson
-- License : MIT (see the file LICENSE)
-- Maintainer : Samuli Thomasson <samuli.thomasson@paivola.fi>
-- Stability : experimental
-- Portability : non-portable
------------------------------------------------------------------------------
module Mahjong.Kyoku.Internal where
import Import
import Mahjong.Tiles
import Mahjong.Configuration
import Mahjong.Hand.Mentsu
import Mahjong.Kyoku.Flags
------------------------------------------------------------------------------
import Mahjong.Hand.Internal
import Mahjong.Hand.Algo
------------------------------------------------------------------------------
import qualified Data.Map as Map
import qualified Data.List as L
import System.Random.Shuffle (shuffleM)
import System.Random (randomRIO)
import qualified Text.PrettyPrint.ANSI.Leijen as P
------------------------------------------------------------------------------
-- * Types
-- | Game state, including current round state.
--
-- Fields starting @_p@ are for public consumption and @_s@ for internal
-- only.
data Kyoku = Kyoku
-- always public
{ _pRound :: Round
, _pTurn :: Kaze -- ^ Current player in turn
, _pOja :: Player -- ^ TODO is field this necessary?
, _pFirstOja :: Player
, _pWallTilesLeft :: Int -- ^ A public aggregate of sWall
, _pDora :: [Tile] -- ^ Indicators
, _pPlayers :: Map Kaze (Player, Points, Text)
, _pHonba :: Int
, _pRiichi :: Int -- ^ Points in table for riichi
, _pResults :: Maybe KyokuResults
, _pFlags :: Set Flag -- ^ List of extendable flags active in the game.
-- secret
, _sEventHistory :: [GameEvent] -- ^ Complete history of events applied in this kyoku, latest first
, _sHands :: Map Kaze Hand
, _sWall :: [Tile]
, _sWanpai :: Wanpai
, _sWaiting :: Maybe Waiting -- ^ Waiting turn action or shout(s)
} deriving (Typeable, Show, Read, Generic)
-- | Kyoku viewed from a specific player's point-of-view
data PlayerKyoku = PlayerKyoku Player Kaze Kyoku
deriving (Typeable, Show, Read)
-- | Left for turn, right for shout(s)
type Waiting = Either WaitTurnAction [WaitShout]
-- | @E1 == (Ton, 1, 0)@ etc. last is for renchans.
type Round = (Kaze, Int, Int)
-- | (shouting player, shouting kaze, secs_until_auto, shout)
type WaitShout = (Player, Kaze, Int, [Shout])
-- | When waiting for a turn action: (player, player_kaze, secs_until_auto, tiles_to_riichi_with)
type WaitTurnAction = (Player, Kaze, Int, [Tile])
-- ^ Indices 0-3 are kan supplement tiles. indices 4-8 are dora, 8-12 ura-dora.
data Wanpai = Wanpai
{ _wSupplement :: [Tile]
, _wDora :: [Tile]
, _wUraDora :: [Tile]
, _wBlank :: [Tile]
} deriving (Typeable, Eq, Show, Read)
-- ** Actions and events
data GameEvent = DealStarts PlayerKyoku -- ^ Only at the start of a round
| DealWaitForShout WaitShout -- ^ Number of seconds left to shout or confirm an ignore (See @GameDontCare@)
| DealWaitForTurnAction WaitTurnAction
| DealTurnBegins Kaze
| DealTurnAction Kaze TurnAction
| DealTurnShouted Kaze Shout -- ^ Who, Shout
| DealPublicHandChanged Kaze PlayerHand
| DealPrivateHandChanged Player Kaze Hand -- ^ Wholly private
| DealFlipDora Tile -- ^ New dora was flipped
| DealFlipUraDora [Tile] -- ^ Ura flipped upto resp. dora
| DealNick Kaze Player Text -- Pos, player id, nick TODO: no nick but fetch the player info separetely
| DealRiichi Kaze
| DealEnded KyokuResults
| GamePoints Kaze Int -- ^ Point change
| GameEnded FinalPoints
deriving (Show, Read, Typeable)
-- | Actions you do on your turn.
data TurnAction = TurnTileDiscard Discard
| TurnTileDraw Bool (Maybe Tile) -- ^ wanpai?, tile
| TurnAnkan Tile
| TurnShouminkan Tile
| TurnTsumo
deriving (Show, Read, Typeable)
-- | A @GamAction@ is what clients send to interact in the game.
data GameAction = GameTurn TurnAction -- ^ An action of the player in turn
| GameShout Shout -- ^ Call after a discard
| GameDontCare -- ^ Discard shouts from this player
deriving (Show, Read, Typeable)
-- ** Points, results
type PointsStatus = Map Player Points
-- | Results from a whole game of mahjong.
newtype FinalPoints = FinalPoints PointsStatus deriving (Show, Read, Eq, Generic)
data KyokuResults = DealTsumo { dWinners :: [Winner], dPayers :: [Payer] }
| DealRon { dWinners :: [Winner], dPayers :: [Payer] }
| DealDraw { dTenpais :: [Tenpai], dNooten :: [Payer] }
| DealAbort { dReason :: AbortiveDraw }
deriving (Eq, Show, Read, Typeable)
data AbortiveDraw = KuushuuKyuuhai -- ^ Nine unrelated tiles in initial hand
| SuufonRenda -- ^ All four winds
| SuuchaRiichi -- ^ All players riichi
| SuuKaikan -- ^ Fourth kon declared (or fifth if one player declared all four)
| Sanchahou -- ^ Three players ron
deriving (Eq, Show, Read, Typeable)
type Winner = (Kaze, Points, ValuedHand)
type Tenpai = (Kaze, Points, [Mentsu], [Tile])
type Payer = (Kaze, Points)
-- ** Hand value
-- | A hand that won.
data ValuedHand = ValuedHand
{ _vhMentsu :: [Mentsu]
, _vhTiles :: [Tile] -- ^ Concealed tiles
, _vhValue :: Value
} deriving (Eq, Show, Read)
type Fu = Int
type Han = Int
type Points = Int
-- | Hand value
data Value = Value
{ _vaYaku :: [Yaku]
, _vaFu :: Fu
, _vaHan :: Han
, _vaValue :: Points -- ^ Basic points (non-dealer and not rounded)
, _vaNamed :: Maybe Text
} deriving (Eq, Show, Read)
data Yaku = Yaku
{ _yHan :: Int
, _yName :: Text
} | YakuExtra
{ _yHan :: Int
, _yName :: Text
} deriving (Eq, Ord, Show, Read)
-- | Required info to calculate the value from a hand.
data ValueInfo = ValueInfo
{ _vKyoku :: Kyoku
, _vPlayer :: Kaze
, _vHand :: Hand
} deriving (Show, Read)
instance HasGroupings ValueInfo where getGroupings = getGroupings . _vHand
-- * Construct state
fourPlayers :: [Player]
fourPlayers = Player <$> [0 .. 3]
-- | A new round with given player names.
newKyoku :: [Player] -- ^ Players, from Ton to Shaa
-> [Text] -- ^ Names
-> IO Kyoku
newKyoku players names = do
oja <- (players L.!!) <$> randomRIO (0, 3)
tiles <- shuffleTiles
return $ dealTiles tiles $ Kyoku
{ _pDora = []
, _pFirstOja = oja
, _pHonba = 0
, _pRiichi = 0
, _pOja = oja
, _pPlayers = mapFromList $ zip [Ton .. Pei] (zip3 players (repeat 25000) names)
, _pResults = Nothing
, _pRound = (Ton, 1, 0)
, _pTurn = Ton
, _pFlags = setFromList [FirstRoundUninterrupted]
, _pWallTilesLeft = 0
, _sEventHistory = mempty
, _sHands = mempty
, _sWall = mempty
, _sWanpai = Wanpai mempty mempty mempty mempty
, _sWaiting = Nothing
}
dealTiles :: [Tile] -> Kyoku -> Kyoku
dealTiles tiles deal = deal
{ _pWallTilesLeft = length wall
, _pDora = [doraX]
, _sEventHistory = []
, _sHands = Map.fromList $ zip [Ton .. Pei] (initHand <$> [h1, h2, h3, h4])
, _sWall = wall
, _sWanpai = Wanpai supplement doraXS uradora rest
} where
(hands, xs) = splitAt (13 * 4) tiles
((h1, h2), (h3, h4)) = splitAt 13 *** splitAt 13 $ splitAt (13*2) hands
(wanpai, wall) = splitAt 14 xs
((supplement, doraX:doraXS), (uradora, rest))
= splitAt 4 *** splitAt 5 $ splitAt 9 wanpai
shuffleTiles :: IO [Tile]
shuffleTiles = shuffleM riichiTiles
-- * Lenses
--
makeLenses ''Kyoku
makeLenses ''Wanpai
makeLenses ''ValueInfo
makeLenses ''ValuedHand
makeLenses ''Value
makeLenses ''Yaku
-- * Utility
kyokuTiles :: Kyoku -> [Tile]
kyokuTiles kyoku = kyoku^.pDora ++ kyoku^.sWall ++ kyoku^..sHands.each.handConcealed.each ++ kyoku^.sWanpai.to wanpaiTiles
-- | Get all tiles currently in the wanpai in no particular order.
wanpaiTiles :: Wanpai -> [Tile]
wanpaiTiles Wanpai{..} = _wSupplement ++ _wDora ++ _wUraDora ++ _wBlank
-- Instances
instance P.Pretty Kyoku where
pretty Kyoku{..} =
P.string "wall:" P.<+> P.hang 0 (prettyList' _sWall) P.<$$>
P.string "unrevealed dora:" P.<+> P.hang 0 (prettyList' $ _wDora _sWanpai) P.<$$>
P.string "hands:" P.<+> P.hang 0 (P.list $ toList $ fmap P.pretty _sHands)
$(deriveSafeCopy 0 'base ''GameEvent)
$(deriveSafeCopy 0 'base ''Kyoku)
$(deriveSafeCopy 0 'base ''PlayerKyoku)
$(deriveSafeCopy 0 'base ''TurnAction)
$(deriveSafeCopy 0 'base ''Wanpai)
$(deriveSafeCopy 0 'base ''KyokuResults)
$(deriveSafeCopy 0 'base ''FinalPoints)
$(deriveSafeCopy 0 'base ''ValuedHand)
$(deriveSafeCopy 0 'base ''Value)
$(deriveSafeCopy 0 'base ''Yaku)
$(deriveSafeCopy 0 'base ''AbortiveDraw)
| SimSaladin/hajong | hajong-server/src/Mahjong/Kyoku/Internal.hs | mit | 9,826 | 0 | 15 | 2,897 | 2,140 | 1,244 | 896 | -1 | -1 |
{- |
Module : Language.Scheme.Plugins.CPUTime
Copyright : Justin Ethier
Licence : MIT (see LICENSE in the distribution)
Maintainer : github.com/justinethier
Stability : experimental
Portability : portable
This module wraps System.CPUTime so that it can be used directly by Scheme code.
More importantly, it serves as an example of how to wrap existing Haskell code so
that it can be loaded and called by husk.
See 'examples/ffi/ffi-cputime.scm' in the husk source tree for an example of how to
call into this module from Scheme code.
-}
module Language.Scheme.Plugins.CPUTime (get, precision) where
import Language.Scheme.Types
import System.CPUTime
import Control.Monad.Except
-- |Wrapper for CPUTime.getCPUTime
get :: [LispVal] -> IOThrowsError LispVal
get [] = do
t <- liftIO $ System.CPUTime.getCPUTime
return $ Number t
get badArgList = throwError $ NumArgs (Just 0) badArgList
-- |Wrapper for CPUTime.cpuTimePrecision
precision :: [LispVal] -> IOThrowsError LispVal
precision [] = return $ Number $ System.CPUTime.cpuTimePrecision
precision badArgList = throwError $ NumArgs (Just 0) badArgList
| justinethier/husk-scheme | hs-src/Language/Scheme/Plugins/CPUTime.hs | mit | 1,127 | 0 | 9 | 181 | 167 | 90 | 77 | 12 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Data.Hash.SL2.Reducer where
import Data.ByteString (ByteString)
import Data.Hash.SL2
import Data.Semigroup
import Data.Semigroup.Reducer
instance Semigroup Hash where
(<>) = mappend
instance Reducer ByteString Hash where
unit = mempty
snoc = append
cons = prepend
| srijs/hwsl2-reducers | src/Data/Hash/SL2/Reducer.hs | mit | 322 | 0 | 5 | 49 | 76 | 47 | 29 | 12 | 0 |
{-|
Module: Flaw.UI.Menu
Description: Menu.
License: MIT
-}
module Flaw.UI.Menu
( Menu(..)
, MenuItem(..)
, newPopupMenu
) where
import Control.Concurrent.STM
import Control.Monad
import qualified Data.Text as T
import Flaw.Math
import Flaw.UI
import Flaw.UI.Button
import Flaw.UI.Metrics
import Flaw.UI.Popup
newtype Menu = Menu [MenuItem]
data MenuItem
= MenuItemCommand !T.Text !(STM ())
-- MenuItemSubMenu !T.Text !Menu
newPopupMenu :: PopupService -> Position -> Menu -> STM ()
newPopupMenu popupService@PopupService
{ popupServiceMetrics = Metrics
{ metricsButtonSize = buttonSize@(Vec2 buttonWidth buttonHeight)
}
} (Vec2 px py) (Menu items) = do
Popup
{ popupPanel = panel
, popupClose = close
} <- newPopup popupService (Vec4 px py (px + buttonWidth) (py + buttonHeight * length items))
forM_ (zip [0..] items) $ \(i, MenuItemCommand text handler) -> do
button <- newLabeledButton text
buttonChild <- addFreeChild panel button
layoutElement button buttonSize
placeFreeChild panel buttonChild $ Vec2 0 (i * buttonHeight)
setActionHandler button $ do
close
handler
| quyse/flaw | flaw-ui/Flaw/UI/Menu.hs | mit | 1,150 | 0 | 15 | 225 | 356 | 190 | 166 | 36 | 1 |
module PolyTest where
undefined : a
undefined = _|_
id x = x
const a b = a
flip f a b = f b a
compose f g x = f (g x)
apply f x = f x
save x f = f x
coerse : a -> b
coerse = undefined
unifiable : a -> a -> a
unifiable = const
polyLet = let id = \ x. x in
id id id id id id (id id) id ((id id) id) id id id id id
end
assert1 = unifiable 1 2
assert2 = unifiable id polyLet
assert3 = unifiable coerse id
main = 0 | pxqr/algorithm-wm | test/poly.hs | mit | 438 | 11 | 10 | 137 | 229 | 115 | 114 | -1 | -1 |
module Types
( ServerDirective(..)
, ClientDirective(..)
, Command(..)
, CommandExtra(..)
, emptyCommandExtra
) where
import System.Exit (ExitCode)
data CommandExtra = CommandExtra
{ ceGhcOptions :: [String]
, ceCabalConfig :: Maybe FilePath
, cePath :: Maybe FilePath
, ceCabalOptions :: [String]
} deriving (Read, Show)
emptyCommandExtra :: CommandExtra
emptyCommandExtra = CommandExtra { ceGhcOptions = []
, ceCabalConfig = Nothing
, cePath = Nothing
, ceCabalOptions = []
}
data ServerDirective
= SrvCommand Command CommandExtra
| SrvStatus
| SrvExit
deriving (Read, Show)
data ClientDirective
= ClientStdout String
| ClientStderr String
| ClientExit ExitCode
| ClientUnexpectedError String -- ^ For unexpected errors that should not happen
deriving (Read, Show)
data Command
= CmdCheck FilePath
| CmdModuleFile String
| CmdInfo FilePath String
| CmdType FilePath (Int, Int)
| CmdFindSymbol String [String]
deriving (Read, Show)
| schell/hdevtools | src/Types.hs | mit | 1,181 | 0 | 9 | 377 | 262 | 159 | 103 | 36 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
-- |
--
-- Module : TestData.TiloBalkeExample
-- Description : An example from Tilo Balke's presentation.
-- Copyright : Wolf-Tilo Balke, Silviu Homoceanu. Institut für Informationssysteme
-- Technische Universität Braunschweig <http://www.ifis.cs.tu-bs.de>
-- License : AllRightsReserved
-- Stability : dev
--
-- An example from Tilo Balke's presentation.
module TestData.TiloBalkeExample (
Entry(..)
, Age(..)
, Income(..)
, Student(..)
, CreditRating(..)
, BuysComputer(..)
, testData
, expectedDecision
, classname
--, splitAge
) where
import DecisionTrees
import DecisionTrees.Definitions hiding (Entry)
import qualified DecisionTrees.Definitions as D
import qualified Data.Map as Map
import qualified Data.Set as Set
import Control.Applicative
import Data.Typeable
data Age = Age Int | AgeRange (Maybe Int) (Maybe Int) deriving Typeable
newtype Income = Income String deriving (Show, Eq, Ord, Typeable)
newtype Student = Student Bool deriving (Show, Eq, Ord, Typeable)
data CreditRating = Fair | Excellent deriving (Show, Eq, Ord, Typeable)
data BuysComputer = Yes | No deriving (Show, Eq, Ord, Typeable)
instance Show Age where
show (Age n) = show n ++ "years"
show (AgeRange mbFrom mbTo) = "[" ++ strFrom ++ ".." ++ strTo ++ "]"
where strFrom = maybe "" show mbFrom
strTo = maybe "" show mbTo
instance Eq Age where
(Age x) == (Age y) = x == y
(AgeRange from to) == (Age x) = (&&) <$> mb (<=) from <*> mb (>=) to $ x
where mb = maybe (const True)
a@(Age x) == r@(AgeRange from to) = r == a
(AgeRange xf xt) == (AgeRange yf yt) = xf == yf && xt == yt
instance Ord Age where
(Age x) `compare` (Age y) = x `compare` y
r@(AgeRange from to) `compare` a@(Age x) | a == r = EQ
| maybe (const False) (<) to x = LT
| otherwise = GT
a@(Age _) `compare` r@(AgeRange _ _) = case r `compare` a of LT -> GT
GT -> LT
EQ -> EQ
(AgeRange xf xt) `compare` (AgeRange yf yt) | xf == yf && xt == yt = EQ
| maybe True (maybe (const False) (<) xt) yt = LT
| maybe True (maybe (const False) (>) xf) yf = GT
data Entry = Entry{ age :: Age
, income :: Income
, student :: Student
, credRating :: CreditRating
, buysComp :: BuysComputer
}
deriving (Show, Eq)
instance Attribute Age where
possibleDiscreteDomains _ = [
[ [AgeRange Nothing (Just 30)], [AgeRange (Just 31) (Just 40)],[ AgeRange (Just 41) Nothing] ]
]
attributeName _ = AttrName "age"
instance Attribute Income where
possibleDiscreteDomains _ = [ [ [Income "high"], [Income "medium"], [Income "low"] ] ]
attributeName _ = AttrName "income"
instance Attribute Student where
possibleDiscreteDomains _ = [ [ [Student True], [Student False] ] ]
attributeName _ = AttrName "student"
instance Attribute CreditRating where
possibleDiscreteDomains _ = [ [ [Fair], [Excellent] ] ]
attributeName _ = AttrName "credit rating"
instance Attribute BuysComputer where
possibleDiscreteDomains _ = [ [ [Yes], [No] ] ]
attributeName _ = AttrName classname
instance D.Entry Entry where
-- entry -> [AttributeContainer]
listAttributes entry = map ($ entry) [
Attr . age
, Attr . income
, Attr . student
, Attr . credRating
]
getClass = Attr . buysComp
classDomain _ = Set.fromList [Attr Yes, Attr No]
attrByName (AttrName name) =
case name of "age" -> Attr . age
"income" -> Attr . income
"student" -> Attr . student
"credit rating" -> Attr . credRating
hasAttribute _ _ = True
newEntry age income student = Entry (Age age) (Income income) (Student student)
classname = "buys computer"
testData :: [Entry]
testData = [
newEntry 25 "high" False Fair No
, newEntry 27 "high" False Excellent No
, newEntry 35 "high" False Fair Yes
, newEntry 42 "medium" False Excellent Yes
, newEntry 52 "low" True Excellent Yes
, newEntry 45 "low" True Fair No
, newEntry 31 "low" True Excellent Yes
, newEntry 29 "medium" False Fair No
, newEntry 22 "low" True Fair Yes
, newEntry 42 "medium" True Excellent Yes
, newEntry 30 "medium" True Excellent Yes
, newEntry 36 "medium" False Excellent Yes
, newEntry 33 "high" True Fair Yes
, newEntry 50 "medium" False Fair No
]
splitAge (Age age) | age <= 30 = AgeRange Nothing (Just 30)
| age > 40 = AgeRange Nothing (Just 30)
| otherwise = AgeRange (Just 31) (Just 40)
tTrue = Attr Yes
tFalse = Attr No
expectedDecision :: Decision Entry AttributeContainer
expectedDecision =
DecisionStep { prepare = splitAge . age
, describePrepare = "age"
, select = Map.fromList [ ([AgeRange Nothing (Just 30)], treeAgeYoung)
, ([AgeRange (Just 31) (Just 40)], treeAgeMiddle)
, ([AgeRange (Just 41) Nothing ], treeAgeSenior)
]
, describeSelect = Nothing
}
treeAgeYoung = DecisionStep { prepare = student
, describePrepare = "student?"
, select = Map.fromList [ ([Student True], treeYoungStudent)
, ([Student False], treeYoungNotStudent)
]
, describeSelect = Just "young age"
}
treeYoungStudent = Decision { classification = Map.fromList [(tTrue , 2)] , describeSelect = Just "student" }
treeYoungNotStudent = Decision { classification = Map.fromList [(tFalse, 3)] , describeSelect = Just "not student" }
treeAgeMiddle = Decision { classification = Map.fromList [(tTrue, 4)]
, describeSelect = Just "middle age"
}
treeAgeSenior = DecisionStep { prepare = credRating
, describePrepare = "credit rating"
, select = Map.fromList [ ([Fair], treeSeniorFair)
, ([Excellent], treeSeniorExcellent)
]
, describeSelect = Just "senior age"
}
treeSeniorFair = Decision (Map.fromList [(tFalse, 2)]) (Just "Fair")
treeSeniorExcellent = Decision (Map.fromList [(tTrue, 3)]) (Just "Excellent")
| fehu/min-dat--decision-trees | test/TestData/TiloBalkeExample.hs | mit | 7,198 | 0 | 13 | 2,641 | 2,087 | 1,131 | 956 | 128 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Main where
{-
WARNING: This Example was actually more used as a POC for the
library to be added to some iseek code.
As such, the example is weird and certainly could be better
organised / more concise, but it certainly is an exhaustive example
of the use cases that I'm writing the library for...
-}
import BasePrelude hiding (first, try, (&), (<>))
import Control.Lens
import Control.Monad.Error.Hoist ((<!?>), (<?>))
import Control.Monad.Except (ExceptT (..), MonadError,
runExceptT)
import Control.Monad.Reader (MonadReader, ReaderT, runReaderT)
import Control.Monad.TM ((.>>=.))
import Control.Monad.Trans (liftIO)
import Control.Monad.Trans (MonadIO)
import Data.Bifunctor (first)
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NEL
import Data.Semigroup ((<>))
import Data.Text (Text, pack)
import qualified Data.Text as T
import Data.Text.Lens
import LDAP.Classy (AsLdapError (..), Dn (..),
GidNumber (..), HasLdapEnv (..),
LDAPMod (..), LDAPModOp (..),
LDAPScope (..), LdapConfig (..),
LdapCredentials (..), LdapEnv,
LdapError, SearchAttributes (..),
Uid (..), UidNumber (..),
checkPassword, cn, dc, deleteEntry,
dnFromEntry, dnFromText, dnText,
findByDn, insertEntry, modify,
modifyEntry, ou, resetPassword,
runLdap, search, searchFirst,
setPassword)
import LDAP.Classy.Decode (AsLdapEntryDecodeError (..),
FromLdapEntry (..),
ToLdapEntry (..), attrList, attrMay,
attrSingle)
import LDAP.Classy.Search (LdapSearch, isPosixAccount,
isPosixGroup, (&&.), (*~*=.), (==.),
(||.))
import Options.Applicative hiding ((<>))
import qualified Options.Applicative as O
data ExampleLdapError
= ExampleLdapErrorError LdapError
| NoMaxUid
| NoMaxGid
| UserNotFound Dn
| MissingGid GidNumber
deriving Show
makeClassyPrisms ''ExampleLdapError
instance AsLdapError ExampleLdapError where
_LdapError = _ExampleLdapErrorError . _LdapError
instance AsLdapEntryDecodeError ExampleLdapError where
_LdapEntryDecodeError = _ExampleLdapErrorError . _LdapError . _LdapEntryDecodeError
type CanExampleLdap m c e
= ( MonadError e m
, MonadReader c m
, MonadIO m
, AsLdapError e
, AsLdapEntryDecodeError e
, HasLdapEnv c
)
newtype AccountCrmId = AccountCrmId Text deriving (Show)
makeWrapped ''AccountCrmId
newtype CustomerNumber = CustomerNumber Text deriving (Show)
makeWrapped ''CustomerNumber
newtype MemberUids = MemberUids [Uid] deriving Show
makeWrapped ''MemberUids
newtype NextUidNumber = NextUidNumber UidNumber deriving (Show,Num)
makeWrapped ''NextUidNumber
newtype NextGidNumber = NextGidNumber GidNumber deriving (Show,Num)
makeWrapped ''NextGidNumber
data Account' a = Account
{ _accountGid :: a
, _accountDn :: Dn
, _accountName :: Text
, _accountAlias :: Text
, _accountCustomerNumber :: CustomerNumber
, _accountCrmId :: AccountCrmId
, _accountMemberUids :: [Uid]
, _accountUniqueMembers :: [Dn]
} deriving Show
makeLenses ''Account'
type Account = Account' GidNumber
type NewAccount = Account' ()
data AccountSearchTerm
= AccountSearchName Text
| AccountSearchCustomerNumber CustomerNumber
| AccountSearchCrmId AccountCrmId
| AccountSearchUsername Uid
makeClassyPrisms ''AccountSearchTerm
data User' a = User
{ _userUid :: Uid
, _userDn :: Dn
, _userGidNumber :: GidNumber
, _userUidNumber :: a
, _userFirstName :: Text
, _userLastName :: Text
, _userDisplayName :: Text
, _userEmail :: Text
, _userMobile :: Maybe Text
} deriving Show
makeLenses ''User'
type NewUser = User' ()
type User = User' UidNumber
data UserSearchTerm
= UserSearchFirstName Text
| UserSearchLastName Text
| UserSearchEmail Text
| UserSearchUsername Uid
makeClassyPrisms ''UserSearchTerm
accountAttrs :: SearchAttributes
accountAttrs = LDAPAttrList
[ "gidNumber"
, "cn"
, "iseekAlias"
, "memberUid"
, "dn"
, "uniqueMember"
, "iseekCustomerNumber"
, "iseekSalesforceID"
]
userAttrs :: SearchAttributes
userAttrs = LDAPAttrList
[ "uid"
, "gidNumber"
, "uidNumber"
, "givenName"
, "sn"
, "displayName"
, "mail"
, "mobile"
, "cn"
]
iseekDn :: Dn
iseekDn = Dn $ dc "iseek" :| [dc "com", dc "au"]
getUserByGidNumber :: (CanExampleLdap m c e, Applicative m , Functor m) => GidNumber -> m (Maybe User)
getUserByGidNumber gidNum = searchFirst
(isPosixGroup &&. "gidNumber" ==. (gidNum^._Wrapped.to show))
accountAttrs
getNextGidNumber :: (CanExampleLdap m c e, Applicative m , Functor m,AsExampleLdapError e) => m NextGidNumber
getNextGidNumber = do
mGidMay <- getMaxGidNumber
mGid <- mGidMay <?> (_NoMaxGid # ())
nGid <- nextFreeGid (mGid + 1)
let dn = Dn (cn "MaxGroupGid" :| [ou "groups"]) <> iseekDn
modify dn [LDAPMod LdapModReplace "gidNumber" [nGid^._Wrapped._Wrapped.to show]]
pure nGid
where
nextFreeGid mGid = do
uMay <- getUserByGidNumber (mGid^._Wrapped)
maybe (pure mGid) (const (nextFreeGid (mGid+1))) uMay
getMaxGidNumber :: (CanExampleLdap m c e, Applicative m, Functor m) => m (Maybe NextGidNumber)
getMaxGidNumber = searchFirst
("objectClass" ==. "iseekGidNext" &&. "cn" ==. "MaxGroupGid")
(LDAPAttrList ["gidNumber"])
insertAccount :: (CanExampleLdap m c e, Applicative m, Functor m, AsExampleLdapError e) => NewAccount -> m ()
insertAccount na = do
gid <- view _Wrapped <$> getNextGidNumber
let acct = na & accountGid .~ gid
insertEntry acct
searchAccounts :: (CanExampleLdap m c e, Applicative m , Functor m) => NonEmpty AccountSearchTerm -> m [Account]
searchAccounts sts = search (foldSearchTerms f sts) accountAttrs
where
f (AccountSearchName n) = ("iseekAlias" *~*=. n^.from packed ||. "cn" ==. n^.from packed)
f (AccountSearchCustomerNumber n) = "iseekCustomerNumber" *~*=. n^._Wrapped.to show
f (AccountSearchCrmId i) = "iseekSalesforceID" *~*=. i^._Wrapped.from packed
f (AccountSearchUsername u) = "memberUid" *~*=. u^._Wrapped.from packed
updateAccount :: (CanExampleLdap m c e, Applicative m, Functor m) => Account -> m ()
updateAccount = modifyEntry
listUidsForAccount :: (CanExampleLdap m c e, Applicative m) => AccountCrmId -> m MemberUids
listUidsForAccount a = do
res <- searchFirst (isPosixGroup &&. "iseekSalesforceID" ==. (a^._Wrapped.from packed)) (LDAPAttrList ["memberUid"])
pure . fromMaybe (MemberUids []) $ res
addUserToAccount :: (CanExampleLdap m c e, Applicative m) => User -> Account-> m ()
addUserToAccount u a = updateAccount $ a
& accountUniqueMembers %~ (++ [u^.userDn])
& accountMemberUids %~ (++ [u^.userUid])
addUserToGid :: (CanExampleLdap m c e, Applicative m,AsExampleLdapError e) => User -> GidNumber -> m ()
addUserToGid u gid = do
a <- getAccountByGid gid <!?> (_MissingGid # gid)
addUserToAccount u a
removeUserFromAccount :: (CanExampleLdap m c e, Applicative m) => User -> Account -> m ()
removeUserFromAccount u a = updateAccount $ a
& accountUniqueMembers %~ filter (/= u^.userDn)
& accountMemberUids %~ filter (/= u^.userUid)
accountsOfUser :: (CanExampleLdap m c e, Applicative m) => User -> m [Account]
accountsOfUser u = search
( "memberUid" ==. u^.userUid._Wrapped.from packed
||. "uniqueMember" ==. u^.userDn.dnText.from packed
)
accountAttrs
getAccountByGid
:: (CanExampleLdap m c e,Applicative m)
=> GidNumber
-> m (Maybe Account)
getAccountByGid gidNumber = searchFirst
(isPosixGroup &&. "gidNumber" ==. (gidNumber^._Wrapped.to show))
accountAttrs
getUser :: (CanExampleLdap m c e, Applicative m , Functor m) => Uid -> m (Maybe User)
getUser uid = searchFirst
(isPosixAccount &&. "uid" ==. (uid^._Wrapped.from packed))
userAttrs
searchUsers :: (CanExampleLdap m c e, Applicative m , Functor m) => NonEmpty UserSearchTerm -> m [User]
searchUsers sts = search (foldSearchTerms searchTerm sts) userAttrs
where
searchTerm (UserSearchUsername uid) = "uid" *~*=. uid^._Wrapped.from packed
searchTerm (UserSearchFirstName fn) = "givenName" *~*=. fn^.from packed
searchTerm (UserSearchLastName sn) = "sn" *~*=. sn^.from packed
searchTerm (UserSearchEmail e) = "mail" *~*=. e^.from packed
foldSearchTerms :: (a -> LdapSearch) -> NonEmpty a -> LdapSearch
foldSearchTerms f as = foldl (&&.) (NEL.head exprs) (NEL.tail exprs)
where
exprs = fmap f as
updateUser :: (CanExampleLdap m c e, Applicative m, Functor m,AsExampleLdapError e) => User -> m ()
updateUser u = do
(oldU :: Maybe User) <- findByDn (u^.userDn) userAttrs
aMay <- oldU .>>=. (getAccountByGid . (^.userGidNumber))
modifyEntry u
case aMay of
Just a | a^.accountGid /= u^.userGidNumber -> do
removeUserFromAccount u a
addUserToGid u (u^.userGidNumber)
Nothing -> addUserToGid u (u^.userGidNumber)
_ -> pure ()
insertUser :: (CanExampleLdap m c e, Applicative m, Functor m, AsExampleLdapError e) => NewUser -> m Text
insertUser nu = do
let gid = nu^.userGidNumber
account <- getAccountByGid gid <!?> (_MissingGid # gid)
uidNumber <- view _Wrapped <$> getNextUidNumber
let user = nu & userUidNumber .~ uidNumber
insertEntry user
addUserToAccount user account
resetPassword $ nu^.userDn
deleteUser :: (CanExampleLdap m c e, Applicative m, Functor m, AsExampleLdapError e) => User -> m ()
deleteUser u = do
deleteEntry u
accountsOfUser u >>= traverse_ (removeUserFromAccount u)
getUserByUidNumber :: (CanExampleLdap m c e, Applicative m , Functor m) => UidNumber -> m (Maybe User)
getUserByUidNumber uidNum = searchFirst
(isPosixAccount &&. "uidNumber" ==. (uidNum^._Wrapped.to show))
userAttrs
getNextUidNumber :: (CanExampleLdap m c e, Applicative m , Functor m,AsExampleLdapError e) => m NextUidNumber
getNextUidNumber = do
mUidMay <- getMaxUidNumber
mUid <- mUidMay <?> (_NoMaxUid # ())
nUid <- nextFreeUid (mUid + 1)
let dn = Dn (cn "MaxCustomerUid" :| [ou "users"]) <> iseekDn
modify dn [LDAPMod LdapModReplace "uidNumber" [nUid^._Wrapped._Wrapped.to show]]
pure nUid
where
nextFreeUid mUid = do
uMay <- getUserByUidNumber (mUid^._Wrapped)
maybe (pure mUid) (const (nextFreeUid (mUid+1))) uMay
getMaxUidNumber :: (CanExampleLdap m c e, Applicative m, Functor m) => m (Maybe NextUidNumber)
getMaxUidNumber = searchFirst
("objectClass" ==. "iseekUidNext" &&. "cn" ==. "MaxCustomerUid")
(LDAPAttrList ["uidNumber"])
instance FromLdapEntry Account where
fromLdapEntry e = Account
<$> (attrSingle "gidNumber" e <&> GidNumber)
<*> pure (dnFromEntry e)
<*> attrSingle "cn" e
<*> attrSingle "iseekAlias" e
<*> (attrSingle "iseekCustomerNumber" e <&> CustomerNumber)
<*> (attrSingle "iseekSalesforceID" e <&> AccountCrmId)
<*> (attrList "memberUid" e <&> fmap Uid)
<*> (attrList "uniqueMember" e)
instance ToLdapEntry Account where
toLdapDn = view accountDn
toLdapAttrs a =
[ ("cn" ,[a^.accountName.from packed])
, ("gidNumber" ,[a^.accountGid._Wrapped.to show])
, ("iseekAlias" ,[a^.accountName.from packed])
, ("iseekCustomerNumber" ,[a^.accountCustomerNumber._Wrapped.to show])
, ("iseekSalesforceId" ,[a^.accountCustomerNumber._Wrapped.from packed])
, ("memberUid" , a^..accountMemberUids.traverse._Wrapped.from packed)
, ("uniqueMember" , a^..accountUniqueMembers.traverse.dnText.from packed)
]
instance FromLdapEntry User where
fromLdapEntry e = User
<$> (attrSingle "uid" e <&> Uid)
<*> pure (dnFromEntry e)
<*> (attrSingle "gidNumber" e <&> GidNumber)
<*> (attrSingle "uidNumber" e <&> UidNumber)
<*> attrSingle "givenName" e
<*> attrSingle "sn" e
<*> attrSingle "displayName" e
<*> attrSingle "mail" e
<*> attrMay "mobile" e
instance ToLdapEntry User where
toLdapDn = view userDn
toLdapAttrs u =
[ ("gidNumber" , [u^.userGidNumber._Wrapped.to show])
, ("uidNumber" , [u^.userUidNumber._Wrapped.to show])
, ("givenName" , [u^.userFirstName.from packed])
, ("sn" , [u^.userLastName.from packed])
, ("displayName" , [u^.userDisplayName.from packed])
, ("cn" , [u^.userDisplayName.from packed])
, ("mail" , [u^.userEmail.from packed])
, ("mobile" , toList $ u^?userMobile._Just.from packed)
, ("objectClass" , ["posixAccount","inetOrgPerson","top"])
, ("homeDirectory" , ["/dev/null"])
]
instance FromLdapEntry MemberUids where
fromLdapEntry e = MemberUids <$> attrList "memberUid" e
instance FromLdapEntry NextUidNumber where
fromLdapEntry e = NextUidNumber <$> attrSingle "uidNumber" e
instance FromLdapEntry NextGidNumber where
fromLdapEntry e = NextGidNumber <$> attrSingle "gidNumber" e
main :: IO ()
main = printErr $ do
LdapOpts h p d s uMay pMay <- liftIO $ execParser opts
let conf = LdapConfig h p d s (LdapCredentials <$> uMay <*> pMay)
let gid = GidNumber 11121
let dn = Dn (("uid","bkolera2") :| [ou "customers",ou "users"]) <> iseekDn
let newU = User (Uid "bkolera2") dn gid () "Ben" "Kolera" "Ben Kolera" "ben.kolera@email.com" (Just "0400123456")
runLdap' conf $ do
getAccountByGid gid >>= liftIO . print
pw <- insertUser newU
getAccountByGid gid >>= liftIO . print
checkPassword dn pw
setPassword dn "hunter2"
checkPassword dn "hunter2"
Just u <- getUser (Uid "bkolera2")
liftIO $ print u
void $ updateUser (u & userMobile .~ (Just "0499333555"))
uMayAfter <- getUser (Uid "bkolera2")
liftIO $ print (uMayAfter :: Maybe User)
void $ updateUser (u & userGidNumber .~ (GidNumber 11124))
getAccountByGid gid >>= liftIO . print
getAccountByGid (GidNumber 11124) >>= liftIO . print
deleteUser u
uMayGone <- getUser (Uid "bkolera2")
liftIO $ print (uMayGone :: Maybe User)
where
runLdap' :: LdapConfig -> ExceptT ExampleLdapError (ReaderT LdapEnv IO) a -> ExceptT String IO a
runLdap' conf =
ExceptT
. fmap (first show)
. flip runReaderT conf
. runExceptT
. runLdap
printErr :: ExceptT String IO () -> IO ()
printErr et = runExceptT et >>= either print (const . pure $ ())
data LdapOpts = LdapOpts Text Int (Maybe Dn) LDAPScope (Maybe Dn) (Maybe Text) deriving Show
opts :: ParserInfo LdapOpts
opts = info (helper <*> ldapOpts) ( fullDesc O.<> progDesc "Sample LDAP Class App")
ldapOpts :: Parser LdapOpts
ldapOpts = LdapOpts
<$> textOption
( long "host"
O.<> metavar "HOSTNAME"
O.<> help "LDAP server hostname to connect to"
O.<> value "localhost"
O.<> showDefault
)
<*> option auto
( long "port"
O.<> metavar "PORT"
O.<> value 3389
O.<> help "Port on the LDAP server to connect to"
)
<*> option dnReader
( long "baseDn"
O.<> metavar "DN"
O.<> value (Just . Dn $ dc "iseek" :| [dc "com",dc "au"])
O.<> help "Base DN to search from"
)
<*> option (eitherReader scopeFromString)
( long "scope"
O.<> metavar "SEARCH_SCOPE"
O.<> value LdapScopeSubtree
O.<> help "Either Default,Base,OneLevel or Subtree"
O.<> showDefaultWith showScope )
<*> option dnReader
( long "rootDn"
O.<> metavar "DN"
O.<> value Nothing
O.<> help "Optional root DN to bind with"
O.<> showDefault
)
<*> textOptionMay
( long "password"
O.<> metavar "PASSWORD"
O.<> help "Password to bind with"
O.<> value Nothing
O.<> showDefault
)
textOption :: Mod OptionFields Text -> Parser Text
textOption = option (pack <$> str)
textOptionMay :: Mod OptionFields (Maybe Text) -> Parser (Maybe Text)
textOptionMay = option textOptionMayReader
textOptionMayReader :: ReadM (Maybe Text)
textOptionMayReader = eitherReader (pure . mfilter (not . T.null) . Just . pack)
scopeFromString :: String -> Either String LDAPScope
scopeFromString "Default" = Right LdapScopeDefault
scopeFromString "Base" = Right LdapScopeBase
scopeFromString "OneLevel" = Right LdapScopeOnelevel
scopeFromString "Subtree" = Right LdapScopeSubtree
scopeFromString s = Left $ "Invalid Scope: " <> s
showScope :: LDAPScope -> String
showScope LdapScopeDefault = "Default"
showScope LdapScopeBase = "Base"
showScope LdapScopeOnelevel = "OneLevel"
showScope LdapScopeSubtree = "SubTree"
showScope (UnknownLDAPScope l) = "Level_" <> show l
dnReader :: ReadM (Maybe Dn)
dnReader = textOptionMayReader <&> (>>= dnFromText)
| benkolera/haskell-ldap-classy | example/Main.hs | mit | 18,071 | 0 | 17 | 4,545 | 5,366 | 2,785 | 2,581 | -1 | -1 |
module P019Spec where
import qualified P019 as P
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec =
describe "solveBasic" $
it "20世紀内の月初の日曜日の数" $
P.solveBasic `shouldBe` 171
| yyotti/euler_haskell | test/P019Spec.hs | mit | 232 | 0 | 8 | 47 | 65 | 37 | 28 | 10 | 1 |
{-# LANGUAGE GADTs, MultiParamTypeClasses #-}
module Residueclass where
data Nat where
Zero :: Nat
Succ :: Nat -> Nat
deriving (Eq)
one :: Nat
one = Succ Zero
instance Num Nat where
Zero + n = n
n + Zero = n
n + (Succ m) = Succ n + m
Zero * _ = Zero
_ * Zero = Zero
n * (Succ m) = n + n * m
abs n = n
signum Zero = Zero
signum _ = one
negate n = n
fromInteger 0 = Zero
fromInteger n = Succ $ fromInteger (n - 1)
class Residueclass a where
limit :: Nat
data Z2
instance Residueclass Z2 where
limit = one
| plneappl/HaskellVectorsETC | Restclass.hs | mit | 577 | 0 | 9 | 190 | 236 | 120 | 116 | -1 | -1 |
import Data.Char
import Data.Foldable (Foldable, foldr)
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import System.Environment
import System.Random
data Sex = Male | Female deriving (Show,Read,Eq,Ord)
data Person = Person {
idNumber :: String,
forename :: String,
surname :: String,
sex :: Sex,
age :: Int,
partner :: Maybe Person,
children :: [Person] } deriving (Show,Read,Eq,Ord)
class Ageing a where
currentAge :: a -> Int
maxAge :: a -> Int
makeOlder :: a -> a
instance Ageing Person where
currentAge = age
makeOlder p = p {age = age p + 1}
maxAge _ = 123
data Breed = Beagle | Husky | Pekingese deriving (Eq,Ord,Show,Read)
data Dog = Dog {
dogName :: String,
dogBreed :: Breed,
dogAge :: Int } deriving (Eq,Ord,Show,Read)
instance Ageing Dog where
currentAge = dogAge
makeOlder d = d {dogAge = dogAge d + 1}
maxAge d = case dogBreed d of
Husky -> 29
_ -> 20
-- 1.1
compareRelativeAge :: (Ageing a, Ageing b) => a -> b -> Ordering
compareRelativeAge x y = compare (fromIntegral (currentAge x) / fromIntegral (maxAge x)) (fromIntegral (currentAge y) / fromIntegral (maxAge y))
-- 1.2
class Nameable a where
name :: a -> String
instance Nameable Dog where
name d = dogName d ++ " the Dog"
instance Nameable Person where
name p = forename p ++ " " ++ surname p
-- 2.1
class Takeable t where
takeSome :: Int -> t a -> [a]
instance Takeable [] where
takeSome = take
-- 2.2
class Headed t where
headOf :: t a -> a
headOff :: t a -> t a
instance Headed [] where
headOf = head
headOff = tail
data Tree a = Null | Node a (Tree a) (Tree a) deriving (Show,Eq)
instance Functor Tree where
fmap _ Null = Null
fmap f (Node x l r) = Node (f x) (fmap f l) (fmap f r)
-- 3.1
mapOnTreeMaybe :: (Functor f) => (a -> b) -> f a -> f b
mapOnTreeMaybe = fmap
-- 4.1
sumPositive :: (Foldable t, Num a, Ord a) => t a -> a
sumPositive t = Data.Foldable.foldr (\x c -> if x > 0 then x + c else c) 0 t
-- 4.2
size :: Foldable t => t a -> Int
size t = Data.Foldable.foldr (\x c -> c+1) 0 t
-- 5.1
toSet :: (Foldable t, Ord a) => t a -> S.Set a
toSet = Data.Foldable.foldr S.insert S.empty
-- 5.2
indexWords :: String -> M.Map String Int
indexWords s = Data.Foldable.foldr (\x c -> M.insertWith (\a b -> a + b) x 1 c) M.empty (words s)
-- 1.1
main :: IO ()
main = do
s1 <- getLine
s2 <- getLine
putStrLn $ reverse $ s1 ++ s2
threeNumbers
-- 1.2
threeNumbers :: IO ()
threeNumbers = do
x <- getLine
y <- getLine
z <- getLine
putStrLn $ show $ (read x :: Int) + (read y :: Int) + (read z :: Int)
-- 2.1
threeStrings :: IO Int
threeStrings = do
s1 <- getLine
s2 <- getLine
s3 <- getLine
putStrLn $ s1 ++ s2 ++ s3
return $ length s1 + length s2 + length s3
-- 2.2
askNumber9 :: IO Int
askNumber9 = do
x <- getLine
if (not (null x)) && (and $ map isNumber x) then
return (read x :: Int)
else askNumber9
-- 2.3
askUser :: String -> (String -> Bool) -> IO String
askUser m p = do
putStrLn m
x <- askUser'' p :: IO String
return x
askUser'' :: Read a => (String -> Bool) -> IO a
askUser'' p = do
x <- getLine
if p x then
return $ read x
else askUser'' p
askUser' :: (Read a) => String -> (String -> Bool) -> IO a
askUser' m p = do
putStrLn m
x <- askUser'' p
return x
-- 2.4
inputStrings :: IO [String]
inputStrings = do
s <- liness []
return s
liness :: [String] -> IO [String]
liness ss = do
s <- getLine
if null s then return $ reverse ss
else liness $ s : ss
-- 3.1
fun1 = do
n' <- getLine
let n = read n' :: Int
ss <- linesss n []
return $ reverse ss
linesss :: Int -> [String] -> IO [String]
linesss n ss = if n == 0 then return ss else do
s <- getLine
linesss (n-1) (s : ss)
-- 3.2
sequence' :: Monad m => [m a] -> m [a]
sequence' [] = return []
sequence' ss = seqs ss []
seqs [] xs = return $ reverse xs
seqs (s:ss) xs = do
x <- s
seqs ss (x:xs)
-- 3.3
mapM' :: Monad m => (a -> m b) -> [a] -> m [b]
mapM' _ [] = return []
mapM' f xs = mapMm f xs []
mapMm _ [] ss = return $ reverse ss
mapMm f (x:xs) ss = do
s <- f x
mapMm f xs $ s : ss
-- 3.4
pytTri = do
mapM_ putStrLn $ map show pythagorean
pythagorean = [ (x,y,m*m+n*n) | m <- [2..100],
n <- [1 .. m-1],
let x = m*m-n*n,
let y = 2*m*n,
x < 100,
y < 100,
m*m + n*n < 100
]
-- 4.1
filterOdd :: IO ()
filterOdd = do
s <- getContents
putStr . unlines . map snd . filter (even . fst) $ zip [1..] $ lines s
-- 4.2
numberLines :: IO ()
numberLines = interact (unlines . map (\(x, y) -> show x ++ ' ' : y) . zip [1 ..] . lines)
-- 4.3
filterWords :: S.Set String -> IO ()
filterWords xs = interact (unwords . filter (\x -> S.notMember x xs) . words)
-- 5.1
wc :: FilePath -> IO (Int, Int, Int)
wc f = do
s <- readFile f
return (length s, length $ words s, length $ lines s)
-- 5.2
copyLines :: [Int] -> FilePath -> FilePath -> IO ()
copyLines ls f1 f2 = do
s <- readFile f1
writeFile f2 $ unlines . map snd . filter (\(l, _) -> elem l ls) . zip [1..] $ lines s
-- 6.1
wordTypes :: FilePath -> IO Int
wordTypes f = do
s <- readFile f
return $ length $ nub $ words s
-- 6.2
diff :: FilePath -> FilePath -> IO ()
diff f1 f2 = do
s1 <- readFile f1
s2 <- readFile f2
let ss = zip (lines s1) (lines s2)
putStrLn $ unlines . map (\(x, y) -> "<" ++ x ++ "\n" ++ ">" ++ y) $ filter (\(x, y) -> x /= y) ss
-- 7.1
fileHead :: IO ()
fileHead = do
xs <- getArgs
let n = read $ head xs :: Int
let f = head $ tail xs
s <- readFile f
putStrLn $ unlines $ take n $ lines s
-- 8.2
randomPositions :: Int -> Int -> Int -> Int -> IO [(Int, Int)]
randomPositions xl xu yl yu = do
g <- getStdGen
g2 <- newStdGen
return $ zip (randomRs (xl, xu) g) (randomRs(yl, yu) g2)
| kbiscanic/PUH | hw09/exercises.hs | mit | 6,097 | 4 | 15 | 1,790 | 2,925 | 1,486 | 1,439 | 187 | 2 |
-- | An untyped socket service. Perhaps a better abstractions would be typed
-- sockets, where the types are serialised either as json and sent as text, or
-- as binary and sent as blobs.
module Blaze2.Core.Service.Socket
( SocketA(..)
, SocketR(..)
, Socket
, Url
, Protocol
) where
import qualified Data.Text as T
type Socket = (SocketA -> IO ()) -> SocketR -> IO ()
type Url = T.Text
type Protocol = T.Text
data SocketR
= OpenSocket Url [Protocol]
| CloseSocket
| SendMessage T.Text
deriving (Show, Eq)
data SocketA
= SocketOpened Protocol
| SocketClosed
| MessageReceived T.Text
| SocketError T.Text
deriving (Show)
| MoixaEnergy/blaze-react | src/Blaze2/Core/Service/Socket.hs | mit | 687 | 0 | 9 | 169 | 159 | 97 | 62 | 21 | 0 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.NotificationCenter
(js_createNotification, createNotification, js_checkPermission,
checkPermission, js_requestPermission, requestPermission,
NotificationCenter, castToNotificationCenter,
gTypeNotificationCenter)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe
"$1[\"createNotification\"]($2, $3,\n$4)" js_createNotification ::
NotificationCenter ->
JSString -> JSString -> JSString -> IO (Nullable Notification)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NotificationCenter.createNotification Mozilla NotificationCenter.createNotification documentation>
createNotification ::
(MonadIO m, ToJSString iconUrl, ToJSString title,
ToJSString body) =>
NotificationCenter ->
iconUrl -> title -> body -> m (Maybe Notification)
createNotification self iconUrl title body
= liftIO
(nullableToMaybe <$>
(js_createNotification (self) (toJSString iconUrl)
(toJSString title)
(toJSString body)))
foreign import javascript unsafe "$1[\"checkPermission\"]()"
js_checkPermission :: NotificationCenter -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NotificationCenter.checkPermission Mozilla NotificationCenter.checkPermission documentation>
checkPermission :: (MonadIO m) => NotificationCenter -> m Int
checkPermission self = liftIO (js_checkPermission (self))
foreign import javascript unsafe "$1[\"requestPermission\"]($2)"
js_requestPermission ::
NotificationCenter -> Nullable VoidCallback -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/NotificationCenter.requestPermission Mozilla NotificationCenter.requestPermission documentation>
requestPermission ::
(MonadIO m) => NotificationCenter -> Maybe VoidCallback -> m ()
requestPermission self callback
= liftIO (js_requestPermission (self) (maybeToNullable callback)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/NotificationCenter.hs | mit | 2,840 | 26 | 11 | 466 | 609 | 359 | 250 | 46 | 1 |
-- Parse the input stream and return a structured representation.
-- TODO validate label
-- TODO validate int is within word size limit
module SimpleAsmParser(
parseAsmProgram
)where
import Parser
import qualified SimpleAsmArchitecture as A
import SimpleAsmGrammer
import Control.Applicative((<$>),(<*>))
import Control.Monad(when)
import Data.Char(isSpace,isDigit)
-- util --
empty :: String -> Bool
empty = and . map isSpace
preview :: String -> String
preview = (++ "...") . take 10
failToken s = fail $ "Unexpected token in stream '" ++ (preview s) ++ "'"
failEmpty = fail "Expected values in stream"
-- Parsing of an AsmProgram is almost like the grammer definition --
parseAsmProgram :: Parser AsmProgram
parseAsmProgram = AsmProgram <$> parseAsmStatements
parseAsmStatements :: Parser AsmStatements
parseAsmStatements = do
str <- get
when (null str) failEmpty
s <- parseAsmStatement
str' <- get
if null str' then
return [s]
else
(s:) <$> parseAsmStatements
parseAsmStatement :: Parser AsmStatement
parseAsmStatement = do
theline <- line
str <- get
put theline
s <- parseAsmStatementLine
put str
return s
parseAsmStatementLine :: Parser AsmStatement
parseAsmStatementLine = tryParserOtherwise
blankOrComment
(do
s <- parseStatement
b_or_c <- blankOrComment
return' s b_or_c
)
where
blankOrComment = tryParserOtherwise parseABlankLine parseAComment
return' s ABlankLine = return $ AStatement s
return' s (AComment c) = return $ AStatementWComment s c
parseABlankLine :: Parser AsmStatement
parseABlankLine = do
s <- get
when (not . empty $ s) (failToken s)
put ""
return ABlankLine
parseAComment :: Parser AsmStatement
parseAComment = do
w <- word
when (head w /= '#') (failToken w)
s <- get
return $ AComment (w ++ s)
parseStatement :: Parser Statement
parseStatement = do
c <- peek
if isSymbol c then
(do
label <- parseLabel
tryParserOtherwise
(parseVariable label)
(parseLabeledOperation label)
)
else
SOperation <$> parseOperation
where isSymbol = not . isSpace
parseVariable :: Label -> Parser Statement
parseVariable label = do
w <- word
when (w /= "const") (failToken w)
tryParserOtherwise
(SConstant label <$> parseWord)
(return $ SVariable label)
parseLabeledOperation :: Label -> Parser Statement
parseLabeledOperation label = SLabeledOperation label <$> parseOperation
parseOperation :: Parser Operation
parseOperation = do
w <- word
case w of
"get" -> return Get
"put" -> return Put
"ld" -> Ld <$> parseObject
"st" -> St <$> parseObject
"add" -> Add <$> parseObject
"sub" -> Sub <$> parseObject
"jpos" -> Jpos <$> parseObject
"jz" -> Jz <$> parseObject
"j" -> J <$> parseObject
"halt" -> return Halt
_ -> failToken w
parseObject :: Parser Object
parseObject = tryParserOtherwise (OMemLocation <$> parseWord) (OLabel <$> parseLabel)
parseLabel :: Parser Label
parseLabel = do
w <- word
-- TODO validate word
return w
parseWord :: Parser A.Word
parseWord = do
i <- parseInt
return $ A.word i
parseInt :: Parser Int
parseInt = do
w <- word
-- TODO validate int is within word size limit?
case reads w :: [(Int,String)] of
[(i,"")] -> return i
_ -> failToken w
| kyle-ilantzis/Simple-ASM | SimpleAsmParser.hs | mit | 3,499 | 26 | 13 | 894 | 1,017 | 508 | 509 | 106 | 11 |
module GraphDB.Macros where
import GraphDB.Util.Prelude
import GraphDB.Util.Prelude.TH
import qualified GraphDB.Util.TH as THU
import qualified GraphDB.Graph as G
import qualified GraphDB.Model as M
import qualified GraphDB.Macros.Templates as T
import qualified GraphDB.Macros.Analysis as A
-- |
-- Generate all the boilerplate code by the type of the root node.
deriveSetup :: Name -> Q [Dec]
deriveSetup root = do
-- The work is done in three phases:
-- 1. While in the 'Q' monad, reify all the required information.
-- 2. Leave the 'Q' monad and run a pure analysis on that information
-- to produce settings for templates to render.
-- 3. While still out of the 'Q' monad, render all the templates.
--
-- Such strategy allows to separate the concerns and
-- exploit parallelism in the last two phases.
edgePairs <- reifyEdgePairs
let (polyIndexS, polyValueS, hashableS, serializableS, setupS) = A.decs (ConT root) edgePairs
hashableS' <- filterM (fmap not . isInstance' ''Hashable . (:[])) hashableS
serializableS' <-
filterM
(fmap not . isInstance' ''Serializable . (\t -> [ConT ''IO, t]))
serializableS
return $ T.renderDecs (polyIndexS, polyValueS, hashableS', serializableS', setupS)
-- |
-- Scan the current module for instance declarations of 'M.Edge' and
-- collect the pairs of the types they link.
reifyEdgePairs :: Q [(Type, Type)]
reifyEdgePairs = do
instances <- THU.reifyLocalInstances
return $ do
(n, tl) <- instances
guard $ n == ''M.Edge
case tl of [a, b] -> return (a, b)
| nikita-volkov/graph-db | library/GraphDB/Macros.hs | mit | 1,561 | 0 | 15 | 299 | 351 | 201 | 150 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module GhostLang.Compiler.ModuleFileReader
( runModuleReader
, parseGhostModules
) where
import Control.Exception (SomeException, try)
import Control.Monad.State (MonadState, StateT, evalStateT, modify', get)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.List (delete, find)
import GhostLang.Interpreter (IntrinsicSet)
import GhostLang.Compiler.Grammar (ghostModuleDef)
import GhostLang.Types ( ImportDecl (..)
, GhostModule (..)
)
import Text.Parsec (ParseError)
import Text.Parsec.String (parseFromFile)
import Text.Printf (printf)
import System.FilePath
type ParseResult = Either ParseError (GhostModule IntrinsicSet)
type PendList = [(FilePath, Bool)]
data Result = Ok | FailedWith String
deriving Eq
data State = State { baseDir :: !FilePath
, pendList :: ![(FilePath, Bool)]
, modList :: ![GhostModule IntrinsicSet] }
-- | Monad stack for module reading. Just StateT on top of IO.
newtype ModuleReader a =
ModuleReader { extrModuleReader :: StateT State IO a }
deriving (Functor, Applicative, Monad, MonadState State, MonadIO)
-- | Run the ModuleReader monad stack.
runModuleReader :: ModuleReader a -> IO a
runModuleReader act = evalStateT (extrModuleReader act) emptyState
-- | Entry for the parsing of modules parsing.
parseGhostModules :: FilePath
-> ModuleReader (Either String [GhostModule IntrinsicSet])
parseGhostModules path = do
-- Save the base directory for the input - Main - file. It will be
-- used as base for all file reads.
setBaseDir $ takeDirectory path
-- Add the first pending. Pendings is what make the engine run.
addPending $ takeFileName path
result <- parseLoop
case result of
Ok -> do
mods <- getModList
return $ Right mods
FailedWith msg -> return $ Left msg
-- | Parse until all pending files are consumed or an error has
-- occurred.
parseLoop :: ModuleReader Result
parseLoop = do
pending <- nextPending
case pending of
Just file -> do
result <- parseGhostMod file
if result == Ok then parseLoop
else return result
-- No more modules to read, and no errors. Done!
Nothing -> return Ok
-- | The parsing workhorse.
parseGhostMod :: FilePath -> ModuleReader Result
parseGhostMod file = do
-- Combine the filename with the stored base to form a complete
-- path.
path <- combineWithBaseDir file
-- Invoke the parser. The result is Either in two levels, exception
-- level and parser error level.
maybeFailed <- liftIO $ tryParse path
case maybeFailed of
Right res -> case res of
Right m -> do togglePending file
addModule m
mapM_ addPending $ importSet m
return Ok
Left msg -> return $ FailedWith (show msg)
Left exc -> return $ FailedWith (printf "Got %s when reading %s"
(show exc) path)
where
tryParse :: FilePath -> IO (Either SomeException ParseResult)
tryParse path = try $ parseFromFile ghostModuleDef path
combineWithBaseDir :: FilePath -> ModuleReader FilePath
combineWithBaseDir file = combine <$> (baseDir <$> get) <*> pure file
setBaseDir :: FilePath -> ModuleReader ()
setBaseDir path = modify' $ \s -> s { baseDir = path }
addPending :: FilePath -> ModuleReader ()
addPending file = modify' $ \s -> s { pendList = addPending' file (pendList s) }
nextPending :: ModuleReader (Maybe FilePath)
nextPending = do
xs <- pendList <$> get
return $ fmap fst (find snd xs)
togglePending :: FilePath -> ModuleReader ()
togglePending file =
modify' $ \s -> s { pendList = togglePending' file (pendList s) }
addModule :: GhostModule IntrinsicSet -> ModuleReader ()
addModule m = modify' $ \s -> s { modList = m : modList s }
getModList :: ModuleReader [GhostModule IntrinsicSet]
getModList = modList <$> get
emptyState :: State
emptyState = State { baseDir = "", pendList = [], modList = [] }
addPending' :: FilePath -> PendList -> PendList
addPending' fp xs = maybe ((fp, True):xs) (const xs) (lookup fp xs)
togglePending' :: FilePath -> PendList -> PendList
togglePending' file xs = maybe xs (\tup -> (file, False):delete tup xs)
(find ((==file) . fst) xs)
importSet :: GhostModule IntrinsicSet -> [FilePath]
importSet (GhostModule _ idecl _ _) = map makeRoot idecl
where
makeRoot :: ImportDecl -> FilePath
makeRoot (ImportDecl decl) = addExtension (joinPath decl) "gl"
| kosmoskatten/ghost-lang | ghost-lang/src/GhostLang/Compiler/ModuleFileReader.hs | mit | 4,686 | 0 | 16 | 1,163 | 1,259 | 662 | 597 | 97 | 3 |
module Main where
import System.ZMQ4.Monadic
import Control.Monad (formM_)
import Data.ByteString.Char8 (pack, unpack)
main :: IO ()
main =
runZMQ $ do
liftIO $ putStrLn "connecting to hello world server"
reqSocket <- socket Req
connect reqSocket "tcp://localhost:5555"
forM_ [1..10] $ \i -> do
liftIO $ putStrLn $ unwords ["Sending request", show i]
send reqSocket [] (pack "Hello")
reply <- receive reqSocket
liftIO $ putStrLn $ unwords ["Received Reply", unpack reply]
| softwaremechanic/Miscellaneous | Haskell/msg_server/hello_world.hs | gpl-2.0 | 534 | 0 | 15 | 131 | 175 | 87 | 88 | 15 | 1 |
module Backends.Haskell.Syntax where
import Pretty
import Data.List (intersperse,sortBy)
import Data.Maybe (fromMaybe)
import Data.Ord (comparing)
import Text.PrettyPrint
type Name = String
type Var = String
-- module ... where <import>* <definition>*
data HSMod = HSMod [HSImport] [HSDef] deriving Show
-- <import>: import module.name
data HSImport = HSImport [String] deriving Show
-- <definition>: <funcdecl>* | data <name> <var>* = <constructor>*
data HSDef = HSFuncDef [HSDecl]
| HSDataDef Name [Var] [HSDataConstr] deriving Show
-- <constructor>: <name> <type>*
data HSDataConstr = HSDataConstr Name [HSType] deriving Show
-- <type>: <name> <type>* | <var>
data HSType = HSType Name [HSType] | HSTypeVar Var deriving Show
-- <funcdecl>: <name> <pat>* = <expr>
data HSDecl = HSDecl Name [HSPat] HSExpr deriving Show
-- <pat>: <var>
data HSPat = PVar Var deriving Show
-- <expr>: <expr> <expr> | <var> | <string> | <int> | <name>
data HSExpr = HSExpr `HSApp` HSExpr | HSVar Var | HSString String | HSInt Int
| HSOp Name deriving Show
-------- PRETTY PRINTING ---------
instance Pretty HSMod where pretty = prettyMod "Main"
instance Pretty HSImport where pretty = prettyImport
instance Pretty HSDef where pretty = prettyDefinition
instance Pretty HSDataConstr where pretty = prettyDataConstr
instance Pretty HSType where pretty = prettyType
instance Pretty HSDecl where pretty = prettyDeclaration
instance Pretty HSPat where pretty = prettyPat
instance Pretty HSExpr where pretty = prettyExpr
prettyMod modname (HSMod imports definitions)
= text "module" <+> text modname <+> text "where" $+$
emptyLine $+$
(vcat . map prettyImport . sortBy (comparing moduleparts) $ imports) $+$
emptyLine $+$
(vcat . intersperse emptyLine $ map prettyDefinition definitions)
where
emptyLine = text ""
moduleparts (HSImport modparts) = modparts
prettyImport (HSImport modparts)
= text "import" <+> (hcat . punctuate (char '.') $ map text modparts)
prettyDefinition (HSFuncDef declarations)
= vcat $ map prettyDeclaration declarations
prettyDefinition (HSDataDef typename typeargs constructors)
= text "data" <+> text typename <+> hsep (map text typeargs) <+>
if null constructors
then empty
else sep (text "=" <+> prettyDataConstr (head constructors)
:map ((text "|" <+>) . prettyDataConstr) (tail constructors))
prettyDataConstr (HSDataConstr name subtypes)
= text name <+> sep (map prettyType subtypes)
prettyType (HSType typename subtypes)
= parens $ text typename <+> sep (map prettyType subtypes)
prettyType (HSTypeVar var)
= text var
prettyDeclaration (HSDecl name pattern expr)
= sep [sep (signature ++ [char '=']), nest 2 (prettyExpr expr)]
where
signature = text name : map prettyPat pattern
prettyPat (PVar varname) = text varname
prettyExpr (HSApp operator operand) = parens $ sep [prettyExpr operator
,nest 2 (prettyExpr operand)]
prettyExpr (HSVar varname) = hsVar varname
prettyExpr (HSString cont) = text . show $ cont
prettyExpr (HSInt num) = int num
prettyExpr (HSOp operator) = parens (text operator)
hsVar varname = if hsOperator varname
then parens . text $ varname
else text . hsEscape $ varname
hsOperator = all operatorChar
where
operatorChar = (`elem` ":.,$<>+-*/%&^=?!~|#")
hsEscape = concatMap escapeChar
where
escapeChar c = fromMaybe [c] $ lookup c escapetable
escapetable = [('-', "_minus_")
,('+', "_plus_")
,('*', "_star_")
,('/', "_slash_")
,('%', "_percent_")
,('&', "_ampersand_")
,('^', "_caret_")
,('=', "_equals_")
,('?', "_quest_")
,('!', "_bang_")
,('~', "_tilde_")
,('|', "_bar_")
,('#', "_hash_")
--,('_', "_underscore_")
]
| keenbug/iexpr | Backends/Haskell/Syntax.hs | gpl-2.0 | 4,054 | 0 | 14 | 1,007 | 1,159 | 624 | 535 | 80 | 2 |
{-# LANGUAGE ExplicitForAll #-}
module HOF where
import HipSpec
import Prelude hiding (zipWith,curry,map,zip)
p f = id . f =:= f . id
op :: (A -> A -> A) -> A -> A -> A
op f x y = f x y
r = op const =:= \ x y -> x
q f g = id . f . g =:= f . g
| danr/hipspec | examples/HOF.hs | gpl-3.0 | 249 | 0 | 8 | 73 | 136 | 74 | 62 | -1 | -1 |
module FormalLanguage.CFG.PrettyPrint
( module FormalLanguage.CFG.PrettyPrint.ANSI
, module FormalLanguage.CFG.PrettyPrint.Haskell
-- , module FormalLanguage.CFG.PrettyPrint.LaTeX
) where
import FormalLanguage.CFG.PrettyPrint.ANSI
import FormalLanguage.CFG.PrettyPrint.Haskell
--import FormalLanguage.CFG.PrettyPrint.LaTeX
| choener/FormalGrammars | FormalLanguage/CFG/PrettyPrint.hs | gpl-3.0 | 333 | 0 | 5 | 30 | 41 | 30 | 11 | 5 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeOperators #-}
module Routes.Admin.Surcharges
( SurchargesAPI
, surchargesRoutes
) where
import Data.Aeson (ToJSON(..), FromJSON(..), (.=), (.:), withObject, object)
import Data.Maybe (isNothing, mapMaybe)
import Database.Persist ((/<-.), Entity(..), replace, selectList, deleteWhere, insertMany_)
import Servant ((:<|>)(..), (:>), AuthProtect, ReqBody, Get, Post, JSON)
import Auth (WrappedAuthToken, Cookied, withAdminCookie, validateAdminAndParameters)
import Models
import Models.Fields (Cents)
import Routes.CommonData (AdminCategorySelect, makeAdminCategorySelects, validateCategorySelect)
import Server
import Validation (Validation(..))
import qualified Data.List as L
import qualified Data.Text as T
import qualified Validation as V
type SurchargesAPI =
"data" :> SurchargesDataRoute
:<|> "update" :> SurchargesUpdateRoute
type SurchargeRoutes =
(WrappedAuthToken -> App (Cookied SurchargesData))
:<|> (WrappedAuthToken -> SurchagesUpdateParameters -> App (Cookied ()))
surchargesRoutes :: SurchargeRoutes
surchargesRoutes =
surchargesDataRoute
:<|> surchargesUpdateRoute
-- DATA
type SurchargesDataRoute =
AuthProtect "cookie-auth"
:> Get '[JSON] (Cookied SurchargesData)
data SurchargesData =
SurchargesData
{ sdSurcharges :: [SurchargeData]
, sdAllCategories :: [AdminCategorySelect]
} deriving (Show)
instance ToJSON SurchargesData where
toJSON SurchargesData {..} =
object
[ "surcharges" .= sdSurcharges
, "categories" .= sdAllCategories
]
data SurchargeData =
SurchargeData
{ sdId :: Maybe SurchargeId
, sdDescription :: T.Text
, sdSingleFee :: Cents
, sdMultipleFee :: Cents
, sdCategories :: [CategoryId]
, sdIsActive :: Bool
} deriving (Show)
instance ToJSON SurchargeData where
toJSON SurchargeData {..} =
object
[ "id" .= sdId
, "description" .= sdDescription
, "singleFee" .= sdSingleFee
, "multipleFee" .= sdMultipleFee
, "categories" .= sdCategories
, "isActive" .= sdIsActive
]
instance FromJSON SurchargeData where
parseJSON = withObject "SurchargeData" $ \v -> do
sdId <- v .: "id"
sdDescription <- v .: "description"
sdSingleFee <- v .: "singleFee"
sdMultipleFee <- v .: "multipleFee"
sdCategories <- v .: "categories"
sdIsActive <- v .: "isActive"
return SurchargeData {..}
surchargesDataRoute :: WrappedAuthToken -> App (Cookied SurchargesData)
surchargesDataRoute t = withAdminCookie t $ \_ -> do
(categories, surcharges) <- runDB $
(,) <$> makeAdminCategorySelects <*> selectList [] []
return SurchargesData
{ sdSurcharges = map makeSurchargeData surcharges
, sdAllCategories = categories
}
where
makeSurchargeData :: Entity Surcharge -> SurchargeData
makeSurchargeData (Entity sId sur) =
SurchargeData
{ sdId = Just sId
, sdDescription = surchargeDescription sur
, sdSingleFee = surchargeSingleFee sur
, sdMultipleFee = surchargeMultipleFee sur
, sdCategories = surchargeCategoryIds sur
, sdIsActive = surchargeIsActive sur
}
-- UPDATE
type SurchargesUpdateRoute =
AuthProtect "cookie-auth"
:> ReqBody '[JSON] SurchagesUpdateParameters
:> Post '[JSON] (Cookied ())
newtype SurchagesUpdateParameters =
SurchagesUpdateParameters
{ supSurcharges :: [SurchargeData]
} deriving (Show)
instance FromJSON SurchagesUpdateParameters where
parseJSON = withObject "SurchagesUpdateParameters" $ \v -> do
supSurcharges <- v .: "surcharges"
return SurchagesUpdateParameters {..}
instance Validation SurchagesUpdateParameters where
validators SurchagesUpdateParameters {..} =
V.indexedValidation "surcharge" validateSurcharge supSurcharges
where
validateSurcharge :: SurchargeData -> App [(T.Text, [(T.Text, Bool)])]
validateSurcharge SurchargeData {..} =
validateCategorySelect True sdCategories
surchargesUpdateRoute :: WrappedAuthToken -> SurchagesUpdateParameters -> App (Cookied ())
surchargesUpdateRoute = validateAdminAndParameters $ \_ SurchagesUpdateParameters {..} -> do
let (new, existing) = L.partition (isNothing . sdId) supSurcharges
runDB $ do
deleteWhere [SurchargeId /<-. mapMaybe sdId existing]
insertMany_ $ map convert new
mapM_ (\s -> mapM_ (\i -> replace i $ convert s ) $ sdId s ) existing
return ()
where
convert :: SurchargeData -> Surcharge
convert SurchargeData {..} =
Surcharge
{ surchargeDescription = sdDescription
, surchargeSingleFee = sdSingleFee
, surchargeMultipleFee = sdMultipleFee
, surchargeCategoryIds = sdCategories
, surchargeIsActive = sdIsActive
}
| Southern-Exposure-Seed-Exchange/southernexposure.com | server/src/Routes/Admin/Surcharges.hs | gpl-3.0 | 5,167 | 0 | 20 | 1,278 | 1,239 | 687 | 552 | 120 | 1 |
{-# LANGUAGE EmptyDataDecls #-}
{-|
Module : Database/Hedsql/Drivers/SqLite/Driver.hs
Description : SqLite driver.
Copyright : (c) Leonard Monnier, 2014
License : GPL-3
Maintainer : leonard.monnier@gmail.com
Stability : experimental
Portability : portable
SqLite driver.
-}
module Database.Hedsql.Drivers.SqLite.Driver
( SqLite
) where
-- | SQLite driver.
data SqLite | momomimachli/Hedsql | src/Database/Hedsql/Drivers/SqLite/Driver.hs | gpl-3.0 | 393 | 0 | 4 | 70 | 20 | 15 | 5 | -1 | -1 |
import qualified Data.Map as M
data LockerState = Taken | Free deriving (Show, Eq)
type Code = String
type LockerMap = M.Map Int (LockerState, Code)
lockerlookup :: Int -> LockerMap -> Either String Code
lockerlookup lockernumber map =
case M.lookup lockernumber map of
Nothing -> Left $ "Locker number " ++ show lockernumber ++ " doesn't exist!"
Just (state, code) -> if state /= Taken
then Right code
else Left $ "Locker " ++ show lockernumber ++ " is already taken!"
lockers :: LockerMap
lockers = M.fromList
[(100, (Taken, "ZA39I")),
(101, (Free, "JAH3I")),
(103, (Free, "IQSA9")),
(105, (Free,"QOTSA")),
(109, (Taken, "893JJ")),
(110, (Taken, "99292"))
]
| ljwolf/learnyouahaskell-assignments | ex.locker.hs | gpl-3.0 | 709 | 30 | 11 | 154 | 295 | 168 | 127 | 19 | 3 |
{-# LANGUAGE TemplateHaskell #-}
module Vdv.Service where
import ClassyPrelude
import Control.Lens(makePrisms)
import Options.Applicative(ReadM,eitherReader)
data Service = ServiceAUS
| ServiceDFI
deriving(Eq,Show,Bounded,Read,Enum)
$(makePrisms ''Service)
serviceContainer :: Service -> Text
serviceContainer ServiceAUS = "AUSNachricht"
serviceContainer ServiceDFI = "AZBNachricht"
journeyContainer :: Service -> [Text]
journeyContainer ServiceAUS = ["IstFahrt"]
journeyContainer ServiceDFI = ["AZBFahrplanLage","AZBFahrtLoeschen"]
parseService :: String -> Either String Service
parseService "AUS" = Right ServiceAUS
parseService "DFI" = Right ServiceDFI
parseService s = Left ("Invalid service " <> s)
serviceOpt :: ReadM Service
serviceOpt = eitherReader parseService
| pmiddend/vdvanalyze | src/Vdv/Service.hs | gpl-3.0 | 805 | 0 | 8 | 115 | 210 | 112 | 98 | 21 | 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.Productstatuses.Custombatch
-- 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)
--
-- Gets the statuses of multiple products in a single request. 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.productstatuses.custombatch@.
module Network.Google.Resource.Content.Productstatuses.Custombatch
(
-- * REST Resource
ProductstatusesCustombatchResource
-- * Creating a Request
, productstatusesCustombatch
, ProductstatusesCustombatch
-- * Request Lenses
, pPayload
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.productstatuses.custombatch@ method which the
-- 'ProductstatusesCustombatch' request conforms to.
type ProductstatusesCustombatchResource =
"content" :>
"v2" :>
"productstatuses" :>
"batch" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ProductstatusesCustomBatchRequest :>
Post '[JSON] ProductstatusesCustomBatchResponse
-- | Gets the statuses of multiple products in a single request. This method
-- can only be called for non-multi-client accounts.
--
-- /See:/ 'productstatusesCustombatch' smart constructor.
newtype ProductstatusesCustombatch = ProductstatusesCustombatch'
{ _pPayload :: ProductstatusesCustomBatchRequest
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProductstatusesCustombatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pPayload'
productstatusesCustombatch
:: ProductstatusesCustomBatchRequest -- ^ 'pPayload'
-> ProductstatusesCustombatch
productstatusesCustombatch pPPayload_ =
ProductstatusesCustombatch'
{ _pPayload = pPPayload_
}
-- | Multipart request metadata.
pPayload :: Lens' ProductstatusesCustombatch ProductstatusesCustomBatchRequest
pPayload = lens _pPayload (\ s a -> s{_pPayload = a})
instance GoogleRequest ProductstatusesCustombatch
where
type Rs ProductstatusesCustombatch =
ProductstatusesCustomBatchResponse
type Scopes ProductstatusesCustombatch =
'["https://www.googleapis.com/auth/content"]
requestClient ProductstatusesCustombatch'{..}
= go (Just AltJSON) _pPayload shoppingContentService
where go
= buildClient
(Proxy :: Proxy ProductstatusesCustombatchResource)
mempty
| rueshyna/gogol | gogol-shopping-content/gen/Network/Google/Resource/Content/Productstatuses/Custombatch.hs | mpl-2.0 | 3,348 | 0 | 13 | 693 | 310 | 191 | 119 | 50 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.ToolResults
-- 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)
--
-- API to publish and access results from developer tools.
--
-- /See:/ <https://firebase.google.com/docs/test-lab/ Cloud Tool Results API Reference>
module Network.Google.ToolResults
(
-- * Service Configuration
toolResultsService
-- * API Declaration
, ToolResultsAPI
-- * Types
-- ** LauncherActivityNotFound
, LauncherActivityNotFound
, launcherActivityNotFound
-- ** NATiveCrash
, NATiveCrash
, nATiveCrash
, natcStackTrace
-- ** OverlAppingUIElements
, OverlAppingUIElements
, overlAppingUIElements
, oauieResourceName
, oauieScreenId
-- ** RoboScriptExecution
, RoboScriptExecution
, roboScriptExecution
, rseTotalActions
, rseSuccessfulActions
-- ** ANR
, ANR
, aNR
, aStackTrace
-- ** InAppPurchasesFound
, InAppPurchasesFound
, inAppPurchasesFound
, iapfInAppPurchasesFlowsExplored
, iapfInAppPurchasesFlowsStarted
-- ** EncounteredNonAndroidUiWidgetScreen
, EncounteredNonAndroidUiWidgetScreen
, encounteredNonAndroidUiWidgetScreen
, enauwsDistinctScreens
, enauwsScreenIds
-- ** StartActivityNotFound
, StartActivityNotFound
, startActivityNotFound
, sanfURI
, sanfAction
-- ** AvailableDeepLinks
, AvailableDeepLinks
, availableDeepLinks
-- ** IosAppCrashed
, IosAppCrashed
, iosAppCrashed
, iacStackTrace
-- ** UpgradeInsight
, UpgradeInsight
, upgradeInsight
, uiPackageName
, uiUpgradeToVersion
-- ** PerformedMonkeyActions
, PerformedMonkeyActions
, performedMonkeyActions
, pmaTotalActions
-- ** NonSdkAPIUsageViolationReport
, NonSdkAPIUsageViolationReport
, nonSdkAPIUsageViolationReport
, nsauvrMinSdkVersion
, nsauvrTargetSdkVersion
, nsauvrUniqueAPIs
, nsauvrExampleAPIs
-- ** PendingGoogleUpdateInsight
, PendingGoogleUpdateInsight
, pendingGoogleUpdateInsight
, pguiNameOfGoogleLibrary
-- ** StackTrace
, StackTrace
, stackTrace
, stException
-- ** NonSdkAPIUsageViolation
, NonSdkAPIUsageViolation
, nonSdkAPIUsageViolation
, nsauvAPISignatures
, nsauvUniqueAPIs
-- ** UIElementTooDeep
, UIElementTooDeep
, uIElementTooDeep
, uietdScreenStateId
, uietdDepth
, uietdScreenId
-- ** PerformedGoogleLogin
, PerformedGoogleLogin
, performedGoogleLogin
-- ** Xgafv
, Xgafv (..)
-- ** NonSdkAPIInsight
, NonSdkAPIInsight
, nonSdkAPIInsight
, nsaiUpgradeInsight
, nsaiPendingGoogleUpdateInsight
, nsaiExampleTraceMessages
, nsaiMatcherId
-- ** UsedRoboIgnoreDirective
, UsedRoboIgnoreDirective
, usedRoboIgnoreDirective
, uridResourceName
-- ** UsedRoboDirective
, UsedRoboDirective
, usedRoboDirective
, urdResourceName
-- ** UnspecifiedWarning
, UnspecifiedWarning
, unspecifiedWarning
-- ** UnusedRoboDirective
, UnusedRoboDirective
, unusedRoboDirective
, uResourceName
-- ** CrashDialogError
, CrashDialogError
, crashDialogError
, cdeCrashPackage
-- ** NonSdkAPI
, NonSdkAPI
, nonSdkAPI
, nsaList
, nsaInsights
, nsaAPISignature
, nsaExampleStackTraces
, nsaInvocationCount
-- ** InsufficientCoverage
, InsufficientCoverage
, insufficientCoverage
-- ** BlankScreen
, BlankScreen
, blankScreen
, bsScreenId
-- ** FailedToInstall
, FailedToInstall
, failedToInstall
-- ** FatalException
, FatalException
, fatalException
, feStackTrace
-- ** NonSdkAPIList
, NonSdkAPIList (..)
-- ** EncounteredLoginScreen
, EncounteredLoginScreen
, encounteredLoginScreen
, elsDistinctScreens
, elsScreenIds
) where
import Network.Google.Prelude
import Network.Google.ToolResults.Types
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Cloud Tool Results API service.
type ToolResultsAPI = ()
| brendanhay/gogol | gogol-toolresults/gen/Network/Google/ToolResults.hs | mpl-2.0 | 4,547 | 0 | 5 | 1,086 | 415 | 295 | 120 | 118 | 0 |
module Domain.Character
( Character(..)
, Stats(..)
) where
import Domain.World
data Character = Character { name :: String
, experience :: Integer
, side :: Side
, stats :: PlaceholderStats
} deriving (Show, Eq)
data Stats = PlaceholderStats {}
| markikollasch/dynasty | src/Domain/Character.hs | mpl-2.0 | 357 | 1 | 9 | 150 | 78 | 51 | 27 | 10 | 0 |
module MapGen where
import Data.Define
import Data.Const
import Data.World
import Utils.Random
import System.Random
import qualified Data.Array as A
import Data.Functor ((<$>))
import Control.Arrow (first)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
-- | instance to add, multiply etc functions from somewhere to numbers
instance Num b => Num (a -> b) where
(f + g) x = f x + g x
(f - g) x = f x - g x
(f * g) x = f x * g x
fromInteger = const . fromInteger
(abs f) x = abs $ f x
(signum f) x = signum $ f x
-- | converts HeiGenType (enumerable type) to height generator function
runHei :: HeiGenType -> HeiGen
runHei (Sines n) = getSineMap n
runHei Random = getRandomHeis
runHei (Hills n) = getHillMap n
runHei (Mountains n) = getMountainOrValleyMap n
runHei (Flat n) = getFlatMap n
runHei (DiamondSquare) = getDiamondSquareMap
runHei (Voronoi n) = getVoronoiMap n
-- | converts given type of water and height generator to a map generator
runWater :: Water -> HeiGen -> MapGen
runWater NoWater = mapGenFromHeightGen
runWater (Rivers n) = addRiversToGen n
runWater (Swamp n) = addSwampsToGen n
-- | add given type of traps to map generator
runTraps :: TrapMap -> MapGen -> MapGen
runTraps NoTraps = id
runTraps (Bonfires n) = foldr (.) id $ replicate n $ addRandomTerr Bonfire
runTraps (MagicMap n) = foldr (.) id $ replicate n $ addRandomTerr MagicNatural
-- | converts MapGenType (enumerable type) to map generator function
runMap :: MapGenType -> MapGen
runMap (MapGenType heigen avg water traps) = runTraps traps $ runWater water
$ foldr (.) (limit *. runHei heigen) $ replicate avg $ first averaging
-- | return map generator with given height generator and without water
pureMapGen :: HeiGenType -> MapGenType
pureMapGen heigen = MapGenType heigen 0 NoWater NoTraps
-- | generator of the world map
type MapGen = StdGen -> (A.Array (Int, Int) Cell, StdGen)
-- | generator of the height map
type HeiGen = StdGen -> (A.Array (Int, Int) Int, StdGen)
-- | apply first argument to the first element of the result of second argument
infixr 9 *.
(*.) :: (a -> c) -> (b -> (a, b)) -> b -> (c, b)
(f *. g) x = (f rez, x') where
(rez, x') = g x
-- | heights < 0 reduced to 0, heights > 9 reduced to 9
limit :: A.Array (Int, Int) Int -> A.Array (Int, Int) Int
limit = fmap $ max 0 . min 9
-- | smoothes the map by taking the average of neighboring cells
averaging :: A.Array (Int, Int) Int -> A.Array (Int, Int) Int
averaging arr = A.array ((0, 0), (maxX, maxY))
[((x, y), avg x y) | x <- [0..maxX], y <- [0..maxY]] where
d = [-1..1]
avg x y = (2 * (arr A.! (x, y)) + sum ((arr A.!) <$> nears))
`div` (2 + length nears) where
nears = [(x + dx, y + dy) | dx <- d, dy <- d,
isCell (x + dx) (y + dy)]
-- | converts height map to full map without any obstacles
mapFromHeights :: A.Array (Int, Int) Int -> A.Array (Int, Int) Cell
mapFromHeights = fmap (\h -> Cell {terrain = Empty, height = h})
-- | converts height generator to map generator without any obstacles
mapGenFromHeightGen :: HeiGen -> MapGen
mapGenFromHeightGen hgen = mapFromHeights *. hgen
-- | get a map with equal heights
getFlatMap :: Int -> HeiGen
getFlatMap n g = (A.listArray ((0, 0), (maxX, maxY))
[n, n..], g)
-- | get a map with random heights
getRandomHeis :: HeiGen
getRandomHeis g = (A.listArray ((0, 0), (maxX, maxY))
$ randomRs (0, 9) g', g'') where
(g', g'') = split g
-- | get a parabolic hill with radius r and center (x0, y0)
getHill :: Float -> Float -> Float -> (Int, Int) -> Float
getHill r x0 y0 (x, y) = max 0 $ r ** 2 - (fromIntegral x - x0) ** 2 - (fromIntegral y - y0) ** 2
-- | get sum of n random hills
getSumHills :: Int -> StdGen -> ((Int, Int) -> Float, StdGen)
getSumHills n g = (f, g3) where
(gr, g1) = split g
(gx, g2) = split g1
(gy, g3) = split g2
rs = randomRs (4.0, 5.0) gr
xs = randomRs (0.0, fromIntegral maxX) gx
ys = randomRs (0.0, fromIntegral maxY) gy
f = sum $ take n $ zipWith3 getHill rs xs ys
-- | get a sine wave with parameters a and b
getSineWave :: Float -> Float -> (Int, Int) -> Float
getSineWave a b (x, y) = sin $ a * fromIntegral x + b * fromIntegral y
-- | get sum of n random sine waves
getSumSines :: Int -> StdGen -> ((Int, Int) -> Float, StdGen)
getSumSines n g = (f, g2) where
(ga, g1) = split g
(gb, g2) = split g1
as = randomRs (0.1, 1.0) ga
bs = randomRs (0.1, 1.0) gb
f = sum $ take n $ zipWith getSineWave as bs
-- | get a mountain or valley (valley if true)
getMountainOrValley :: Bool -> Float -> Float -> (Int, Int) -> Float
getMountainOrValley t x0 y0 (x, y) = (* 2) $ getType $ exp $ negate $ sqrt
$ (x0 - fromIntegral x) ** 2 + (y0 - fromIntegral y) ** 2 where
getType = if t then (-) 0.004 else id
-- | get sum of n random mountains or valleys
getSumMountainOrValley :: Int -> StdGen -> ((Int, Int) -> Float, StdGen)
getSumMountainOrValley n g = (f, g3) where
(gx, g1) = split g
(gy, g2) = split g1
(gb, g3) = split g2
xs = randomRs (0.0, fromIntegral maxX) gx
ys = randomRs (0.0, fromIntegral maxY) gy
bs = randomRs (False, True) gb
f = sum $ take n $ zipWith3 getMountainOrValley bs xs ys
-- | get a map with random mountains like
-- exp (sqrt ((x - x0) ^ 2 + (y - y0) ^ 2)) and symmetric valleys
getMountains :: Int -> HeiGen
getMountains n gen = (A.array ((0, 0), (maxX, maxY))
[((x, y), sumLand (x, y)) | x <- [0..maxX], y <- [0..maxY]], g') where
(g, g') = split gen
(gx, gy)= split g
xs = randomRs (0, maxX) gx
ys = randomRs (0, maxY) gy
mnts = take n $ zipWith getMnt xs ys
vlls = take n $ drop n $ zipWith getVll xs ys
getMnt, getVll :: Int -> Int -> (Int, Int) -> Float
getMnt xMnt yMnt (x, y) = (* 2) $ exp $ negate $ sqrt
$ fromIntegral $ (xMnt - x) ^ (2 :: Int) + (yMnt - y) ^ (2 :: Int)
getVll xMnt yMnt (x, y) = (* 2) $ negate $ exp $ negate $ sqrt
$ fromIntegral $ (xMnt - x) ^ (2 :: Int) + (yMnt - y) ^ (2 :: Int)
sumMnts = floor . sum mnts
sumVlls = floor . sum vlls
sumLand = sumMnts + sumVlls
-- | get heightmap from a height function, cut-offs are for normalizeA
getMapFromFun :: (Float, Float) -> ((Int, Int) -> Float) -> A.Array (Int, Int) Int
getMapFromFun cuts f = normalizeA cuts $ A.array ((0, 0), (maxX, maxY))
[((x, y), f (x, y)) | x <- [0..maxX], y <- [0..maxY]]
-- | normalize array to [0, 9] with given cut-offs
normalizeA :: (Float, Float) -> A.Array (Int, Int) Float -> A.Array (Int, Int) Int
normalizeA (minC, maxC) a = norm <$> a where
maxA = maximum $ A.elems a
minA = minimum $ A.elems a
norm x = max 0 $ min 9 $ floor $ (x - minA) / (maxA - minA) * (maxC - minC) + minC
-- | get map with default cut-offs
getMapFromFunDef :: ((Int, Int) -> Float) -> A.Array (Int, Int) Int
getMapFromFunDef = getMapFromFun (-1.0, 11.0)
-- | height generator for hills
getHillMap :: Int -> HeiGen
getHillMap n = getMapFromFunDef *. getSumHills n
-- | height generator for sine waves
getSineMap :: Int -> HeiGen
getSineMap n = getMapFromFunDef *. getSumSines n
-- | height generator for mountains or valleys
getMountainOrValleyMap :: Int -> HeiGen
getMountainOrValleyMap n = getMapFromFunDef *. getSumMountainOrValley n
-- | add one river starts from (x, y) and flowing down
addRiver :: Int -> Int -> (A.Array (Int, Int) Cell, StdGen)
-> (A.Array (Int, Int) Cell, StdGen)
addRiver x y (wmap, g) =
if null nears
then (newWMap, g')
else uncurry addRiver (uniformFromList q nears) (newWMap, g')
where
newWMap = wmap A.// [((x, y), Cell {terrain = Water,
height = height $ wmap A.! (x, y)})]
nears =
filter (uncurry isCell &&&
((Empty ==) . terrain . (wmap A.!)) &&&
((height (wmap A.! (x, y)) >=) . height . (wmap A.!)))
[(x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)]
(q, g')= randomR (0.0, 1.0) g
-- | add 'cnt' rivers
addRivers :: Int -> MapGen -> MapGen
addRivers cnt mgen g = foldr ($) (wmap, g3) $ zipWith addRiver xs ys where
(wmap, g1) = mgen g
(gx, g2) = split g1
(gy, g3) = split g2
xs = take cnt $ randomRs (0, maxX) gx
ys = take cnt $ randomRs (0, maxY) gy
-- | add 'n' rivers to height generator
addRiversToGen :: Int -> HeiGen -> MapGen
addRiversToGen n = addRivers n . mapGenFromHeightGen
-- | add swamps with given depth
addSwamps :: Int -> A.Array (Int, Int) Int -> A.Array (Int, Int) Cell
addSwamps maxh = ((\x -> Cell {height = x, terrain =
if x <= maxh then Water else Empty}) <$>)
-- | add swamps to height generator
addSwampsToGen :: Int -> HeiGen -> MapGen
addSwampsToGen maxh hgen g = (addSwamps maxh heis, g') where
(heis, g') = hgen g
-- | add given terrain to a random place if this place is 'Empty'
addRandomTerr :: Terrain -> MapGen -> MapGen
addRandomTerr terr mgen g =
if terrain cell == Empty
then (wmap A.// [((x, y), cell {terrain = terr})], g3)
else (wmap, g3)
where
(x, g1) = randomR (0, maxX) g
(y, g2) = randomR (0, maxY) g1
(wmap, g3) = mgen g2
cell = wmap A.! (x, y)
-- | minimal power of 2 that is more than maxX and maxY
diamondSquareSize :: Int
diamondSquareSize = 128
-- | parameter for algorithm, also need to be power of 2
blockSize :: Int
blockSize = 16
-- | list of odd multiples of n
coordsOdd :: Int -> [Int]
coordsOdd n = [n, 3 * n .. diamondSquareSize - n]
-- | list of even multiples of n
coordsEven :: Int -> [Int]
coordsEven n = [0, 2 * n .. diamondSquareSize]
-- | maximum moise on first step
noiseCoeff :: Float
noiseCoeff = 10.0
-- | get bound for nois by iteration
getBound :: Int -> Float
getBound n = noiseCoeff * fromIntegral n / fromIntegral blockSize
-- | one 'diamond' step of algorithm
addDiamonds :: Int -> (M.Map (Int, Int) Float, StdGen) -> (M.Map (Int, Int) Float, StdGen)
addDiamonds n p = foldr (addDiamond n) p [(x, y) | x <- coordsOdd n, y <- coordsOdd n] where
-- | add one 'diamond' with given coords
addDiamond :: Int -> (Int, Int) -> (M.Map (Int, Int) Float, StdGen) -> (M.Map (Int, Int) Float, StdGen)
addDiamond n (x, y) (m, g) = (M.insert (x, y) newVal m, g') where
newVal = max 0.0 $ min 10.0 $ (+) noise $ flip (/) 4.0 $ sum
$ fromMaybe 5.0 . flip M.lookup m <$>
[(x - n, y - n), (x - n, y + n), (x + n, y - n), (x + n, y + n)]
(noise, g') = randomR (-bound, bound) g
bound = getBound n
-- | one 'vertical square' step of algorithm
addSquaresV :: Int -> (M.Map (Int, Int) Float, StdGen) -> (M.Map (Int, Int) Float, StdGen)
addSquaresV n p = foldr (addSquareV n) p [(x, y) | x <- coordsEven n, y <- coordsOdd n] where
-- | add one 'vertical square' with given coords
addSquareV :: Int -> (Int, Int) -> (M.Map (Int, Int) Float, StdGen) -> (M.Map (Int, Int) Float, StdGen)
addSquareV n (x, y) (m, g) = (M.insert (x, y) newVal m, g') where
newVal = max 0.0 $ min 10.0 $ (+) noise $ flip (/) 2.0 $ sum
$ fromMaybe 5.0 . flip M.lookup m <$> [(x, y - n), (x, y + n)]
(noise, g') = randomR (-bound, bound) g
bound = getBound n
-- | one 'horizontal square' step of algorithm
addSquaresH :: Int -> (M.Map (Int, Int) Float, StdGen) -> (M.Map (Int, Int) Float, StdGen)
addSquaresH n p = foldr (addSquareH n) p [(x, y) | x <- coordsOdd n, y <- coordsEven n] where
-- | add one 'horizontal square' with given coords
addSquareH :: Int -> (Int, Int) -> (M.Map (Int, Int) Float, StdGen) -> (M.Map (Int, Int) Float, StdGen)
addSquareH n (x, y) (m, g) = (M.insert (x, y) newVal m, g') where
newVal = max 0.0 $ min 10.0 $ (+) noise $ flip (/) 2.0 $ sum
$ fromMaybe 5.0 . flip M.lookup m <$> [(x - n, y), (x + n, y)]
(noise, g') = randomR (-bound, bound) g
bound = getBound n
-- | run step with distance n
diamondSquareStep :: Int -> (M.Map (Int, Int) Float, StdGen) -> (M.Map (Int, Int) Float, StdGen)
diamondSquareStep 0 = id
diamondSquareStep n = diamondSquareStep (n `div` 2) . addSquaresV n . addSquaresH n . addDiamonds n
-- | random height by given coords
addRandomHei :: (Int, Int) -> (M.Map (Int, Int) Float, StdGen) -> (M.Map (Int, Int) Float, StdGen)
addRandomHei p (m, g) = (M.insert p newVal m, g') where
(newVal, g') = randomR (0.0, 10.0) g
getStartMap :: StdGen -> (M.Map (Int, Int) Float, StdGen)
getStartMap g = foldr addRandomHei (M.empty, g) [(x, y) |
x <- coordsEven blockSize, y <- coordsEven blockSize]
-- | generate a map using 'diamond square' algorithm
diamondSquare :: StdGen -> (M.Map (Int, Int) Float, StdGen)
diamondSquare = diamondSquareStep blockSize . getStartMap where
-- | wrapped height generator
getDiamondSquareMap :: HeiGen
getDiamondSquareMap g = (A.array ((0, 0), (maxX, maxY)) $ M.toList $
M.filterWithKey isGoodKey $ floor <$> m, g') where
(m, g') = diamondSquare g
isGoodKey key _ = uncurry isCell key
-- | get height by list of centers and coords
getVoronoiHeight :: [(Float, Float)] -> (Int, Int) -> Float
getVoronoiHeight centers (x, y) = minimum $ map
(dist (fromIntegral x, fromIntegral y)) centers where
dist (x1, y1) (x2, y2) = sqrt $ (x1 - x2) ** 2 + (y1 - y2) ** 2
-- | get 'Voronoi diagram' map
getVoronoiMap :: Int -> HeiGen
getVoronoiMap cnt g = (getMapFromFun (0.0, 20.0) $ getVoronoiHeight $ zip xs ys, g2) where
(gx, g1) = split g
(gy, g2) = split g1
xs = take cnt $ randomRs (0.0, fromIntegral maxX) gx
ys = take cnt $ randomRs (0.0, fromIntegral maxY) gy
| green-orange/trapHack | src/MapGen.hs | unlicense | 13,035 | 730 | 13 | 2,701 | 5,723 | 3,163 | 2,560 | 233 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Th04 (module Th04) where
import Language.Haskell.TH
isPrime :: (Integral a) => a -> Bool
isPrime k | k <= 1 = False
| otherwise = not $ elem 0 (map (mod k) [2..k-1])
nextPrime :: (Integral a) => a -> a
nextPrime n | isPrime n = n
| otherwise = nextPrime (n+1)
doPrime :: (Integral a) => a -> a -> [a]
doPrime n m | curr > m = []
| otherwise = curr:doPrime (curr+1) m
where curr = nextPrime n
primeQ :: Int -> Int -> ExpQ
primeQ n m = [| doPrime n m |]
| egaburov/funstuff | Haskell/thsk/Th04.hs | apache-2.0 | 546 | 0 | 11 | 158 | 256 | 132 | 124 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module BeholderObserver.Controller (
addNewProject
) where
import Data.Text as T
import BeholderObserver.Data
addNewProject :: DataLoader dldr => dldr -> Text -> IO Project
addNewProject dl projectName =
let projectId = getProjectIdFromName projectName
project = Project projectId projectName []
in do
addProject dl project
return project
punct = '"' : "',./;'[]\\`-=~!@#$%^&*()_+{}|:<>?"
getProjectIdFromName :: T.Text -> T.Text
getProjectIdFromName = T.replace " " "-" . stripChars
stripChars :: T.Text -> T.Text
stripChars "" = ""
stripChars txt =
let c = T.head txt
cs = T.tail txt
in if c `elem` punct then stripChars cs else T.cons c . stripChars $ cs
| proegssilb/beholder-observer | src/BeholderObserver/Controller.hs | apache-2.0 | 765 | 0 | 11 | 175 | 222 | 113 | 109 | 21 | 2 |
module Common.Instr where
import Common.Core
import Data.Bits (shift,(.|.))
-- | Instructions are given in ascending order of the minimum opcode value
data Instr = Cls
| Ret
| Sys Addr
| Jp Addr
| Call Addr
| SeC Vx Byte
| SneC Vx Byte
| SeV Vx Vy
| LdC Vx Byte
| AddC Vx Byte
| LdV Vx Vy
| Or Vx Vy
| And Vx Vy
| Xor Vx Vy
| AddV Vx Vy
| Sub Vx Vy
| Shr Vx
| Subn Vx Vy
| Shl Vx
| SneV Vx Vy
| LdI Addr
| JpV0 Addr
| Rnd Vx Byte
| Drw Vx Vy Nybble
| Skp Vx
| Sknp Vx
| LdDT Vx
| LdK Vx
| SetDT Vx
| SetST Vx
| AddI Vx
| LdF Vx
| WrtB Vx
| WrtV Vx
| RdV Vx
deriving Show
-- | Convert two bytes to an opcode
makeOp :: Byte -> Byte -> Op
makeOp b1 b2 = fromIntegral b1 `shift` 8 .|. fromIntegral b2
-- | Generate an instruction from a given opcode
parseOp :: Op -> Either String Instr
parseOp op = case d1 of
0x0 -> case (d2,d3,d4) of
(0x0,0xe,0x0) -> Right Cls
(0x0,0xe,0xe) -> Right Ret
_ -> Right (Sys addr)
0x1 -> Right (Jp addr)
0x2 -> Right (Call addr)
0x3 -> Right (SeC vx c)
0x4 -> Right (SneC vx c)
0x5 -> Right (SeV vx vy)
0x6 -> Right (LdC vx c)
0x7 -> Right (AddC vx c)
0x8 -> case d4 of
0x0 -> Right (LdV vx vy)
0x1 -> Right (Or vx vy)
0x2 -> Right (And vx vy)
0x3 -> Right (Xor vx vy)
0x4 -> Right (AddV vx vy)
0x5 -> Right (Sub vx vy)
0x6 -> Right (Shr vx)
0x7 -> Right (Subn vx vy)
0xe -> Right (Shl vx)
_ -> wrong
0x9 -> case d4 of
0x0 -> Right (SneV vx vy)
_ -> wrong
0xa -> Right (LdI addr)
0xb -> Right (JpV0 addr)
0xc -> Right (Rnd vx c)
0xd -> Right (Drw vx vy n)
0xe -> case (d3,d4) of
(0x9,0xe) -> Right (Skp vx)
(0xa,0x1) -> Right (Sknp vx)
_ -> wrong
0xf -> case (d3,d4) of
(0x0,0x7) -> Right (LdDT vx)
(0x0,0xa) -> Right (LdK vx)
(0x1,0x5) -> Right (SetDT vx)
(0x1,0x8) -> Right (SetST vx)
(0x1,0xe) -> Right (AddI vx)
(0x2,0x9) -> Right (LdF vx)
(0x3,0x3) -> Right (WrtB vx)
(0x5,0x5) -> Right (WrtV vx)
(0x6,0x5) -> Right (RdV vx)
_ -> wrong
where d1 = wordDigit1 op
d2 = wordDigit2 op
d3 = wordDigit3 op
d4 = wordDigit4 op
addr = opAddr op
vx = d2
vy = d3
c = opConst op
n = d4
wrong = Left "Invalid opcode."
| jepugs/emul8 | src/Common/Instr.hs | apache-2.0 | 2,692 | 0 | 13 | 1,112 | 1,101 | 576 | 525 | 97 | 39 |
module Sound.Freesound.Test (
fs
, anySatisfy
, allSatisfy
, getAll
, unlessCI
) where
import Data.Aeson (FromJSON)
import Sound.Freesound
import qualified Sound.Freesound.List as L
import System.Environment (getEnv, lookupEnv)
import Test.Hspec.Core.Spec
fs :: Freesound a -> IO a
fs a = flip runFreesound a =<< apiKeyFromString `fmap` getEnv "FREESOUND_API_KEY"
anySatisfy :: (FromJSON a) => (a -> Bool) -> List a -> Freesound Bool
anySatisfy p l = do
if any p (elems l)
then return True
else do
n <- getNext l
case n of
Nothing -> return False
Just l' -> anySatisfy p l'
allSatisfy :: (FromJSON a) => (a -> Bool) -> List a -> Freesound Bool
allSatisfy p l = do
if all p (elems l)
then do
n <- getNext l
case n of
Nothing -> return True
Just l' -> allSatisfy p l'
else return False
getAll :: (FromJSON a) => List a -> Freesound [a]
getAll l =
case L.next l of
Nothing -> return $ L.elems l
Just n -> do
xs <- getAll =<< get n
return $ L.elems l ++ xs
-- | Emit spec only when _not_ running on the CI server.
unlessCI :: SpecWith () -> SpecWith ()
unlessCI action = do
e <- runIO $ lookupEnv "CI"
case e of
Nothing -> action
_ -> return ()
| kaoskorobase/freesound | test/Sound/Freesound/Test.hs | bsd-2-clause | 1,269 | 0 | 13 | 346 | 493 | 246 | 247 | 44 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE Safe #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Copyright : (C) 2013-2015, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <christiaan.baaij@gmail.com>
-}
module CLaSH.Class.Num
( -- * Arithmetic functions for arguments and results of different precision
ExtendingNum (..)
-- * Saturating arithmetic functions
, SaturationMode (..)
, SaturatingNum (..)
, boundedPlus
, boundedMin
, boundedMult
)
where
-- * Arithmetic functions for arguments and results of different precision
-- | Adding, subtracting, and multiplying values of two different (sub-)types.
class ExtendingNum a b where
-- | Type of the result of the addition or subtraction
type AResult a b
-- | Add values of different (sub-)types, return a value of a (sub-)type
-- that is potentially different from either argument.
plus :: a -> b -> AResult a b
-- | Subtract values of different (sub-)types, return a value of a (sub-)type
-- that is potentially different from either argument.
minus :: a -> b -> AResult a b
-- | Type of the result of the multiplication
type MResult a b
-- | Multiply values of different (sub-)types, return a value of a (sub-)type
-- that is potentially different from either argument.
times :: a -> b -> MResult a b
-- * Saturating arithmetic functions
-- | Determine how overflow and underflow are handled by the functions in
-- 'SaturatingNum'
data SaturationMode
= SatWrap -- ^ Wrap around on overflow and underflow
| SatBound -- ^ Become 'maxBound' on overflow, and 'minBound' on underflow
| SatZero -- ^ Become @0@ on overflow and underflow
| SatSymmetric -- ^ Become 'maxBound' on overflow, and (@'minBound' - 1@) on
-- underflow for signed numbers, and 'minBound' for unsigned
-- numbers.
deriving Eq
-- | 'Num' operators in which overflow and underflow behaviour can be specified
-- using 'SaturationMode'.
class (Bounded a, Num a) => SaturatingNum a where
-- | Addition with parametrisable over- and underflow behaviour
satPlus :: SaturationMode -> a -> a -> a
-- | Subtraction with parametrisable over- and underflow behaviour
satMin :: SaturationMode -> a -> a -> a
-- | Multiplication with parametrisable over- and underflow behaviour
satMult :: SaturationMode -> a -> a -> a
{-# INLINE boundedPlus #-}
-- | Addition that clips to 'maxBound' on overflow, and 'minBound' on underflow
boundedPlus :: SaturatingNum a => a -> a -> a
boundedPlus = satPlus SatBound
{-# INLINE boundedMin #-}
-- | Subtraction that clips to 'maxBound' on overflow, and 'minBound' on
-- underflow
boundedMin :: SaturatingNum a => a -> a -> a
boundedMin = satMin SatBound
{-# INLINE boundedMult #-}
-- | Multiplication that clips to 'maxBound' on overflow, and 'minBound' on
-- underflow
boundedMult :: SaturatingNum a => a -> a -> a
boundedMult = satMult SatBound
| Ericson2314/clash-prelude | src/CLaSH/Class/Num.hs | bsd-2-clause | 3,044 | 0 | 9 | 623 | 332 | 200 | 132 | 38 | 1 |
------------------------------------------------------------------------------
-- |
-- Module: Blaze.ByteString.Builder.Char.Utf8
-- Copyright: (c) 2013 Leon P Smith
-- License: BSD3
-- Maintainer: Leon P Smith <leon@melding-monads.com>
-- Stability: experimental
--
------------------------------------------------------------------------------
module Blaze.ByteString.Builder.Char.Utf8
(
-- * Writing UTF-8 encoded characters to a buffer
writeChar
-- * Creating Builders from UTF-8 encoded characters
, fromChar
, fromString
, fromShow
, fromText
, fromLazyText
) where
import Data.Monoid
import Blaze.ByteString.Builder.Compat.Write (Write, writePrimBounded)
import Data.ByteString.Builder ( Builder )
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Builder.Prim as P
import qualified Data.Text as TS
import qualified Data.Text.Lazy as TL
writeChar :: Char -> Write
writeChar = writePrimBounded P.charUtf8
fromChar :: Char -> Builder
fromChar = B.charUtf8
fromString :: String -> Builder
fromString = B.stringUtf8
fromShow :: Show a => a -> Builder
fromShow = fromString . show
fromText :: TS.Text -> Builder
fromText = fromString . TS.unpack
fromLazyText :: TL.Text -> Builder
fromLazyText = fromString . TL.unpack
| lpsmith/blaze-builder-compat | src/Blaze/ByteString/Builder/Char/Utf8.hs | bsd-3-clause | 1,334 | 0 | 6 | 233 | 228 | 145 | 83 | 27 | 1 |
{-# OPTIONS_GHC -XTemplateHaskell -XPatternGuards #-}
module Compile (compile) where
import Control.Monad.Trans
import Harpy
import Harpy.X86Disassembler
import System.IO
import Foreign
-- our modules
import Parser
import Asm
$(callDecl "callgen" [t|Int|])
compile :: [Exp] -> IO ()
compile i = do
runCodeGen (compile' i) () ()
return ()
compile' e = do
gfunc (mapM_ generate e)
x <- callgen
dis <- disassemble
io $ putStrLn ("Disassembly:") >> mapM_ (putStrLn . showIntel) dis
io $ putStr ("Result: ") >> print x
where
io = liftIO
generate x | EInt y <- x = gconst y
| Add <- x = gadd
| Multiply <- x = gmul
| Divide <- x = gdiv
| Minus <- x = gsub
| Open <- x = error "Parsing error, invalid (mismatched) parenthesis"
| Close <- x = error "Parsing error, invalid (mismatched) parenthesis"
| thoughtpolice/calc | Compile.hs | bsd-3-clause | 967 | 0 | 11 | 314 | 308 | 151 | 157 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RebindableSyntax #-}
module Network.API.Subledger.Test.Account
( spec
, establishAccount
, establishTwoAccounts
) where
import Data.API.Subledger.Account
import Data.API.Subledger.Book
import Data.API.Subledger.Org
import Data.API.Subledger.Types
import Data.Time.Clock (getCurrentTime)
import Network.API.Subledger.Test.Book (establishBook)
import Network.API.Subledger.Test.Org (establishOrg)
import Network.API.Subledger.Test.Prelude
import Test.Hspec
spec :: SubledgerSpec
spec subledger =
describe "account specs" $
beforeWith (establishOrg subledger) $
beforeWith (establishBook subledger) $ do
it "successfully creates an account" $ \(oid, bid) -> do
result <- subledger $
return =<< (createAccount oid bid "sample account" CreditNormal -&- Reference "http://baz.quux")
result `shouldSatisfy` isRight
let Right Account { accountState = state
, accountBookId = abid
, accountBody = aBody
} = result
state `shouldBe` Active
abid `shouldBe` Just bid
aBody `shouldBe` AccountBody "sample account" (Just $ Reference "http://baz.quux") CreditNormal
context "with existing account" $
beforeWith (establishAccount subledger) $ do
it "successfully retrieves an account" $ \(oid, bid, aid) -> do
result <- subledger $
fetchAccount oid bid aid >>= return
result `shouldSatisfy` isRight
it "successfully retrieves the balance of that account" $ \(oid, bid, aid) -> do
result <- subledger $ do
t <- fmap fromUTCTime $ liftIO getCurrentTime
fetchAccountBalance oid bid aid t >>= return
result `shouldSatisfy` isRight
establishAccount :: SubledgerInterpreter -> (OrgId, BookId) -> IO (OrgId, BookId, AccountId)
establishAccount subledger (oid, bid) = do
Right Account { accountId = aid } <-
subledger $ return =<< createAccount oid bid "sample account" DebitNormal
return (oid, bid, aid)
establishTwoAccounts :: SubledgerInterpreter -> (OrgId, BookId) -> IO (OrgId, BookId, AccountId, AccountId)
establishTwoAccounts subledger (oid, bid) = do
Right Account { accountId = aid1 } <-
subledger $ return =<<
createAccount oid bid "sample account—debit" DebitNormal
Right Account { accountId = aid2 } <-
subledger $ return =<<
createAccount oid bid "sample account—credit" CreditNormal
return (oid, bid, aid1, aid2)
| whittle/subledger | subledger-tests/src/Network/API/Subledger/Test/Account.hs | bsd-3-clause | 2,626 | 0 | 21 | 636 | 685 | 367 | 318 | 57 | 1 |
{-# LANGUAGE NamedFieldPuns #-}
-- | cabal-install CLI command: run
--
module Distribution.Client.CmdRun (
-- * The @run@ CLI and action
runCommand,
runAction,
-- * Internals exposed for testing
TargetProblem(..),
selectPackageTargets,
selectComponentTarget
) where
import Distribution.Client.ProjectOrchestration
import Distribution.Client.CmdErrorMessages
import Distribution.Client.Setup
( GlobalFlags, ConfigFlags(..), ConfigExFlags, InstallFlags )
import qualified Distribution.Client.Setup as Client
import Distribution.Simple.Setup
( HaddockFlags, fromFlagOrDefault )
import Distribution.Simple.Command
( CommandUI(..), usageAlternatives )
import Distribution.Types.ComponentName
( componentNameString )
import Distribution.Text
( display )
import Distribution.Verbosity
( Verbosity, normal )
import Distribution.Simple.Utils
( wrapText, die', ordNub )
import qualified Data.Map as Map
import qualified Data.Set as Set
import Control.Monad (when)
runCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
runCommand = Client.installCommand {
commandName = "new-run",
commandSynopsis = "Run an executable.",
commandUsage = usageAlternatives "new-run"
[ "[TARGET] [FLAGS] [-- EXECUTABLE_FLAGS]" ],
commandDescription = Just $ \pname -> wrapText $
"Runs the specified executable, first ensuring it is up to date.\n\n"
++ "Any executable in any package in the project can be specified. "
++ "A package can be specified if contains just one executable. "
++ "The default is to use the package in the current directory if it "
++ "contains just one executable.\n\n"
++ "Extra arguments can be passed to the program, but use '--' to "
++ "separate arguments for the program from arguments for " ++ pname
++ ". The executable is run in an environment where it can find its "
++ "data files inplace in the build tree.\n\n"
++ "Dependencies are built or rebuilt as necessary. Additional "
++ "configuration flags can be specified on the command line and these "
++ "extend the project configuration from the 'cabal.project', "
++ "'cabal.project.local' and other files.",
commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " new-run\n"
++ " Run the executable in the package in the current directory\n"
++ " " ++ pname ++ " new-run foo-tool\n"
++ " Run the named executable (in any package in the project)\n"
++ " " ++ pname ++ " new-run pkgfoo:foo-tool\n"
++ " Run the executable 'foo-tool' in the package 'pkgfoo'\n"
++ " " ++ pname ++ " new-run foo -O2 -- dothing --fooflag\n"
++ " Build with '-O2' and run the program, passing it extra arguments.\n\n"
++ cmdCommonHelpTextNewBuildBeta
}
-- | The @build@ command does a lot. It brings the install plan up to date,
-- selects that part of the plan needed by the given or implicit targets and
-- then executes the plan.
--
-- For more details on how this works, see the module
-- "Distribution.Client.ProjectOrchestration"
--
runAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
runAction (configFlags, configExFlags, installFlags, haddockFlags)
targetStrings globalFlags = do
baseCtx <- establishProjectBaseContext verbosity cliConfig
targetSelectors <- either (reportTargetSelectorProblems verbosity) return
=<< readTargetSelectors (localPackages baseCtx) targetStrings
buildCtx <-
runProjectPreBuildPhase verbosity baseCtx $ \elaboratedPlan -> do
when (buildSettingOnlyDeps (buildSettings baseCtx)) $
die' verbosity $
"The run command does not support '--only-dependencies'. "
++ "You may wish to use 'build --only-dependencies' and then "
++ "use 'run'."
-- Interpret the targets on the command line as build targets
-- (as opposed to say repl or haddock targets).
targets <- either (reportTargetProblems verbosity) return
$ resolveTargets
selectPackageTargets
selectComponentTarget
TargetProblemCommon
elaboratedPlan
targetSelectors
-- Reject multiple targets, or at least targets in different
-- components. It is ok to have two module/file targets in the
-- same component, but not two that live in different components.
when (Set.size (distinctTargetComponents targets) > 1) $
reportTargetProblems verbosity
[TargetProblemMultipleTargets targets]
let elaboratedPlan' = pruneInstallPlanToTargets
TargetActionBuild
targets
elaboratedPlan
return elaboratedPlan'
printPlan verbosity baseCtx buildCtx
buildOutcomes <- runProjectBuildPhase verbosity baseCtx buildCtx
runProjectPostBuildPhase verbosity baseCtx buildCtx buildOutcomes
where
verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
cliConfig = commandLineFlagsToProjectConfig
globalFlags configFlags configExFlags
installFlags haddockFlags
-- | This defines what a 'TargetSelector' means for the @run@ command.
-- It selects the 'AvailableTarget's that the 'TargetSelector' refers to,
-- or otherwise classifies the problem.
--
-- For the @run@ command we select the exe if there is only one and it's
-- buildable. Fail if there are no or multiple buildable exe components.
--
selectPackageTargets :: TargetSelector PackageId
-> [AvailableTarget k] -> Either TargetProblem [k]
selectPackageTargets targetSelector targets
-- If there is exactly one buildable executable then we select that
| [target] <- targetsExesBuildable
= Right [target]
-- but fail if there are multiple buildable executables.
| not (null targetsExesBuildable)
= Left (TargetProblemMatchesMultiple targetSelector targetsExesBuildable')
-- If there are executables but none are buildable then we report those
| not (null targetsExes)
= Left (TargetProblemNoneEnabled targetSelector targetsExes)
-- If there are no executables but some other targets then we report that
| not (null targets)
= Left (TargetProblemNoExes targetSelector)
-- If there are no targets at all then we report that
| otherwise
= Left (TargetProblemNoTargets targetSelector)
where
(targetsExesBuildable,
targetsExesBuildable') = selectBuildableTargets'
. filterTargetsKind ExeKind
$ targets
targetsExes = forgetTargetsDetail
. filterTargetsKind ExeKind
$ targets
-- | For a 'TargetComponent' 'TargetSelector', check if the component can be
-- selected.
--
-- For the @run@ command we just need to check it is a executable, in addition
-- to the basic checks on being buildable etc.
--
selectComponentTarget :: PackageId -> ComponentName -> SubComponentTarget
-> AvailableTarget k -> Either TargetProblem k
selectComponentTarget pkgid cname subtarget@WholeComponent t
| CExeName _ <- availableTargetComponentName t
= either (Left . TargetProblemCommon) return $
selectComponentTargetBasic pkgid cname subtarget t
| otherwise
= Left (TargetProblemComponentNotExe pkgid cname)
selectComponentTarget pkgid cname subtarget _
= Left (TargetProblemIsSubComponent pkgid cname subtarget)
-- | The various error conditions that can occur when matching a
-- 'TargetSelector' against 'AvailableTarget's for the @run@ command.
--
data TargetProblem =
TargetProblemCommon TargetProblemCommon
-- | The 'TargetSelector' matches targets but none are buildable
| TargetProblemNoneEnabled (TargetSelector PackageId) [AvailableTarget ()]
-- | There are no targets at all
| TargetProblemNoTargets (TargetSelector PackageId)
-- | The 'TargetSelector' matches targets but no executables
| TargetProblemNoExes (TargetSelector PackageId)
-- | A single 'TargetSelector' matches multiple targets
| TargetProblemMatchesMultiple (TargetSelector PackageId) [AvailableTarget ()]
-- | Multiple 'TargetSelector's match multiple targets
| TargetProblemMultipleTargets TargetsMap
-- | The 'TargetSelector' refers to a component that is not an executable
| TargetProblemComponentNotExe PackageId ComponentName
-- | Asking to run an individual file or module is not supported
| TargetProblemIsSubComponent PackageId ComponentName SubComponentTarget
deriving (Eq, Show)
reportTargetProblems :: Verbosity -> [TargetProblem] -> IO a
reportTargetProblems verbosity =
die' verbosity . unlines . map renderTargetProblem
renderTargetProblem :: TargetProblem -> String
renderTargetProblem (TargetProblemCommon problem) =
renderTargetProblemCommon "run" problem
renderTargetProblem (TargetProblemNoneEnabled targetSelector targets) =
renderTargetProblemNoneEnabled "run" targetSelector targets
renderTargetProblem (TargetProblemNoExes targetSelector) =
"Cannot run the target '" ++ showTargetSelector targetSelector
++ "' which refers to " ++ renderTargetSelector targetSelector
++ " because "
++ plural (targetSelectorPluralPkgs targetSelector) "it does" "they do"
++ " not contain any executables."
renderTargetProblem (TargetProblemNoTargets targetSelector) =
case targetSelectorFilter targetSelector of
Just kind | kind /= ExeKind
-> "The run command is for running executables, but the target '"
++ showTargetSelector targetSelector ++ "' refers to "
++ renderTargetSelector targetSelector ++ "."
_ -> renderTargetProblemNoTargets "run" targetSelector
where
targetSelectorFilter (TargetPackage _ _ mkfilter) = mkfilter
targetSelectorFilter (TargetAllPackages mkfilter) = mkfilter
targetSelectorFilter (TargetComponent _ _ _) = Nothing
renderTargetProblem (TargetProblemMatchesMultiple targetSelector targets) =
"The run command is for running a single executable at once. The target '"
++ showTargetSelector targetSelector ++ "' refers to "
++ renderTargetSelector targetSelector ++ " which includes the executables "
++ renderListCommaAnd
[ display name
| cname@CExeName{} <- map availableTargetComponentName targets
, let Just name = componentNameString cname
]
++ "."
renderTargetProblem (TargetProblemMultipleTargets selectorMap) =
"The run command is for running a single executable at once. The targets "
++ renderListCommaAnd [ "'" ++ showTargetSelector ts ++ "'"
| ts <- ordNub (concatMap snd (concat (Map.elems selectorMap))) ]
++ " refer to different executables."
renderTargetProblem (TargetProblemComponentNotExe pkgid cname) =
"The run command is for running executables, but the target '"
++ showTargetSelector targetSelector ++ "' refers to "
++ renderTargetSelector targetSelector ++ " from the package "
++ display pkgid ++ "."
where
targetSelector = TargetComponent pkgid cname WholeComponent
renderTargetProblem (TargetProblemIsSubComponent pkgid cname subtarget) =
"The run command can only run an executable as a whole, "
++ "not files or modules within them, but the target '"
++ showTargetSelector targetSelector ++ "' refers to "
++ renderTargetSelector targetSelector ++ "."
where
targetSelector = TargetComponent pkgid cname subtarget
| mydaum/cabal | cabal-install/Distribution/Client/CmdRun.hs | bsd-3-clause | 11,902 | 0 | 25 | 2,795 | 1,765 | 918 | 847 | 184 | 4 |
{-# LANGUAGE TypeFamilies, DataKinds, GADTs, StandaloneDeriving, TemplateHaskell, GeneralizedNewtypeDeriving #-}
module TICTACTOE (TICTACTOE, CELL(..), GAME(..), (?), SOLVE(..), tq) where
import GHC.TypeLits
import TH
class Game (a :: GAME) where
(?) :: SOLVE a
instance Game START where
(?) = GameStarting
instance Game PROGRESS where
(?) = GameProgress
instance Game DRAW where
(?) = Draw
instance Game WINNERA where
(?) = WinnerA
instance Game WINNERB where
(?) = WinnerB
type instance TICTACTOE NOBODY NOBODY NOBODY NOBODY NOBODY NOBODY NOBODY NOBODY NOBODY = START
tictactoe
| mxswd/ylj-2014 | 2_proof/tictactoe/TICTACTOE.hs | bsd-3-clause | 598 | 0 | 7 | 100 | 176 | 107 | 69 | 18 | 0 |
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------
-- This is a big module, but, if you pay attention to
-- (a) the sectioning, and (b) the type signatures, the
-- structure should not be too overwhelming.
{-# LANGUAGE GADTs #-}
module X86.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import X86.Instr
import X86.Cond
import X86.Regs
import X86.RegInfo
import CodeGen.Platform
import CPrim
import Instruction
import PIC
import NCGMonad
import Size
import Reg
import Platform
-- Our intermediate code:
import BasicTypes
import BlockId
import Module ( primPackageId )
import PprCmm ()
import CmmUtils
import Cmm
import Hoopl
import CLabel
-- The rest:
import ForeignCall ( CCallConv(..) )
import OrdList
import Outputable
import Unique
import FastString
import FastBool ( isFastTrue )
import DynFlags
import Util
import Control.Monad
import Data.Bits
import Data.Int
import Data.Maybe
import Data.Word
is32BitPlatform :: NatM Bool
is32BitPlatform = do
dflags <- getDynFlags
return $ target32Bit (targetPlatform dflags)
sse2Enabled :: NatM Bool
sse2Enabled = do
dflags <- getDynFlags
return (isSse2Enabled dflags)
sse4_2Enabled :: NatM Bool
sse4_2Enabled = do
dflags <- getDynFlags
return (isSse4_2Enabled dflags)
if_sse2 :: NatM a -> NatM a -> NatM a
if_sse2 sse2 x87 = do
b <- sse2Enabled
if b then sse2 else x87
cmmTopCodeGen
:: RawCmmDecl
-> NatM [NatCmmDecl (Alignment, CmmStatics) Instr]
cmmTopCodeGen (CmmProc info lab live graph) = do
let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
picBaseMb <- getPicBaseMaybeNat
dflags <- getDynFlags
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
tops = proc : concat statics
os = platformOS $ targetPlatform dflags
case picBaseMb of
Just picBase -> initializePicBase_x86 ArchX86 os picBase tops
Nothing -> return tops
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec (1, dat)] -- no translation, we just use CmmStatic
basicBlockCodeGen
:: CmmBlock
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl (Alignment, CmmStatics) Instr])
basicBlockCodeGen block = do
let (CmmEntry id, nodes, tail) = blockSplit block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
let
(top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
return (BasicBlock id top : other_blocks, statics)
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
is32Bit <- is32BitPlatform
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode size reg src
| is32Bit && isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode size reg src
where ty = cmmRegType dflags reg
size = cmmTypeSize ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode size addr src
| is32Bit && isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode size addr src
where ty = cmmExprType dflags src
size = cmmTypeSize ty
CmmUnsafeForeignCall target result_regs args
-> genCCall is32Bit target result_regs args
CmmBranch id -> genBranch id
CmmCondBranch arg true false -> do b1 <- genCondJump true arg
b2 <- genBranch false
return (b1 `appOL` b2)
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg
, cml_args_regs = gregs } -> do
dflags <- getDynFlags
genJump arg (jumpRegs dflags gregs)
_ ->
panic "stmtToInstrs: statement should have been cps'd away"
jumpRegs :: DynFlags -> [GlobalReg] -> [Reg]
jumpRegs dflags gregs = [ RegReal r | Just r <- map (globalRegMaybe platform) gregs ]
where platform = targetPlatform dflags
--------------------------------------------------------------------------------
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal yields the insns in the correct order.
--
type InstrBlock
= OrdList Instr
-- | Condition codes passed up the tree.
--
data CondCode
= CondCode Bool Cond InstrBlock
-- | a.k.a "Register64"
-- Reg is the lower 32-bit temporary which contains the result.
-- Use getHiVRegFromLo to find the other VRegUnique.
--
-- Rules of this simplified insn selection game are therefore that
-- the returned Reg may be modified
--
data ChildCode64
= ChildCode64
InstrBlock
Reg
-- | Register's passed up the tree. If the stix code forces the register
-- to live in a pre-decided machine register, it comes out as @Fixed@;
-- otherwise, it comes out as @Any@, and the parent can decide which
-- register to put it in.
--
data Register
= Fixed Size Reg InstrBlock
| Any Size (Reg -> InstrBlock)
swizzleRegisterRep :: Register -> Size -> Register
swizzleRegisterRep (Fixed _ reg code) size = Fixed size reg code
swizzleRegisterRep (Any _ codefn) size = Any size codefn
-- | Grab the Reg for a CmmReg
getRegisterReg :: Platform -> Bool -> CmmReg -> Reg
getRegisterReg _ use_sse2 (CmmLocal (LocalReg u pk))
= let sz = cmmTypeSize pk in
if isFloatSize sz && not use_sse2
then RegVirtual (mkVirtualReg u FF80)
else RegVirtual (mkVirtualReg u sz)
getRegisterReg platform _ (CmmGlobal mid)
= case globalRegMaybe platform mid of
Just reg -> RegReal $ reg
Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
-- By this stage, the only MagicIds remaining should be the
-- ones which map to a real machine register on this
-- platform. Hence ...
-- | Memory addressing modes passed up the tree.
data Amode
= Amode AddrMode InstrBlock
{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
-- | Check whether an integer will fit in 32 bits.
-- A CmmInt is intended to be truncated to the appropriate
-- number of bits, so here we truncate it to Int64. This is
-- important because e.g. -1 as a CmmInt might be either
-- -1 or 18446744073709551615.
--
is32BitInteger :: Integer -> Bool
is32BitInteger i = i64 <= 0x7fffffff && i64 >= -0x80000000
where i64 = fromIntegral i :: Int64
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = mkAsmTempLabel (getUnique blockid)
-- -----------------------------------------------------------------------------
-- General things for putting together code sequences
-- Expand CmmRegOff. ToDo: should we do it this way around, or convert
-- CmmExprs into CmmRegOff?
mangleIndexTree :: DynFlags -> CmmReg -> Int -> CmmExpr
mangleIndexTree dflags reg off
= CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)]
where width = typeWidth (cmmRegType dflags reg)
-- | The dual to getAnyReg: compute an expression into a register, but
-- we don't mind which one it is.
getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
getSomeReg expr = do
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed _ reg code ->
return (reg, code)
assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_I64Code addrTree valueTree = do
Amode addr addr_code <- getAmode addrTree
ChildCode64 vcode rlo <- iselExpr64 valueTree
let
rhi = getHiVRegFromLo rlo
-- Little-endian store
mov_lo = MOV II32 (OpReg rlo) (OpAddr addr)
mov_hi = MOV II32 (OpReg rhi) (OpAddr (fromJust (addrOffset addr 4)))
return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do
ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
let
r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32
r_dst_hi = getHiVRegFromLo r_dst_lo
r_src_hi = getHiVRegFromLo r_src_lo
mov_lo = MOV II32 (OpReg r_src_lo) (OpReg r_dst_lo)
mov_hi = MOV II32 (OpReg r_src_hi) (OpReg r_dst_hi)
return (
vcode `snocOL` mov_lo `snocOL` mov_hi
)
assignReg_I64Code _ _
= panic "assignReg_I64Code(i386): invalid lvalue"
iselExpr64 :: CmmExpr -> NatM ChildCode64
iselExpr64 (CmmLit (CmmInt i _)) = do
(rlo,rhi) <- getNewRegPairNat II32
let
r = fromIntegral (fromIntegral i :: Word32)
q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32)
code = toOL [
MOV II32 (OpImm (ImmInteger r)) (OpReg rlo),
MOV II32 (OpImm (ImmInteger q)) (OpReg rhi)
]
return (ChildCode64 code rlo)
iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do
Amode addr addr_code <- getAmode addrTree
(rlo,rhi) <- getNewRegPairNat II32
let
mov_lo = MOV II32 (OpAddr addr) (OpReg rlo)
mov_hi = MOV II32 (OpAddr (fromJust (addrOffset addr 4))) (OpReg rhi)
return (
ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
)
iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty
= return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32))
-- we handle addition, but rather badly
iselExpr64 (CmmMachOp (MO_Add _) [e1, CmmLit (CmmInt i _)]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
(rlo,rhi) <- getNewRegPairNat II32
let
r = fromIntegral (fromIntegral i :: Word32)
q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32)
r1hi = getHiVRegFromLo r1lo
code = code1 `appOL`
toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
ADD II32 (OpImm (ImmInteger r)) (OpReg rlo),
MOV II32 (OpReg r1hi) (OpReg rhi),
ADC II32 (OpImm (ImmInteger q)) (OpReg rhi) ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
ADD II32 (OpReg r2lo) (OpReg rlo),
MOV II32 (OpReg r1hi) (OpReg rhi),
ADC II32 (OpReg r2hi) (OpReg rhi) ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_UU_Conv _ W64) [expr]) = do
fn <- getAnyReg expr
r_dst_lo <- getNewRegNat II32
let r_dst_hi = getHiVRegFromLo r_dst_lo
code = fn r_dst_lo
return (
ChildCode64 (code `snocOL`
MOV II32 (OpImm (ImmInt 0)) (OpReg r_dst_hi))
r_dst_lo
)
iselExpr64 expr
= pprPanic "iselExpr64(i386)" (ppr expr)
--------------------------------------------------------------------------------
getRegister :: CmmExpr -> NatM Register
getRegister e = do dflags <- getDynFlags
is32Bit <- is32BitPlatform
getRegister' dflags is32Bit e
getRegister' :: DynFlags -> Bool -> CmmExpr -> NatM Register
getRegister' dflags is32Bit (CmmReg reg)
= case reg of
CmmGlobal PicBaseReg
| is32Bit ->
-- on x86_64, we have %rip for PicBaseReg, but it's not
-- a full-featured register, it can only be used for
-- rip-relative addressing.
do reg' <- getPicBaseNat (archWordSize is32Bit)
return (Fixed (archWordSize is32Bit) reg' nilOL)
_ ->
do use_sse2 <- sse2Enabled
let
sz = cmmTypeSize (cmmRegType dflags reg)
size | not use_sse2 && isFloatSize sz = FF80
| otherwise = sz
--
let platform = targetPlatform dflags
return (Fixed size (getRegisterReg platform use_sse2 reg) nilOL)
getRegister' dflags is32Bit (CmmRegOff r n)
= getRegister' dflags is32Bit $ mangleIndexTree dflags r n
-- for 32-bit architectuers, support some 64 -> 32 bit conversions:
-- TO_W_(x), TO_W_(x >> 32)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32) [x])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32) [x])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' _ _ (CmmLit lit@(CmmFloat f w)) =
if_sse2 float_const_sse2 float_const_x87
where
float_const_sse2
| f == 0.0 = do
let
size = floatSize w
code dst = unitOL (XOR size (OpReg dst) (OpReg dst))
-- I don't know why there are xorpd, xorps, and pxor instructions.
-- They all appear to do the same thing --SDM
return (Any size code)
| otherwise = do
Amode addr code <- memConstant (widthInBytes w) lit
loadFloatAmode True w addr code
float_const_x87 = case w of
W64
| f == 0.0 ->
let code dst = unitOL (GLDZ dst)
in return (Any FF80 code)
| f == 1.0 ->
let code dst = unitOL (GLD1 dst)
in return (Any FF80 code)
_otherwise -> do
Amode addr code <- memConstant (widthInBytes w) lit
loadFloatAmode False w addr code
-- catch simple cases of zero- or sign-extended load
getRegister' _ _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVZxL II8) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_SS_Conv W8 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVSxL II8) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVZxL II16) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVSxL II16) addr
return (Any II32 code)
-- catch simple cases of zero- or sign-extended load
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVZxL II8) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W8 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II8) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVZxL II16) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II16) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOV II32) addr -- 32-bit loads zero-extend
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II32) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
CmmLit displacement])
| not is32Bit = do
return $ Any II64 (\dst -> unitOL $
LEA II64 (OpAddr (ripRel (litToImm displacement))) (OpReg dst))
getRegister' dflags is32Bit (CmmMachOp mop [x]) = do -- unary MachOps
sse2 <- sse2Enabled
case mop of
MO_F_Neg w
| sse2 -> sse2NegCode w x
| otherwise -> trivialUFCode FF80 (GNEG FF80) x
MO_S_Neg w -> triv_ucode NEGI (intSize w)
MO_Not w -> triv_ucode NOT (intSize w)
-- Nop conversions
MO_UU_Conv W32 W8 -> toI8Reg W32 x
MO_SS_Conv W32 W8 -> toI8Reg W32 x
MO_UU_Conv W16 W8 -> toI8Reg W16 x
MO_SS_Conv W16 W8 -> toI8Reg W16 x
MO_UU_Conv W32 W16 -> toI16Reg W32 x
MO_SS_Conv W32 W16 -> toI16Reg W32 x
MO_UU_Conv W64 W32 | not is32Bit -> conversionNop II64 x
MO_SS_Conv W64 W32 | not is32Bit -> conversionNop II64 x
MO_UU_Conv W64 W16 | not is32Bit -> toI16Reg W64 x
MO_SS_Conv W64 W16 | not is32Bit -> toI16Reg W64 x
MO_UU_Conv W64 W8 | not is32Bit -> toI8Reg W64 x
MO_SS_Conv W64 W8 | not is32Bit -> toI8Reg W64 x
MO_UU_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x
MO_SS_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x
-- widenings
MO_UU_Conv W8 W32 -> integerExtend W8 W32 MOVZxL x
MO_UU_Conv W16 W32 -> integerExtend W16 W32 MOVZxL x
MO_UU_Conv W8 W16 -> integerExtend W8 W16 MOVZxL x
MO_SS_Conv W8 W32 -> integerExtend W8 W32 MOVSxL x
MO_SS_Conv W16 W32 -> integerExtend W16 W32 MOVSxL x
MO_SS_Conv W8 W16 -> integerExtend W8 W16 MOVSxL x
MO_UU_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVZxL x
MO_UU_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVZxL x
MO_UU_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVZxL x
MO_SS_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVSxL x
MO_SS_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVSxL x
MO_SS_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVSxL x
-- for 32-to-64 bit zero extension, amd64 uses an ordinary movl.
-- However, we don't want the register allocator to throw it
-- away as an unnecessary reg-to-reg move, so we keep it in
-- the form of a movzl and print it as a movl later.
MO_FF_Conv W32 W64
| sse2 -> coerceFP2FP W64 x
| otherwise -> conversionNop FF80 x
MO_FF_Conv W64 W32 -> coerceFP2FP W32 x
MO_FS_Conv from to -> coerceFP2Int from to x
MO_SF_Conv from to -> coerceInt2FP from to x
MO_V_Insert {} -> needLlvm
MO_V_Extract {} -> needLlvm
MO_V_Add {} -> needLlvm
MO_V_Sub {} -> needLlvm
MO_V_Mul {} -> needLlvm
MO_VS_Quot {} -> needLlvm
MO_VS_Rem {} -> needLlvm
MO_VS_Neg {} -> needLlvm
MO_VU_Quot {} -> needLlvm
MO_VU_Rem {} -> needLlvm
MO_VF_Insert {} -> needLlvm
MO_VF_Extract {} -> needLlvm
MO_VF_Add {} -> needLlvm
MO_VF_Sub {} -> needLlvm
MO_VF_Mul {} -> needLlvm
MO_VF_Quot {} -> needLlvm
MO_VF_Neg {} -> needLlvm
_other -> pprPanic "getRegister" (pprMachOp mop)
where
triv_ucode :: (Size -> Operand -> Instr) -> Size -> NatM Register
triv_ucode instr size = trivialUCode size (instr size) x
-- signed or unsigned extension.
integerExtend :: Width -> Width
-> (Size -> Operand -> Operand -> Instr)
-> CmmExpr -> NatM Register
integerExtend from to instr expr = do
(reg,e_code) <- if from == W8 then getByteReg expr
else getSomeReg expr
let
code dst =
e_code `snocOL`
instr (intSize from) (OpReg reg) (OpReg dst)
return (Any (intSize to) code)
toI8Reg :: Width -> CmmExpr -> NatM Register
toI8Reg new_rep expr
= do codefn <- getAnyReg expr
return (Any (intSize new_rep) codefn)
-- HACK: use getAnyReg to get a byte-addressable register.
-- If the source was a Fixed register, this will add the
-- mov instruction to put it into the desired destination.
-- We're assuming that the destination won't be a fixed
-- non-byte-addressable register; it won't be, because all
-- fixed registers are word-sized.
toI16Reg = toI8Reg -- for now
conversionNop :: Size -> CmmExpr -> NatM Register
conversionNop new_size expr
= do e_code <- getRegister' dflags is32Bit expr
return (swizzleRegisterRep e_code new_size)
getRegister' _ is32Bit (CmmMachOp mop [x, y]) = do -- dyadic MachOps
sse2 <- sse2Enabled
case mop of
MO_F_Eq _ -> condFltReg is32Bit EQQ x y
MO_F_Ne _ -> condFltReg is32Bit NE x y
MO_F_Gt _ -> condFltReg is32Bit GTT x y
MO_F_Ge _ -> condFltReg is32Bit GE x y
MO_F_Lt _ -> condFltReg is32Bit LTT x y
MO_F_Le _ -> condFltReg is32Bit LE x y
MO_Eq _ -> condIntReg EQQ x y
MO_Ne _ -> condIntReg NE x y
MO_S_Gt _ -> condIntReg GTT x y
MO_S_Ge _ -> condIntReg GE x y
MO_S_Lt _ -> condIntReg LTT x y
MO_S_Le _ -> condIntReg LE x y
MO_U_Gt _ -> condIntReg GU x y
MO_U_Ge _ -> condIntReg GEU x y
MO_U_Lt _ -> condIntReg LU x y
MO_U_Le _ -> condIntReg LEU x y
MO_F_Add w | sse2 -> trivialFCode_sse2 w ADD x y
| otherwise -> trivialFCode_x87 GADD x y
MO_F_Sub w | sse2 -> trivialFCode_sse2 w SUB x y
| otherwise -> trivialFCode_x87 GSUB x y
MO_F_Quot w | sse2 -> trivialFCode_sse2 w FDIV x y
| otherwise -> trivialFCode_x87 GDIV x y
MO_F_Mul w | sse2 -> trivialFCode_sse2 w MUL x y
| otherwise -> trivialFCode_x87 GMUL x y
MO_Add rep -> add_code rep x y
MO_Sub rep -> sub_code rep x y
MO_S_Quot rep -> div_code rep True True x y
MO_S_Rem rep -> div_code rep True False x y
MO_U_Quot rep -> div_code rep False True x y
MO_U_Rem rep -> div_code rep False False x y
MO_S_MulMayOflo rep -> imulMayOflo rep x y
MO_Mul rep -> triv_op rep IMUL
MO_And rep -> triv_op rep AND
MO_Or rep -> triv_op rep OR
MO_Xor rep -> triv_op rep XOR
{- Shift ops on x86s have constraints on their source, it
either has to be Imm, CL or 1
=> trivialCode is not restrictive enough (sigh.)
-}
MO_Shl rep -> shift_code rep SHL x y {-False-}
MO_U_Shr rep -> shift_code rep SHR x y {-False-}
MO_S_Shr rep -> shift_code rep SAR x y {-False-}
MO_V_Insert {} -> needLlvm
MO_V_Extract {} -> needLlvm
MO_V_Add {} -> needLlvm
MO_V_Sub {} -> needLlvm
MO_V_Mul {} -> needLlvm
MO_VS_Quot {} -> needLlvm
MO_VS_Rem {} -> needLlvm
MO_VS_Neg {} -> needLlvm
MO_VF_Insert {} -> needLlvm
MO_VF_Extract {} -> needLlvm
MO_VF_Add {} -> needLlvm
MO_VF_Sub {} -> needLlvm
MO_VF_Mul {} -> needLlvm
MO_VF_Quot {} -> needLlvm
MO_VF_Neg {} -> needLlvm
_other -> pprPanic "getRegister(x86) - binary CmmMachOp (1)" (pprMachOp mop)
where
--------------------
triv_op width instr = trivialCode width op (Just op) x y
where op = instr (intSize width)
imulMayOflo :: Width -> CmmExpr -> CmmExpr -> NatM Register
imulMayOflo rep a b = do
(a_reg, a_code) <- getNonClobberedReg a
b_code <- getAnyReg b
let
shift_amt = case rep of
W32 -> 31
W64 -> 63
_ -> panic "shift_amt"
size = intSize rep
code = a_code `appOL` b_code eax `appOL`
toOL [
IMUL2 size (OpReg a_reg), -- result in %edx:%eax
SAR size (OpImm (ImmInt shift_amt)) (OpReg eax),
-- sign extend lower part
SUB size (OpReg edx) (OpReg eax)
-- compare against upper
-- eax==0 if high part == sign extended low part
]
return (Fixed size eax code)
--------------------
shift_code :: Width
-> (Size -> Operand -> Operand -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
{- Case1: shift length as immediate -}
shift_code width instr x (CmmLit lit) = do
x_code <- getAnyReg x
let
size = intSize width
code dst
= x_code dst `snocOL`
instr size (OpImm (litToImm lit)) (OpReg dst)
return (Any size code)
{- Case2: shift length is complex (non-immediate)
* y must go in %ecx.
* we cannot do y first *and* put its result in %ecx, because
%ecx might be clobbered by x.
* if we do y second, then x cannot be
in a clobbered reg. Also, we cannot clobber x's reg
with the instruction itself.
* so we can either:
- do y first, put its result in a fresh tmp, then copy it to %ecx later
- do y second and put its result into %ecx. x gets placed in a fresh
tmp. This is likely to be better, because the reg alloc can
eliminate this reg->reg move here (it won't eliminate the other one,
because the move is into the fixed %ecx).
-}
shift_code width instr x y{-amount-} = do
x_code <- getAnyReg x
let size = intSize width
tmp <- getNewRegNat size
y_code <- getAnyReg y
let
code = x_code tmp `appOL`
y_code ecx `snocOL`
instr size (OpReg ecx) (OpReg tmp)
return (Fixed size tmp code)
--------------------
add_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
add_code rep x (CmmLit (CmmInt y _))
| is32BitInteger y = add_int rep x y
add_code rep x y = trivialCode rep (ADD size) (Just (ADD size)) x y
where size = intSize rep
--------------------
sub_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
sub_code rep x (CmmLit (CmmInt y _))
| is32BitInteger (-y) = add_int rep x (-y)
sub_code rep x y = trivialCode rep (SUB (intSize rep)) Nothing x y
-- our three-operand add instruction:
add_int width x y = do
(x_reg, x_code) <- getSomeReg x
let
size = intSize width
imm = ImmInt (fromInteger y)
code dst
= x_code `snocOL`
LEA size
(OpAddr (AddrBaseIndex (EABaseReg x_reg) EAIndexNone imm))
(OpReg dst)
--
return (Any size code)
----------------------
div_code width signed quotient x y = do
(y_op, y_code) <- getRegOrMem y -- cannot be clobbered
x_code <- getAnyReg x
let
size = intSize width
widen | signed = CLTD size
| otherwise = XOR size (OpReg edx) (OpReg edx)
instr | signed = IDIV
| otherwise = DIV
code = y_code `appOL`
x_code eax `appOL`
toOL [widen, instr size y_op]
result | quotient = eax
| otherwise = edx
return (Fixed size result code)
getRegister' _ _ (CmmLoad mem pk)
| isFloatType pk
= do
Amode addr mem_code <- getAmode mem
use_sse2 <- sse2Enabled
loadFloatAmode use_sse2 (typeWidth pk) addr mem_code
getRegister' _ is32Bit (CmmLoad mem pk)
| is32Bit && not (isWord64 pk)
= do
code <- intLoadCode instr mem
return (Any size code)
where
width = typeWidth pk
size = intSize width
instr = case width of
W8 -> MOVZxL II8
_other -> MOV size
-- We always zero-extend 8-bit loads, if we
-- can't think of anything better. This is because
-- we can't guarantee access to an 8-bit variant of every register
-- (esi and edi don't have 8-bit variants), so to make things
-- simpler we do our 8-bit arithmetic with full 32-bit registers.
-- Simpler memory load code on x86_64
getRegister' _ is32Bit (CmmLoad mem pk)
| not is32Bit
= do
code <- intLoadCode (MOV size) mem
return (Any size code)
where size = intSize $ typeWidth pk
getRegister' _ is32Bit (CmmLit (CmmInt 0 width))
= let
size = intSize width
-- x86_64: 32-bit xor is one byte shorter, and zero-extends to 64 bits
size1 = if is32Bit then size
else case size of
II64 -> II32
_ -> size
code dst
= unitOL (XOR size1 (OpReg dst) (OpReg dst))
in
return (Any size code)
-- optimisation for loading small literals on x86_64: take advantage
-- of the automatic zero-extension from 32 to 64 bits, because the 32-bit
-- instruction forms are shorter.
getRegister' dflags is32Bit (CmmLit lit)
| not is32Bit, isWord64 (cmmLitType dflags lit), not (isBigLit lit)
= let
imm = litToImm lit
code dst = unitOL (MOV II32 (OpImm imm) (OpReg dst))
in
return (Any II64 code)
where
isBigLit (CmmInt i _) = i < 0 || i > 0xffffffff
isBigLit _ = False
-- note1: not the same as (not.is32BitLit), because that checks for
-- signed literals that fit in 32 bits, but we want unsigned
-- literals here.
-- note2: all labels are small, because we're assuming the
-- small memory model (see gcc docs, -mcmodel=small).
getRegister' dflags _ (CmmLit lit)
= do let size = cmmTypeSize (cmmLitType dflags lit)
imm = litToImm lit
code dst = unitOL (MOV size (OpImm imm) (OpReg dst))
return (Any size code)
getRegister' _ _ other
| isVecExpr other = needLlvm
| otherwise = pprPanic "getRegister(x86)" (ppr other)
intLoadCode :: (Operand -> Operand -> Instr) -> CmmExpr
-> NatM (Reg -> InstrBlock)
intLoadCode instr mem = do
Amode src mem_code <- getAmode mem
return (\dst -> mem_code `snocOL` instr (OpAddr src) (OpReg dst))
-- Compute an expression into *any* register, adding the appropriate
-- move instruction if necessary.
getAnyReg :: CmmExpr -> NatM (Reg -> InstrBlock)
getAnyReg expr = do
r <- getRegister expr
anyReg r
anyReg :: Register -> NatM (Reg -> InstrBlock)
anyReg (Any _ code) = return code
anyReg (Fixed rep reg fcode) = return (\dst -> fcode `snocOL` reg2reg rep reg dst)
-- A bit like getSomeReg, but we want a reg that can be byte-addressed.
-- Fixed registers might not be byte-addressable, so we make sure we've
-- got a temporary, inserting an extra reg copy if necessary.
getByteReg :: CmmExpr -> NatM (Reg, InstrBlock)
getByteReg expr = do
is32Bit <- is32BitPlatform
if is32Bit
then do r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed rep reg code
| isVirtualReg reg -> return (reg,code)
| otherwise -> do
tmp <- getNewRegNat rep
return (tmp, code `snocOL` reg2reg rep reg tmp)
-- ToDo: could optimise slightly by checking for
-- byte-addressable real registers, but that will
-- happen very rarely if at all.
else getSomeReg expr -- all regs are byte-addressable on x86_64
-- Another variant: this time we want the result in a register that cannot
-- be modified by code to evaluate an arbitrary expression.
getNonClobberedReg :: CmmExpr -> NatM (Reg, InstrBlock)
getNonClobberedReg expr = do
dflags <- getDynFlags
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed rep reg code
-- only certain regs can be clobbered
| reg `elem` instrClobberedRegs (targetPlatform dflags)
-> do
tmp <- getNewRegNat rep
return (tmp, code `snocOL` reg2reg rep reg tmp)
| otherwise ->
return (reg, code)
reg2reg :: Size -> Reg -> Reg -> Instr
reg2reg size src dst
| size == FF80 = GMOV src dst
| otherwise = MOV size (OpReg src) (OpReg dst)
--------------------------------------------------------------------------------
getAmode :: CmmExpr -> NatM Amode
getAmode e = do is32Bit <- is32BitPlatform
getAmode' is32Bit e
getAmode' :: Bool -> CmmExpr -> NatM Amode
getAmode' _ (CmmRegOff r n) = do dflags <- getDynFlags
getAmode $ mangleIndexTree dflags r n
getAmode' is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
CmmLit displacement])
| not is32Bit
= return $ Amode (ripRel (litToImm displacement)) nilOL
-- This is all just ridiculous, since it carefully undoes
-- what mangleIndexTree has just done.
getAmode' is32Bit (CmmMachOp (MO_Sub _rep) [x, CmmLit lit@(CmmInt i _)])
| is32BitLit is32Bit lit
-- ASSERT(rep == II32)???
= do (x_reg, x_code) <- getSomeReg x
let off = ImmInt (-(fromInteger i))
return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
getAmode' is32Bit (CmmMachOp (MO_Add _rep) [x, CmmLit lit])
| is32BitLit is32Bit lit
-- ASSERT(rep == II32)???
= do (x_reg, x_code) <- getSomeReg x
let off = litToImm lit
return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
-- Turn (lit1 << n + lit2) into (lit2 + lit1 << n) so it will be
-- recognised by the next rule.
getAmode' is32Bit (CmmMachOp (MO_Add rep) [a@(CmmMachOp (MO_Shl _) _),
b@(CmmLit _)])
= getAmode' is32Bit (CmmMachOp (MO_Add rep) [b,a])
getAmode' _ (CmmMachOp (MO_Add _) [x, CmmMachOp (MO_Shl _)
[y, CmmLit (CmmInt shift _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
= x86_complex_amode x y shift 0
getAmode' _ (CmmMachOp (MO_Add _)
[x, CmmMachOp (MO_Add _)
[CmmMachOp (MO_Shl _) [y, CmmLit (CmmInt shift _)],
CmmLit (CmmInt offset _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
&& is32BitInteger offset
= x86_complex_amode x y shift offset
getAmode' _ (CmmMachOp (MO_Add _) [x,y])
= x86_complex_amode x y 0 0
getAmode' is32Bit (CmmLit lit) | is32BitLit is32Bit lit
= return (Amode (ImmAddr (litToImm lit) 0) nilOL)
getAmode' _ expr = do
(reg,code) <- getSomeReg expr
return (Amode (AddrBaseIndex (EABaseReg reg) EAIndexNone (ImmInt 0)) code)
x86_complex_amode :: CmmExpr -> CmmExpr -> Integer -> Integer -> NatM Amode
x86_complex_amode base index shift offset
= do (x_reg, x_code) <- getNonClobberedReg base
-- x must be in a temp, because it has to stay live over y_code
-- we could compre x_reg and y_reg and do something better here...
(y_reg, y_code) <- getSomeReg index
let
code = x_code `appOL` y_code
base = case shift of 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8;
n -> panic $ "x86_complex_amode: unhandled shift! (" ++ show n ++ ")"
return (Amode (AddrBaseIndex (EABaseReg x_reg) (EAIndex y_reg base) (ImmInt (fromIntegral offset)))
code)
-- -----------------------------------------------------------------------------
-- getOperand: sometimes any operand will do.
-- getNonClobberedOperand: the value of the operand will remain valid across
-- the computation of an arbitrary expression, unless the expression
-- is computed directly into a register which the operand refers to
-- (see trivialCode where this function is used for an example).
getNonClobberedOperand :: CmmExpr -> NatM (Operand, InstrBlock)
getNonClobberedOperand (CmmLit lit) = do
use_sse2 <- sse2Enabled
if use_sse2 && isSuitableFloatingPointLit lit
then do
let CmmFloat _ w = lit
Amode addr code <- memConstant (widthInBytes w) lit
return (OpAddr addr, code)
else do
is32Bit <- is32BitPlatform
dflags <- getDynFlags
if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit))
then return (OpImm (litToImm lit), nilOL)
else getNonClobberedOperand_generic (CmmLit lit)
getNonClobberedOperand (CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2)
&& (if is32Bit then not (isWord64 pk) else True)
then do
dflags <- getDynFlags
let platform = targetPlatform dflags
Amode src mem_code <- getAmode mem
(src',save_code) <-
if (amodeCouldBeClobbered platform src)
then do
tmp <- getNewRegNat (archWordSize is32Bit)
return (AddrBaseIndex (EABaseReg tmp) EAIndexNone (ImmInt 0),
unitOL (LEA (archWordSize is32Bit) (OpAddr src) (OpReg tmp)))
else
return (src, nilOL)
return (OpAddr src', mem_code `appOL` save_code)
else do
getNonClobberedOperand_generic (CmmLoad mem pk)
getNonClobberedOperand e = getNonClobberedOperand_generic e
getNonClobberedOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock)
getNonClobberedOperand_generic e = do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
amodeCouldBeClobbered :: Platform -> AddrMode -> Bool
amodeCouldBeClobbered platform amode = any (regClobbered platform) (addrModeRegs amode)
regClobbered :: Platform -> Reg -> Bool
regClobbered platform (RegReal (RealRegSingle rr)) = isFastTrue (freeReg platform rr)
regClobbered _ _ = False
-- getOperand: the operand is not required to remain valid across the
-- computation of an arbitrary expression.
getOperand :: CmmExpr -> NatM (Operand, InstrBlock)
getOperand (CmmLit lit) = do
use_sse2 <- sse2Enabled
if (use_sse2 && isSuitableFloatingPointLit lit)
then do
let CmmFloat _ w = lit
Amode addr code <- memConstant (widthInBytes w) lit
return (OpAddr addr, code)
else do
is32Bit <- is32BitPlatform
dflags <- getDynFlags
if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit))
then return (OpImm (litToImm lit), nilOL)
else getOperand_generic (CmmLit lit)
getOperand (CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True)
then do
Amode src mem_code <- getAmode mem
return (OpAddr src, mem_code)
else
getOperand_generic (CmmLoad mem pk)
getOperand e = getOperand_generic e
getOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock)
getOperand_generic e = do
(reg, code) <- getSomeReg e
return (OpReg reg, code)
isOperand :: Bool -> CmmExpr -> Bool
isOperand _ (CmmLoad _ _) = True
isOperand is32Bit (CmmLit lit) = is32BitLit is32Bit lit
|| isSuitableFloatingPointLit lit
isOperand _ _ = False
memConstant :: Int -> CmmLit -> NatM Amode
memConstant align lit = do
lbl <- getNewLabelNat
dflags <- getDynFlags
(addr, addr_code) <- if target32Bit (targetPlatform dflags)
then do dynRef <- cmmMakeDynamicReference
dflags
DataReference
lbl
Amode addr addr_code <- getAmode dynRef
return (addr, addr_code)
else return (ripRel (ImmCLbl lbl), nilOL)
let code =
LDATA ReadOnlyData (align, Statics lbl [CmmStaticLit lit])
`consOL` addr_code
return (Amode addr code)
loadFloatAmode :: Bool -> Width -> AddrMode -> InstrBlock -> NatM Register
loadFloatAmode use_sse2 w addr addr_code = do
let size = floatSize w
code dst = addr_code `snocOL`
if use_sse2
then MOV size (OpAddr addr) (OpReg dst)
else GLD size addr dst
return (Any (if use_sse2 then size else FF80) code)
-- if we want a floating-point literal as an operand, we can
-- use it directly from memory. However, if the literal is
-- zero, we're better off generating it into a register using
-- xor.
isSuitableFloatingPointLit :: CmmLit -> Bool
isSuitableFloatingPointLit (CmmFloat f _) = f /= 0.0
isSuitableFloatingPointLit _ = False
getRegOrMem :: CmmExpr -> NatM (Operand, InstrBlock)
getRegOrMem e@(CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True)
then do
Amode src mem_code <- getAmode mem
return (OpAddr src, mem_code)
else do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
getRegOrMem e = do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
is32BitLit :: Bool -> CmmLit -> Bool
is32BitLit is32Bit (CmmInt i W64)
| not is32Bit
= -- assume that labels are in the range 0-2^31-1: this assumes the
-- small memory model (see gcc docs, -mcmodel=small).
is32BitInteger i
is32BitLit _ _ = True
-- Set up a condition code for a conditional branch.
getCondCode :: CmmExpr -> NatM CondCode
-- yes, they really do seem to want exactly the same!
getCondCode (CmmMachOp mop [x, y])
=
case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
MO_F_Lt W32 -> condFltCode LTT x y
MO_F_Le W32 -> condFltCode LE x y
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode LTT x y
MO_F_Le W64 -> condFltCode LE x y
MO_Eq _ -> condIntCode EQQ x y
MO_Ne _ -> condIntCode NE x y
MO_S_Gt _ -> condIntCode GTT x y
MO_S_Ge _ -> condIntCode GE x y
MO_S_Lt _ -> condIntCode LTT x y
MO_S_Le _ -> condIntCode LE x y
MO_U_Gt _ -> condIntCode GU x y
MO_U_Ge _ -> condIntCode GEU x y
MO_U_Lt _ -> condIntCode LU x y
MO_U_Le _ -> condIntCode LEU x y
_other -> pprPanic "getCondCode(x86,x86_64)" (ppr (CmmMachOp mop [x,y]))
getCondCode other = pprPanic "getCondCode(2)(x86,x86_64)" (ppr other)
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condIntCode cond x y = do is32Bit <- is32BitPlatform
condIntCode' is32Bit cond x y
condIntCode' :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM CondCode
-- memory vs immediate
condIntCode' is32Bit cond (CmmLoad x pk) (CmmLit lit)
| is32BitLit is32Bit lit = do
Amode x_addr x_code <- getAmode x
let
imm = litToImm lit
code = x_code `snocOL`
CMP (cmmTypeSize pk) (OpImm imm) (OpAddr x_addr)
--
return (CondCode False cond code)
-- anything vs zero, using a mask
-- TODO: Add some sanity checking!!!!
condIntCode' is32Bit cond (CmmMachOp (MO_And _) [x,o2]) (CmmLit (CmmInt 0 pk))
| (CmmLit lit@(CmmInt mask _)) <- o2, is32BitLit is32Bit lit
= do
(x_reg, x_code) <- getSomeReg x
let
code = x_code `snocOL`
TEST (intSize pk) (OpImm (ImmInteger mask)) (OpReg x_reg)
--
return (CondCode False cond code)
-- anything vs zero
condIntCode' _ cond x (CmmLit (CmmInt 0 pk)) = do
(x_reg, x_code) <- getSomeReg x
let
code = x_code `snocOL`
TEST (intSize pk) (OpReg x_reg) (OpReg x_reg)
--
return (CondCode False cond code)
-- anything vs operand
condIntCode' is32Bit cond x y
| isOperand is32Bit y = do
dflags <- getDynFlags
(x_reg, x_code) <- getNonClobberedReg x
(y_op, y_code) <- getOperand y
let
code = x_code `appOL` y_code `snocOL`
CMP (cmmTypeSize (cmmExprType dflags x)) y_op (OpReg x_reg)
return (CondCode False cond code)
-- operand vs. anything: invert the comparison so that we can use a
-- single comparison instruction.
| isOperand is32Bit x
, Just revcond <- maybeFlipCond cond = do
dflags <- getDynFlags
(y_reg, y_code) <- getNonClobberedReg y
(x_op, x_code) <- getOperand x
let
code = y_code `appOL` x_code `snocOL`
CMP (cmmTypeSize (cmmExprType dflags x)) x_op (OpReg y_reg)
return (CondCode False revcond code)
-- anything vs anything
condIntCode' _ cond x y = do
dflags <- getDynFlags
(y_reg, y_code) <- getNonClobberedReg y
(x_op, x_code) <- getRegOrMem x
let
code = y_code `appOL`
x_code `snocOL`
CMP (cmmTypeSize (cmmExprType dflags x)) (OpReg y_reg) x_op
return (CondCode False cond code)
--------------------------------------------------------------------------------
condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condFltCode cond x y
= if_sse2 condFltCode_sse2 condFltCode_x87
where
condFltCode_x87
= ASSERT(cond `elem` ([EQQ, NE, LE, LTT, GE, GTT])) do
(x_reg, x_code) <- getNonClobberedReg x
(y_reg, y_code) <- getSomeReg y
let
code = x_code `appOL` y_code `snocOL`
GCMP cond x_reg y_reg
-- The GCMP insn does the test and sets the zero flag if comparable
-- and true. Hence we always supply EQQ as the condition to test.
return (CondCode True EQQ code)
-- in the SSE2 comparison ops (ucomiss, ucomisd) the left arg may be
-- an operand, but the right must be a reg. We can probably do better
-- than this general case...
condFltCode_sse2 = do
dflags <- getDynFlags
(x_reg, x_code) <- getNonClobberedReg x
(y_op, y_code) <- getOperand y
let
code = x_code `appOL`
y_code `snocOL`
CMP (floatSize $ cmmExprWidth dflags x) y_op (OpReg x_reg)
-- NB(1): we need to use the unsigned comparison operators on the
-- result of this comparison.
return (CondCode True (condToUnsigned cond) code)
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_IntCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_FltCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_FltCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
-- integer assignment to memory
-- specific case of adding/subtracting an integer to a particular address.
-- ToDo: catch other cases where we can use an operation directly on a memory
-- address.
assignMem_IntCode pk addr (CmmMachOp op [CmmLoad addr2 _,
CmmLit (CmmInt i _)])
| addr == addr2, pk /= II64 || is32BitInteger i,
Just instr <- check op
= do Amode amode code_addr <- getAmode addr
let code = code_addr `snocOL`
instr pk (OpImm (ImmInt (fromIntegral i))) (OpAddr amode)
return code
where
check (MO_Add _) = Just ADD
check (MO_Sub _) = Just SUB
check _ = Nothing
-- ToDo: more?
-- general case
assignMem_IntCode pk addr src = do
is32Bit <- is32BitPlatform
Amode addr code_addr <- getAmode addr
(code_src, op_src) <- get_op_RI is32Bit src
let
code = code_src `appOL`
code_addr `snocOL`
MOV pk op_src (OpAddr addr)
-- NOTE: op_src is stable, so it will still be valid
-- after code_addr. This may involve the introduction
-- of an extra MOV to a temporary register, but we hope
-- the register allocator will get rid of it.
--
return code
where
get_op_RI :: Bool -> CmmExpr -> NatM (InstrBlock,Operand) -- code, operator
get_op_RI is32Bit (CmmLit lit) | is32BitLit is32Bit lit
= return (nilOL, OpImm (litToImm lit))
get_op_RI _ op
= do (reg,code) <- getNonClobberedReg op
return (code, OpReg reg)
-- Assign; dst is a reg, rhs is mem
assignReg_IntCode pk reg (CmmLoad src _) = do
load_code <- intLoadCode (MOV pk) src
dflags <- getDynFlags
let platform = targetPlatform dflags
return (load_code (getRegisterReg platform False{-no sse2-} reg))
-- dst is a reg, but src could be anything
assignReg_IntCode _ reg src = do
dflags <- getDynFlags
let platform = targetPlatform dflags
code <- getAnyReg src
return (code (getRegisterReg platform False{-no sse2-} reg))
-- Floating point assignment to memory
assignMem_FltCode pk addr src = do
(src_reg, src_code) <- getNonClobberedReg src
Amode addr addr_code <- getAmode addr
use_sse2 <- sse2Enabled
let
code = src_code `appOL`
addr_code `snocOL`
if use_sse2 then MOV pk (OpReg src_reg) (OpAddr addr)
else GST pk src_reg addr
return code
-- Floating point assignment to a register/temporary
assignReg_FltCode _ reg src = do
use_sse2 <- sse2Enabled
src_code <- getAnyReg src
dflags <- getDynFlags
let platform = targetPlatform dflags
return (src_code (getRegisterReg platform use_sse2 reg))
genJump :: CmmExpr{-the branch target-} -> [Reg] -> NatM InstrBlock
genJump (CmmLoad mem _) regs = do
Amode target code <- getAmode mem
return (code `snocOL` JMP (OpAddr target) regs)
genJump (CmmLit lit) regs = do
return (unitOL (JMP (OpImm (litToImm lit)) regs))
genJump expr regs = do
(reg,code) <- getSomeReg expr
return (code `snocOL` JMP (OpReg reg) regs)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
I386: First, we have to ensure that the condition
codes are set according to the supplied comparison operation.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump id bool = do
CondCode is_float cond cond_code <- getCondCode bool
use_sse2 <- sse2Enabled
if not is_float || not use_sse2
then
return (cond_code `snocOL` JXX cond id)
else do
lbl <- getBlockIdNat
-- see comment with condFltReg
let code = case cond of
NE -> or_unordered
GU -> plain_test
GEU -> plain_test
_ -> and_ordered
plain_test = unitOL (
JXX cond id
)
or_unordered = toOL [
JXX cond id,
JXX PARITY id
]
and_ordered = toOL [
JXX PARITY lbl,
JXX cond id,
JXX ALWAYS lbl,
NEWBLOCK lbl
]
return (cond_code `appOL` code)
-- -----------------------------------------------------------------------------
-- Generating C calls
-- Now the biggest nightmare---calls. Most of the nastiness is buried in
-- @get_arg@, which moves the arguments to the correct registers/stack
-- locations. Apart from that, the code is easy.
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
genCCall
:: Bool -- 32 bit platform?
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-- Unroll memcpy calls if the source and destination pointers are at
-- least DWORD aligned and the number of bytes to copy isn't too
-- large. Otherwise, call C's memcpy.
genCCall is32Bit (PrimTarget MO_Memcpy) _
[dst, src,
(CmmLit (CmmInt n _)),
(CmmLit (CmmInt align _))]
| n <= maxInlineSizeThreshold && align .&. 3 == 0 = do
code_dst <- getAnyReg dst
dst_r <- getNewRegNat size
code_src <- getAnyReg src
src_r <- getNewRegNat size
tmp_r <- getNewRegNat size
return $ code_dst dst_r `appOL` code_src src_r `appOL`
go dst_r src_r tmp_r n
where
size = if align .&. 4 /= 0 then II32 else (archWordSize is32Bit)
sizeBytes = fromIntegral (sizeInBytes size)
go :: Reg -> Reg -> Reg -> Integer -> OrdList Instr
go dst src tmp i
| i >= sizeBytes =
unitOL (MOV size (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV size (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - sizeBytes)
-- Deal with remaining bytes.
| i >= 4 = -- Will never happen on 32-bit
unitOL (MOV II32 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II32 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 4)
| i >= 2 =
unitOL (MOVZxL II16 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II16 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 2)
| i >= 1 =
unitOL (MOVZxL II8 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II8 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 1)
| otherwise = nilOL
where
src_addr = AddrBaseIndex (EABaseReg src) EAIndexNone
(ImmInteger (n - i))
dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone
(ImmInteger (n - i))
genCCall _ (PrimTarget MO_Memset) _
[dst,
CmmLit (CmmInt c _),
CmmLit (CmmInt n _),
CmmLit (CmmInt align _)]
| n <= maxInlineSizeThreshold && align .&. 3 == 0 = do
code_dst <- getAnyReg dst
dst_r <- getNewRegNat size
return $ code_dst dst_r `appOL` go dst_r n
where
(size, val) = case align .&. 3 of
2 -> (II16, c2)
0 -> (II32, c4)
_ -> (II8, c)
c2 = c `shiftL` 8 .|. c
c4 = c2 `shiftL` 16 .|. c2
sizeBytes = fromIntegral (sizeInBytes size)
go :: Reg -> Integer -> OrdList Instr
go dst i
-- TODO: Add movabs instruction and support 64-bit sets.
| i >= sizeBytes = -- This might be smaller than the below sizes
unitOL (MOV size (OpImm (ImmInteger val)) (OpAddr dst_addr)) `appOL`
go dst (i - sizeBytes)
| i >= 4 = -- Will never happen on 32-bit
unitOL (MOV II32 (OpImm (ImmInteger c4)) (OpAddr dst_addr)) `appOL`
go dst (i - 4)
| i >= 2 =
unitOL (MOV II16 (OpImm (ImmInteger c2)) (OpAddr dst_addr)) `appOL`
go dst (i - 2)
| i >= 1 =
unitOL (MOV II8 (OpImm (ImmInteger c)) (OpAddr dst_addr)) `appOL`
go dst (i - 1)
| otherwise = nilOL
where
dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone
(ImmInteger (n - i))
genCCall _ (PrimTarget MO_WriteBarrier) _ _ = return nilOL
-- write barrier compiles to no code on x86/x86-64;
-- we keep it this long in order to prevent earlier optimisations.
genCCall _ (PrimTarget MO_Touch) _ _ = return nilOL
genCCall is32bit (PrimTarget (MO_Prefetch_Data n )) _ [src] =
case n of
0 -> genPrefetch src $ PREFETCH NTA size
1 -> genPrefetch src $ PREFETCH Lvl2 size
2 -> genPrefetch src $ PREFETCH Lvl1 size
3 -> genPrefetch src $ PREFETCH Lvl0 size
l -> panic $ "unexpected prefetch level in genCCall MO_Prefetch_Data: " ++ (show l)
-- the c / llvm prefetch convention is 0, 1, 2, and 3
-- the x86 corresponding names are : NTA, 2 , 1, and 0
where
size = archWordSize is32bit
-- need to know what register width for pointers!
genPrefetch inRegSrc prefetchCTor =
do
code_src <- getAnyReg inRegSrc
src_r <- getNewRegNat size
return $ code_src src_r `appOL`
(unitOL (prefetchCTor (OpAddr
((AddrBaseIndex (EABaseReg src_r ) EAIndexNone (ImmInt 0)))) ))
-- prefetch always takes an address
genCCall is32Bit (PrimTarget (MO_BSwap width)) [dst] [src] = do
dflags <- getDynFlags
let platform = targetPlatform dflags
let dst_r = getRegisterReg platform False (CmmLocal dst)
case width of
W64 | is32Bit -> do
ChildCode64 vcode rlo <- iselExpr64 src
let dst_rhi = getHiVRegFromLo dst_r
rhi = getHiVRegFromLo rlo
return $ vcode `appOL`
toOL [ MOV II32 (OpReg rlo) (OpReg dst_rhi),
MOV II32 (OpReg rhi) (OpReg dst_r),
BSWAP II32 dst_rhi,
BSWAP II32 dst_r ]
W16 -> do code_src <- getAnyReg src
return $ code_src dst_r `appOL`
unitOL (BSWAP II32 dst_r) `appOL`
unitOL (SHR II32 (OpImm $ ImmInt 16) (OpReg dst_r))
_ -> do code_src <- getAnyReg src
return $ code_src dst_r `appOL` unitOL (BSWAP size dst_r)
where
size = intSize width
genCCall is32Bit (PrimTarget (MO_PopCnt width)) dest_regs@[dst]
args@[src] = do
sse4_2 <- sse4_2Enabled
dflags <- getDynFlags
let platform = targetPlatform dflags
if sse4_2
then do code_src <- getAnyReg src
src_r <- getNewRegNat size
let dst_r = getRegisterReg platform False (CmmLocal dst)
return $ code_src src_r `appOL`
(if width == W8 then
-- The POPCNT instruction doesn't take a r/m8
unitOL (MOVZxL II8 (OpReg src_r) (OpReg src_r)) `appOL`
unitOL (POPCNT II16 (OpReg src_r) dst_r)
else
unitOL (POPCNT size (OpReg src_r) dst_r)) `appOL`
(if width == W8 || width == W16 then
-- We used a 16-bit destination register above,
-- so zero-extend
unitOL (MOVZxL II16 (OpReg dst_r) (OpReg dst_r))
else nilOL)
else do
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall is32Bit target dest_regs args
where
size = intSize width
lbl = mkCmmCodeLabel primPackageId (fsLit (popCntLabel width))
genCCall is32Bit (PrimTarget (MO_UF_Conv width)) dest_regs args = do
dflags <- getDynFlags
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall is32Bit target dest_regs args
where
lbl = mkCmmCodeLabel primPackageId (fsLit (word2FloatLabel width))
genCCall is32Bit target dest_regs args
| is32Bit = genCCall32 target dest_regs args
| otherwise = genCCall64 target dest_regs args
genCCall32 :: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall32 target dest_regs args = do
dflags <- getDynFlags
let platform = targetPlatform dflags
case (target, dest_regs) of
-- void return type prim op
(PrimTarget op, []) ->
outOfLineCmmOp op Nothing args
-- we only cope with a single result for foreign calls
(PrimTarget op, [r]) -> do
l1 <- getNewLabelNat
l2 <- getNewLabelNat
sse2 <- sse2Enabled
if sse2
then
outOfLineCmmOp op (Just r) args
else case op of
MO_F32_Sqrt -> actuallyInlineFloatOp GSQRT FF32 args
MO_F64_Sqrt -> actuallyInlineFloatOp GSQRT FF64 args
MO_F32_Sin -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF32 args
MO_F64_Sin -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF64 args
MO_F32_Cos -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF32 args
MO_F64_Cos -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF64 args
MO_F32_Tan -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF32 args
MO_F64_Tan -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF64 args
_other_op -> outOfLineCmmOp op (Just r) args
where
actuallyInlineFloatOp instr size [x]
= do res <- trivialUFCode size (instr size) x
any <- anyReg res
return (any (getRegisterReg platform False (CmmLocal r)))
actuallyInlineFloatOp _ _ args
= panic $ "genCCall32.actuallyInlineFloatOp: bad number of arguments! ("
++ show (length args) ++ ")"
(PrimTarget (MO_S_QuotRem width), _) -> divOp1 platform True width dest_regs args
(PrimTarget (MO_U_QuotRem width), _) -> divOp1 platform False width dest_regs args
(PrimTarget (MO_U_QuotRem2 width), _) -> divOp2 platform False width dest_regs args
(PrimTarget (MO_Add2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do hCode <- getAnyReg (CmmLit (CmmInt 0 width))
lCode <- getAnyReg (CmmMachOp (MO_Add width) [arg_x, arg_y])
let size = intSize width
reg_l = getRegisterReg platform True (CmmLocal res_l)
reg_h = getRegisterReg platform True (CmmLocal res_h)
code = hCode reg_h `appOL`
lCode reg_l `snocOL`
ADC size (OpImm (ImmInteger 0)) (OpReg reg_h)
return code
_ -> panic "genCCall32: Wrong number of arguments/results for add2"
(PrimTarget (MO_U_Mul2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do (y_reg, y_code) <- getRegOrMem arg_y
x_code <- getAnyReg arg_x
let size = intSize width
reg_h = getRegisterReg platform True (CmmLocal res_h)
reg_l = getRegisterReg platform True (CmmLocal res_l)
code = y_code `appOL`
x_code rax `appOL`
toOL [MUL2 size y_reg,
MOV size (OpReg rdx) (OpReg reg_h),
MOV size (OpReg rax) (OpReg reg_l)]
return code
_ -> panic "genCCall32: Wrong number of arguments/results for add2"
_ -> genCCall32' dflags target dest_regs args
where divOp1 platform signed width results [arg_x, arg_y]
= divOp platform signed width results Nothing arg_x arg_y
divOp1 _ _ _ _ _
= panic "genCCall32: Wrong number of arguments for divOp1"
divOp2 platform signed width results [arg_x_high, arg_x_low, arg_y]
= divOp platform signed width results (Just arg_x_high) arg_x_low arg_y
divOp2 _ _ _ _ _
= panic "genCCall64: Wrong number of arguments for divOp2"
divOp platform signed width [res_q, res_r]
m_arg_x_high arg_x_low arg_y
= do let size = intSize width
reg_q = getRegisterReg platform True (CmmLocal res_q)
reg_r = getRegisterReg platform True (CmmLocal res_r)
widen | signed = CLTD size
| otherwise = XOR size (OpReg rdx) (OpReg rdx)
instr | signed = IDIV
| otherwise = DIV
(y_reg, y_code) <- getRegOrMem arg_y
x_low_code <- getAnyReg arg_x_low
x_high_code <- case m_arg_x_high of
Just arg_x_high ->
getAnyReg arg_x_high
Nothing ->
return $ const $ unitOL widen
return $ y_code `appOL`
x_low_code rax `appOL`
x_high_code rdx `appOL`
toOL [instr size y_reg,
MOV size (OpReg rax) (OpReg reg_q),
MOV size (OpReg rdx) (OpReg reg_r)]
divOp _ _ _ _ _ _ _
= panic "genCCall32: Wrong number of results for divOp"
genCCall32' :: DynFlags
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall32' dflags target dest_regs args = do
let
prom_args = map (maybePromoteCArg dflags W32) args
-- Align stack to 16n for calls, assuming a starting stack
-- alignment of 16n - word_size on procedure entry. Which we
-- maintiain. See Note [rts/StgCRun.c : Stack Alignment on X86]
sizes = map (arg_size . cmmExprType dflags) (reverse args)
raw_arg_size = sum sizes + wORD_SIZE dflags
arg_pad_size = (roundTo 16 $ raw_arg_size) - raw_arg_size
tot_arg_size = raw_arg_size + arg_pad_size - wORD_SIZE dflags
delta0 <- getDeltaNat
setDeltaNat (delta0 - arg_pad_size)
use_sse2 <- sse2Enabled
push_codes <- mapM (push_arg use_sse2) (reverse prom_args)
delta <- getDeltaNat
MASSERT(delta == delta0 - tot_arg_size)
-- deal with static vs dynamic call targets
(callinsns,cconv) <-
case target of
ForeignTarget (CmmLit (CmmLabel lbl)) conv
-> -- ToDo: stdcall arg sizes
return (unitOL (CALL (Left fn_imm) []), conv)
where fn_imm = ImmCLbl lbl
ForeignTarget expr conv
-> do { (dyn_r, dyn_c) <- getSomeReg expr
; ASSERT( isWord32 (cmmExprType dflags expr) )
return (dyn_c `snocOL` CALL (Right dyn_r) [], conv) }
PrimTarget _
-> panic $ "genCCall: Can't handle PrimTarget call type here, error "
++ "probably because too many return values."
let push_code
| arg_pad_size /= 0
= toOL [SUB II32 (OpImm (ImmInt arg_pad_size)) (OpReg esp),
DELTA (delta0 - arg_pad_size)]
`appOL` concatOL push_codes
| otherwise
= concatOL push_codes
-- Deallocate parameters after call for ccall;
-- but not for stdcall (callee does it)
--
-- We have to pop any stack padding we added
-- even if we are doing stdcall, though (#5052)
pop_size
| ForeignConvention StdCallConv _ _ _ <- cconv = arg_pad_size
| otherwise = tot_arg_size
call = callinsns `appOL`
toOL (
(if pop_size==0 then [] else
[ADD II32 (OpImm (ImmInt pop_size)) (OpReg esp)])
++
[DELTA delta0]
)
setDeltaNat delta0
dflags <- getDynFlags
let platform = targetPlatform dflags
let
-- assign the results, if necessary
assign_code [] = nilOL
assign_code [dest]
| isFloatType ty =
if use_sse2
then let tmp_amode = AddrBaseIndex (EABaseReg esp)
EAIndexNone
(ImmInt 0)
sz = floatSize w
in toOL [ SUB II32 (OpImm (ImmInt b)) (OpReg esp),
DELTA (delta0 - b),
GST sz fake0 tmp_amode,
MOV sz (OpAddr tmp_amode) (OpReg r_dest),
ADD II32 (OpImm (ImmInt b)) (OpReg esp),
DELTA delta0]
else unitOL (GMOV fake0 r_dest)
| isWord64 ty = toOL [MOV II32 (OpReg eax) (OpReg r_dest),
MOV II32 (OpReg edx) (OpReg r_dest_hi)]
| otherwise = unitOL (MOV (intSize w) (OpReg eax) (OpReg r_dest))
where
ty = localRegType dest
w = typeWidth ty
b = widthInBytes w
r_dest_hi = getHiVRegFromLo r_dest
r_dest = getRegisterReg platform use_sse2 (CmmLocal dest)
assign_code many = pprPanic "genCCall.assign_code - too many return values:" (ppr many)
return (push_code `appOL`
call `appOL`
assign_code dest_regs)
where
arg_size :: CmmType -> Int -- Width in bytes
arg_size ty = widthInBytes (typeWidth ty)
roundTo a x | x `mod` a == 0 = x
| otherwise = x + a - (x `mod` a)
push_arg :: Bool -> CmmActual {-current argument-}
-> NatM InstrBlock -- code
push_arg use_sse2 arg -- we don't need the hints on x86
| isWord64 arg_ty = do
ChildCode64 code r_lo <- iselExpr64 arg
delta <- getDeltaNat
setDeltaNat (delta - 8)
let
r_hi = getHiVRegFromLo r_lo
return ( code `appOL`
toOL [PUSH II32 (OpReg r_hi), DELTA (delta - 4),
PUSH II32 (OpReg r_lo), DELTA (delta - 8),
DELTA (delta-8)]
)
| isFloatType arg_ty = do
(reg, code) <- getSomeReg arg
delta <- getDeltaNat
setDeltaNat (delta-size)
return (code `appOL`
toOL [SUB II32 (OpImm (ImmInt size)) (OpReg esp),
DELTA (delta-size),
let addr = AddrBaseIndex (EABaseReg esp)
EAIndexNone
(ImmInt 0)
size = floatSize (typeWidth arg_ty)
in
if use_sse2
then MOV size (OpReg reg) (OpAddr addr)
else GST size reg addr
]
)
| otherwise = do
(operand, code) <- getOperand arg
delta <- getDeltaNat
setDeltaNat (delta-size)
return (code `snocOL`
PUSH II32 operand `snocOL`
DELTA (delta-size))
where
arg_ty = cmmExprType dflags arg
size = arg_size arg_ty -- Byte size
genCCall64 :: ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall64 target dest_regs args = do
dflags <- getDynFlags
let platform = targetPlatform dflags
case (target, dest_regs) of
(PrimTarget op, []) ->
-- void return type prim op
outOfLineCmmOp op Nothing args
(PrimTarget op, [res]) ->
-- we only cope with a single result for foreign calls
outOfLineCmmOp op (Just res) args
(PrimTarget (MO_S_QuotRem width), _) -> divOp1 platform True width dest_regs args
(PrimTarget (MO_U_QuotRem width), _) -> divOp1 platform False width dest_regs args
(PrimTarget (MO_U_QuotRem2 width), _) -> divOp2 platform False width dest_regs args
(PrimTarget (MO_Add2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do hCode <- getAnyReg (CmmLit (CmmInt 0 width))
lCode <- getAnyReg (CmmMachOp (MO_Add width) [arg_x, arg_y])
let size = intSize width
reg_l = getRegisterReg platform True (CmmLocal res_l)
reg_h = getRegisterReg platform True (CmmLocal res_h)
code = hCode reg_h `appOL`
lCode reg_l `snocOL`
ADC size (OpImm (ImmInteger 0)) (OpReg reg_h)
return code
_ -> panic "genCCall64: Wrong number of arguments/results for add2"
(PrimTarget (MO_U_Mul2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do (y_reg, y_code) <- getRegOrMem arg_y
x_code <- getAnyReg arg_x
let size = intSize width
reg_h = getRegisterReg platform True (CmmLocal res_h)
reg_l = getRegisterReg platform True (CmmLocal res_l)
code = y_code `appOL`
x_code rax `appOL`
toOL [MUL2 size y_reg,
MOV size (OpReg rdx) (OpReg reg_h),
MOV size (OpReg rax) (OpReg reg_l)]
return code
_ -> panic "genCCall64: Wrong number of arguments/results for add2"
_ ->
do dflags <- getDynFlags
genCCall64' dflags target dest_regs args
where divOp1 platform signed width results [arg_x, arg_y]
= divOp platform signed width results Nothing arg_x arg_y
divOp1 _ _ _ _ _
= panic "genCCall64: Wrong number of arguments for divOp1"
divOp2 platform signed width results [arg_x_high, arg_x_low, arg_y]
= divOp platform signed width results (Just arg_x_high) arg_x_low arg_y
divOp2 _ _ _ _ _
= panic "genCCall64: Wrong number of arguments for divOp2"
divOp platform signed width [res_q, res_r]
m_arg_x_high arg_x_low arg_y
= do let size = intSize width
reg_q = getRegisterReg platform True (CmmLocal res_q)
reg_r = getRegisterReg platform True (CmmLocal res_r)
widen | signed = CLTD size
| otherwise = XOR size (OpReg rdx) (OpReg rdx)
instr | signed = IDIV
| otherwise = DIV
(y_reg, y_code) <- getRegOrMem arg_y
x_low_code <- getAnyReg arg_x_low
x_high_code <- case m_arg_x_high of
Just arg_x_high -> getAnyReg arg_x_high
Nothing -> return $ const $ unitOL widen
return $ y_code `appOL`
x_low_code rax `appOL`
x_high_code rdx `appOL`
toOL [instr size y_reg,
MOV size (OpReg rax) (OpReg reg_q),
MOV size (OpReg rdx) (OpReg reg_r)]
divOp _ _ _ _ _ _ _
= panic "genCCall64: Wrong number of results for divOp"
genCCall64' :: DynFlags
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall64' dflags target dest_regs args = do
-- load up the register arguments
let prom_args = map (maybePromoteCArg dflags W32) args
(stack_args, int_regs_used, fp_regs_used, load_args_code)
<-
if platformOS platform == OSMinGW32
then load_args_win prom_args [] [] (allArgRegs platform) nilOL
else do (stack_args, aregs, fregs, load_args_code)
<- load_args prom_args (allIntArgRegs platform) (allFPArgRegs platform) nilOL
let fp_regs_used = reverse (drop (length fregs) (reverse (allFPArgRegs platform)))
int_regs_used = reverse (drop (length aregs) (reverse (allIntArgRegs platform)))
return (stack_args, int_regs_used, fp_regs_used, load_args_code)
let
arg_regs_used = int_regs_used ++ fp_regs_used
arg_regs = [eax] ++ arg_regs_used
-- for annotating the call instruction with
sse_regs = length fp_regs_used
arg_stack_slots = if platformOS platform == OSMinGW32
then length stack_args + length (allArgRegs platform)
else length stack_args
tot_arg_size = arg_size * arg_stack_slots
-- Align stack to 16n for calls, assuming a starting stack
-- alignment of 16n - word_size on procedure entry. Which we
-- maintain. See Note [rts/StgCRun.c : Stack Alignment on X86]
(real_size, adjust_rsp) <-
if (tot_arg_size + wORD_SIZE dflags) `rem` 16 == 0
then return (tot_arg_size, nilOL)
else do -- we need to adjust...
delta <- getDeltaNat
setDeltaNat (delta - wORD_SIZE dflags)
return (tot_arg_size + wORD_SIZE dflags, toOL [
SUB II64 (OpImm (ImmInt (wORD_SIZE dflags))) (OpReg rsp),
DELTA (delta - wORD_SIZE dflags) ])
-- push the stack args, right to left
push_code <- push_args (reverse stack_args) nilOL
-- On Win64, we also have to leave stack space for the arguments
-- that we are passing in registers
lss_code <- if platformOS platform == OSMinGW32
then leaveStackSpace (length (allArgRegs platform))
else return nilOL
delta <- getDeltaNat
-- deal with static vs dynamic call targets
(callinsns,_cconv) <-
case target of
ForeignTarget (CmmLit (CmmLabel lbl)) conv
-> -- ToDo: stdcall arg sizes
return (unitOL (CALL (Left fn_imm) arg_regs), conv)
where fn_imm = ImmCLbl lbl
ForeignTarget expr conv
-> do (dyn_r, dyn_c) <- getSomeReg expr
return (dyn_c `snocOL` CALL (Right dyn_r) arg_regs, conv)
PrimTarget _
-> panic $ "genCCall: Can't handle PrimTarget call type here, error "
++ "probably because too many return values."
let
-- The x86_64 ABI requires us to set %al to the number of SSE2
-- registers that contain arguments, if the called routine
-- is a varargs function. We don't know whether it's a
-- varargs function or not, so we have to assume it is.
--
-- It's not safe to omit this assignment, even if the number
-- of SSE2 regs in use is zero. If %al is larger than 8
-- on entry to a varargs function, seg faults ensue.
assign_eax n = unitOL (MOV II32 (OpImm (ImmInt n)) (OpReg eax))
let call = callinsns `appOL`
toOL (
-- Deallocate parameters after call for ccall;
-- stdcall has callee do it, but is not supported on
-- x86_64 target (see #3336)
(if real_size==0 then [] else
[ADD (intSize (wordWidth dflags)) (OpImm (ImmInt real_size)) (OpReg esp)])
++
[DELTA (delta + real_size)]
)
setDeltaNat (delta + real_size)
let
-- assign the results, if necessary
assign_code [] = nilOL
assign_code [dest] =
case typeWidth rep of
W32 | isFloatType rep -> unitOL (MOV (floatSize W32) (OpReg xmm0) (OpReg r_dest))
W64 | isFloatType rep -> unitOL (MOV (floatSize W64) (OpReg xmm0) (OpReg r_dest))
_ -> unitOL (MOV (cmmTypeSize rep) (OpReg rax) (OpReg r_dest))
where
rep = localRegType dest
r_dest = getRegisterReg platform True (CmmLocal dest)
assign_code _many = panic "genCCall.assign_code many"
return (load_args_code `appOL`
adjust_rsp `appOL`
push_code `appOL`
lss_code `appOL`
assign_eax sse_regs `appOL`
call `appOL`
assign_code dest_regs)
where platform = targetPlatform dflags
arg_size = 8 -- always, at the mo
load_args :: [CmmExpr]
-> [Reg] -- int regs avail for args
-> [Reg] -- FP regs avail for args
-> InstrBlock
-> NatM ([CmmExpr],[Reg],[Reg],InstrBlock)
load_args args [] [] code = return (args, [], [], code)
-- no more regs to use
load_args [] aregs fregs code = return ([], aregs, fregs, code)
-- no more args to push
load_args (arg : rest) aregs fregs code
| isFloatType arg_rep =
case fregs of
[] -> push_this_arg
(r:rs) -> do
arg_code <- getAnyReg arg
load_args rest aregs rs (code `appOL` arg_code r)
| otherwise =
case aregs of
[] -> push_this_arg
(r:rs) -> do
arg_code <- getAnyReg arg
load_args rest rs fregs (code `appOL` arg_code r)
where
arg_rep = cmmExprType dflags arg
push_this_arg = do
(args',ars,frs,code') <- load_args rest aregs fregs code
return (arg:args', ars, frs, code')
load_args_win :: [CmmExpr]
-> [Reg] -- used int regs
-> [Reg] -- used FP regs
-> [(Reg, Reg)] -- (int, FP) regs avail for args
-> InstrBlock
-> NatM ([CmmExpr],[Reg],[Reg],InstrBlock)
load_args_win args usedInt usedFP [] code
= return (args, usedInt, usedFP, code)
-- no more regs to use
load_args_win [] usedInt usedFP _ code
= return ([], usedInt, usedFP, code)
-- no more args to push
load_args_win (arg : rest) usedInt usedFP
((ireg, freg) : regs) code
| isFloatType arg_rep = do
arg_code <- getAnyReg arg
load_args_win rest (ireg : usedInt) (freg : usedFP) regs
(code `appOL`
arg_code freg `snocOL`
-- If we are calling a varargs function
-- then we need to define ireg as well
-- as freg
MOV II64 (OpReg freg) (OpReg ireg))
| otherwise = do
arg_code <- getAnyReg arg
load_args_win rest (ireg : usedInt) usedFP regs
(code `appOL` arg_code ireg)
where
arg_rep = cmmExprType dflags arg
push_args [] code = return code
push_args (arg:rest) code
| isFloatType arg_rep = do
(arg_reg, arg_code) <- getSomeReg arg
delta <- getDeltaNat
setDeltaNat (delta-arg_size)
let code' = code `appOL` arg_code `appOL` toOL [
SUB (intSize (wordWidth dflags)) (OpImm (ImmInt arg_size)) (OpReg rsp) ,
DELTA (delta-arg_size),
MOV (floatSize width) (OpReg arg_reg) (OpAddr (spRel dflags 0))]
push_args rest code'
| otherwise = do
ASSERT(width == W64) return ()
(arg_op, arg_code) <- getOperand arg
delta <- getDeltaNat
setDeltaNat (delta-arg_size)
let code' = code `appOL` arg_code `appOL` toOL [
PUSH II64 arg_op,
DELTA (delta-arg_size)]
push_args rest code'
where
arg_rep = cmmExprType dflags arg
width = typeWidth arg_rep
leaveStackSpace n = do
delta <- getDeltaNat
setDeltaNat (delta - n * arg_size)
return $ toOL [
SUB II64 (OpImm (ImmInt (n * wORD_SIZE dflags))) (OpReg rsp),
DELTA (delta - n * arg_size)]
maybePromoteCArg :: DynFlags -> Width -> CmmExpr -> CmmExpr
maybePromoteCArg dflags wto arg
| wfrom < wto = CmmMachOp (MO_UU_Conv wfrom wto) [arg]
| otherwise = arg
where
wfrom = cmmExprWidth dflags arg
-- | We're willing to inline and unroll memcpy/memset calls that touch
-- at most these many bytes. This threshold is the same as the one
-- used by GCC and LLVM.
maxInlineSizeThreshold :: Integer
maxInlineSizeThreshold = 128
outOfLineCmmOp :: CallishMachOp -> Maybe CmmFormal -> [CmmActual] -> NatM InstrBlock
outOfLineCmmOp mop res args
= do
dflags <- getDynFlags
targetExpr <- cmmMakeDynamicReference dflags CallReference lbl
let target = ForeignTarget targetExpr
(ForeignConvention CCallConv [] [] CmmMayReturn)
stmtToInstrs (CmmUnsafeForeignCall target (catMaybes [res]) args')
where
-- Assume we can call these functions directly, and that they're not in a dynamic library.
-- TODO: Why is this ok? Under linux this code will be in libm.so
-- Is is because they're really implemented as a primitive instruction by the assembler?? -- BL 2009/12/31
lbl = mkForeignLabel fn Nothing ForeignLabelInThisPackage IsFunction
args' = case mop of
MO_Memcpy -> init args
MO_Memset -> init args
MO_Memmove -> init args
_ -> args
fn = case mop of
MO_F32_Sqrt -> fsLit "sqrtf"
MO_F32_Sin -> fsLit "sinf"
MO_F32_Cos -> fsLit "cosf"
MO_F32_Tan -> fsLit "tanf"
MO_F32_Exp -> fsLit "expf"
MO_F32_Log -> fsLit "logf"
MO_F32_Asin -> fsLit "asinf"
MO_F32_Acos -> fsLit "acosf"
MO_F32_Atan -> fsLit "atanf"
MO_F32_Sinh -> fsLit "sinhf"
MO_F32_Cosh -> fsLit "coshf"
MO_F32_Tanh -> fsLit "tanhf"
MO_F32_Pwr -> fsLit "powf"
MO_F64_Sqrt -> fsLit "sqrt"
MO_F64_Sin -> fsLit "sin"
MO_F64_Cos -> fsLit "cos"
MO_F64_Tan -> fsLit "tan"
MO_F64_Exp -> fsLit "exp"
MO_F64_Log -> fsLit "log"
MO_F64_Asin -> fsLit "asin"
MO_F64_Acos -> fsLit "acos"
MO_F64_Atan -> fsLit "atan"
MO_F64_Sinh -> fsLit "sinh"
MO_F64_Cosh -> fsLit "cosh"
MO_F64_Tanh -> fsLit "tanh"
MO_F64_Pwr -> fsLit "pow"
MO_Memcpy -> fsLit "memcpy"
MO_Memset -> fsLit "memset"
MO_Memmove -> fsLit "memmove"
MO_PopCnt _ -> fsLit "popcnt"
MO_BSwap _ -> fsLit "bswap"
MO_UF_Conv _ -> unsupported
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _ ) -> unsupported
unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported here")
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> [Maybe BlockId] -> NatM InstrBlock
genSwitch dflags expr ids
| gopt Opt_PIC dflags
= do
(reg,e_code) <- getSomeReg expr
lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let op = OpAddr (AddrBaseIndex (EABaseReg tableReg)
(EAIndex reg (wORD_SIZE dflags)) (ImmInt 0))
return $ if target32Bit (targetPlatform dflags)
then e_code `appOL` t_code `appOL` toOL [
ADD (intSize (wordWidth dflags)) op (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids ReadOnlyData lbl
]
else case platformOS (targetPlatform dflags) of
OSDarwin ->
-- on Mac OS X/x86_64, put the jump table
-- in the text section to work around a
-- limitation of the linker.
-- ld64 is unable to handle the relocations for
-- .quad L1 - L0
-- if L0 is not preceded by a non-anonymous
-- label in its section.
e_code `appOL` t_code `appOL` toOL [
ADD (intSize (wordWidth dflags)) op (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids Text lbl
]
_ ->
-- HACK: On x86_64 binutils<2.17 is only able
-- to generate PC32 relocations, hence we only
-- get 32-bit offsets in the jump table. As
-- these offsets are always negative we need
-- to properly sign extend them to 64-bit.
-- This hack should be removed in conjunction
-- with the hack in PprMach.hs/pprDataItem
-- once binutils 2.17 is standard.
e_code `appOL` t_code `appOL` toOL [
MOVSxL II32 op (OpReg reg),
ADD (intSize (wordWidth dflags)) (OpReg reg) (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids ReadOnlyData lbl
]
| otherwise
= do
(reg,e_code) <- getSomeReg expr
lbl <- getNewLabelNat
let op = OpAddr (AddrBaseIndex EABaseNone (EAIndex reg (wORD_SIZE dflags)) (ImmCLbl lbl))
code = e_code `appOL` toOL [
JMP_TBL op ids ReadOnlyData lbl
]
return code
generateJumpTableForInstr :: DynFlags -> Instr -> Maybe (NatCmmDecl (Alignment, CmmStatics) Instr)
generateJumpTableForInstr dflags (JMP_TBL _ ids section lbl)
= Just (createJumpTable dflags ids section lbl)
generateJumpTableForInstr _ _ = Nothing
createJumpTable :: DynFlags -> [Maybe BlockId] -> Section -> CLabel
-> GenCmmDecl (Alignment, CmmStatics) h g
createJumpTable dflags ids section lbl
= let jumpTable
| gopt Opt_PIC dflags =
let jumpTableEntryRel Nothing
= CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntryRel (Just blockid)
= CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
where blockLabel = mkAsmTempLabel (getUnique blockid)
in map jumpTableEntryRel ids
| otherwise = map (jumpTableEntry dflags) ids
in CmmData section (1, Statics lbl jumpTable)
-- -----------------------------------------------------------------------------
-- 'condIntReg' and 'condFltReg': condition codes into registers
-- Turn those condition codes into integers now (when they appear on
-- the right hand side of an assignment).
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
condIntReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
condIntReg cond x y = do
CondCode _ cond cond_code <- condIntCode cond x y
tmp <- getNewRegNat II8
let
code dst = cond_code `appOL` toOL [
SETCC cond (OpReg tmp),
MOVZxL II8 (OpReg tmp) (OpReg dst)
]
return (Any II32 code)
condFltReg :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM Register
condFltReg is32Bit cond x y = if_sse2 condFltReg_sse2 condFltReg_x87
where
condFltReg_x87 = do
CondCode _ cond cond_code <- condFltCode cond x y
tmp <- getNewRegNat II8
let
code dst = cond_code `appOL` toOL [
SETCC cond (OpReg tmp),
MOVZxL II8 (OpReg tmp) (OpReg dst)
]
return (Any II32 code)
condFltReg_sse2 = do
CondCode _ cond cond_code <- condFltCode cond x y
tmp1 <- getNewRegNat (archWordSize is32Bit)
tmp2 <- getNewRegNat (archWordSize is32Bit)
let
-- We have to worry about unordered operands (eg. comparisons
-- against NaN). If the operands are unordered, the comparison
-- sets the parity flag, carry flag and zero flag.
-- All comparisons are supposed to return false for unordered
-- operands except for !=, which returns true.
--
-- Optimisation: we don't have to test the parity flag if we
-- know the test has already excluded the unordered case: eg >
-- and >= test for a zero carry flag, which can only occur for
-- ordered operands.
--
-- ToDo: by reversing comparisons we could avoid testing the
-- parity flag in more cases.
code dst =
cond_code `appOL`
(case cond of
NE -> or_unordered dst
GU -> plain_test dst
GEU -> plain_test dst
_ -> and_ordered dst)
plain_test dst = toOL [
SETCC cond (OpReg tmp1),
MOVZxL II8 (OpReg tmp1) (OpReg dst)
]
or_unordered dst = toOL [
SETCC cond (OpReg tmp1),
SETCC PARITY (OpReg tmp2),
OR II8 (OpReg tmp1) (OpReg tmp2),
MOVZxL II8 (OpReg tmp2) (OpReg dst)
]
and_ordered dst = toOL [
SETCC cond (OpReg tmp1),
SETCC NOTPARITY (OpReg tmp2),
AND II8 (OpReg tmp1) (OpReg tmp2),
MOVZxL II8 (OpReg tmp2) (OpReg dst)
]
return (Any II32 code)
-- -----------------------------------------------------------------------------
-- 'trivial*Code': deal with trivial instructions
-- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
-- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
-- Only look for constants on the right hand side, because that's
-- where the generic optimizer will have put them.
-- Similarly, for unary instructions, we don't have to worry about
-- matching an StInt as the argument, because genericOpt will already
-- have handled the constant-folding.
{-
The Rules of the Game are:
* You cannot assume anything about the destination register dst;
it may be anything, including a fixed reg.
* You may compute an operand into a fixed reg, but you may not
subsequently change the contents of that fixed reg. If you
want to do so, first copy the value either to a temporary
or into dst. You are free to modify dst even if it happens
to be a fixed reg -- that's not your problem.
* You cannot assume that a fixed reg will stay live over an
arbitrary computation. The same applies to the dst reg.
* Temporary regs obtained from getNewRegNat are distinct from
each other and from all other regs, and stay live over
arbitrary computations.
--------------------
SDM's version of The Rules:
* If getRegister returns Any, that means it can generate correct
code which places the result in any register, period. Even if that
register happens to be read during the computation.
Corollary #1: this means that if you are generating code for an
operation with two arbitrary operands, you cannot assign the result
of the first operand into the destination register before computing
the second operand. The second operand might require the old value
of the destination register.
Corollary #2: A function might be able to generate more efficient
code if it knows the destination register is a new temporary (and
therefore not read by any of the sub-computations).
* If getRegister returns Any, then the code it generates may modify only:
(a) fresh temporaries
(b) the destination register
(c) known registers (eg. %ecx is used by shifts)
In particular, it may *not* modify global registers, unless the global
register happens to be the destination register.
-}
trivialCode :: Width -> (Operand -> Operand -> Instr)
-> Maybe (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCode width instr m a b
= do is32Bit <- is32BitPlatform
trivialCode' is32Bit width instr m a b
trivialCode' :: Bool -> Width -> (Operand -> Operand -> Instr)
-> Maybe (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCode' is32Bit width _ (Just revinstr) (CmmLit lit_a) b
| is32BitLit is32Bit lit_a = do
b_code <- getAnyReg b
let
code dst
= b_code dst `snocOL`
revinstr (OpImm (litToImm lit_a)) (OpReg dst)
return (Any (intSize width) code)
trivialCode' _ width instr _ a b
= genTrivialCode (intSize width) instr a b
-- This is re-used for floating pt instructions too.
genTrivialCode :: Size -> (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
genTrivialCode rep instr a b = do
(b_op, b_code) <- getNonClobberedOperand b
a_code <- getAnyReg a
tmp <- getNewRegNat rep
let
-- We want the value of b to stay alive across the computation of a.
-- But, we want to calculate a straight into the destination register,
-- because the instruction only has two operands (dst := dst `op` src).
-- The troublesome case is when the result of b is in the same register
-- as the destination reg. In this case, we have to save b in a
-- new temporary across the computation of a.
code dst
| dst `regClashesWithOp` b_op =
b_code `appOL`
unitOL (MOV rep b_op (OpReg tmp)) `appOL`
a_code dst `snocOL`
instr (OpReg tmp) (OpReg dst)
| otherwise =
b_code `appOL`
a_code dst `snocOL`
instr b_op (OpReg dst)
return (Any rep code)
regClashesWithOp :: Reg -> Operand -> Bool
reg `regClashesWithOp` OpReg reg2 = reg == reg2
reg `regClashesWithOp` OpAddr amode = any (==reg) (addrModeRegs amode)
_ `regClashesWithOp` _ = False
-----------
trivialUCode :: Size -> (Operand -> Instr)
-> CmmExpr -> NatM Register
trivialUCode rep instr x = do
x_code <- getAnyReg x
let
code dst =
x_code dst `snocOL`
instr (OpReg dst)
return (Any rep code)
-----------
trivialFCode_x87 :: (Size -> Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialFCode_x87 instr x y = do
(x_reg, x_code) <- getNonClobberedReg x -- these work for float regs too
(y_reg, y_code) <- getSomeReg y
let
size = FF80 -- always, on x87
code dst =
x_code `appOL`
y_code `snocOL`
instr size x_reg y_reg dst
return (Any size code)
trivialFCode_sse2 :: Width -> (Size -> Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialFCode_sse2 pk instr x y
= genTrivialCode size (instr size) x y
where size = floatSize pk
trivialUFCode :: Size -> (Reg -> Reg -> Instr) -> CmmExpr -> NatM Register
trivialUFCode size instr x = do
(x_reg, x_code) <- getSomeReg x
let
code dst =
x_code `snocOL`
instr x_reg dst
return (Any size code)
--------------------------------------------------------------------------------
coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP from to x = if_sse2 coerce_sse2 coerce_x87
where
coerce_x87 = do
(x_reg, x_code) <- getSomeReg x
let
opc = case to of W32 -> GITOF; W64 -> GITOD;
n -> panic $ "coerceInt2FP.x87: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc x_reg dst
-- ToDo: works for non-II32 reps?
return (Any FF80 code)
coerce_sse2 = do
(x_op, x_code) <- getOperand x -- ToDo: could be a safe operand
let
opc = case to of W32 -> CVTSI2SS; W64 -> CVTSI2SD
n -> panic $ "coerceInt2FP.sse: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc (intSize from) x_op dst
return (Any (floatSize to) code)
-- works even if the destination rep is <II32
--------------------------------------------------------------------------------
coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int from to x = if_sse2 coerceFP2Int_sse2 coerceFP2Int_x87
where
coerceFP2Int_x87 = do
(x_reg, x_code) <- getSomeReg x
let
opc = case from of W32 -> GFTOI; W64 -> GDTOI
n -> panic $ "coerceFP2Int.x87: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc x_reg dst
-- ToDo: works for non-II32 reps?
return (Any (intSize to) code)
coerceFP2Int_sse2 = do
(x_op, x_code) <- getOperand x -- ToDo: could be a safe operand
let
opc = case from of W32 -> CVTTSS2SIQ; W64 -> CVTTSD2SIQ;
n -> panic $ "coerceFP2Init.sse: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc (intSize to) x_op dst
return (Any (intSize to) code)
-- works even if the destination rep is <II32
--------------------------------------------------------------------------------
coerceFP2FP :: Width -> CmmExpr -> NatM Register
coerceFP2FP to x = do
use_sse2 <- sse2Enabled
(x_reg, x_code) <- getSomeReg x
let
opc | use_sse2 = case to of W32 -> CVTSD2SS; W64 -> CVTSS2SD;
n -> panic $ "coerceFP2FP: unhandled width ("
++ show n ++ ")"
| otherwise = GDTOF
code dst = x_code `snocOL` opc x_reg dst
return (Any (if use_sse2 then floatSize to else FF80) code)
--------------------------------------------------------------------------------
sse2NegCode :: Width -> CmmExpr -> NatM Register
sse2NegCode w x = do
let sz = floatSize w
x_code <- getAnyReg x
-- This is how gcc does it, so it can't be that bad:
let
const | FF32 <- sz = CmmInt 0x80000000 W32
| otherwise = CmmInt 0x8000000000000000 W64
Amode amode amode_code <- memConstant (widthInBytes w) const
tmp <- getNewRegNat sz
let
code dst = x_code dst `appOL` amode_code `appOL` toOL [
MOV sz (OpAddr amode) (OpReg tmp),
XOR sz (OpReg tmp) (OpReg dst)
]
--
return (Any sz code)
isVecExpr :: CmmExpr -> Bool
isVecExpr (CmmMachOp (MO_V_Insert {}) _) = True
isVecExpr (CmmMachOp (MO_V_Extract {}) _) = True
isVecExpr (CmmMachOp (MO_V_Add {}) _) = True
isVecExpr (CmmMachOp (MO_V_Sub {}) _) = True
isVecExpr (CmmMachOp (MO_V_Mul {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Quot {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Rem {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Neg {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Insert {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Extract {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Add {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Sub {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Mul {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Quot {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Neg {}) _) = True
isVecExpr (CmmMachOp _ [e]) = isVecExpr e
isVecExpr _ = False
needLlvm :: NatM a
needLlvm =
sorry $ unlines ["The native code generator does not support vector"
,"instructions. Please use -fllvm."]
| hferreiro/replay | compiler/nativeGen/X86/CodeGen.hs | bsd-3-clause | 108,515 | 0 | 23 | 36,321 | 28,403 | 13,987 | 14,416 | -1 | -1 |
{-# LANGUAGE TypeSynonymInstances, OverlappingInstances #-}
module Text.JSON.AttoJSON.Bson
( -- * Convert between JSON and Bson
toBson, fromBson, toBsonHook
-- * Additional JSON instances for BSON
, JSON (..)
) where
import Data.Bson
import Data.CompactString.UTF8 (fromByteString_, toByteString)
import Data.Ratio
import Control.Applicative
import Data.Map hiding (mapMaybe)
import qualified Prelude as P
import Prelude
import Data.ByteString.Char8
import Text.JSON.AttoJSON
import Data.Maybe
import Data.Time.Clock
import Data.Time.Format
import Control.Monad
import Data.Maybe
import System.Locale
instance JSON Document where
toJSON = JSObject . fromList . P.map (\(k:=v) -> (toByteString k, toJSON v))
fromJSON (JSObject dic) = mapM (\(k, v) -> (fromByteString_ k :=) <$> fromJSON v) $ toList dic
fromJSON _ = Nothing
instance JSON Value where
toJSON (Float a) = JSNumber $ toRational a
toJSON (String u) = JSString $ toByteString u
toJSON (Doc doc) = toJSON doc
toJSON (Array vs) = JSArray $ P.map toJSON vs
toJSON (Bin (Binary bin)) = JSString bin
toJSON (Fun (Function f)) = JSString f
toJSON (Uuid (UUID uid)) = JSString uid
toJSON (Md5 (MD5 md5)) = JSString md5
toJSON (UserDef (UserDefined ud)) = JSString ud
toJSON (ObjId (Oid w32 w64)) = JSNumber $ toRational $ fromIntegral $ (toInteger w32)*2^64+toInteger w64
toJSON (Bool b) = JSBool b
toJSON (UTC utctime) = JSString $ pack $ formatTime defaultTimeLocale "%c" utctime
toJSON Null = JSNull
toJSON (RegEx (Regex a b)) = JSString (toByteString a `append` toByteString b)
toJSON (JavaScr (Javascript d js)) = JSString $ toByteString js
toJSON (Sym (Symbol sym)) = JSString . toByteString $ sym
toJSON (Int32 int) = JSNumber . toRational . fromIntegral $ int
toJSON (Int64 int) = JSNumber . toRational . fromIntegral $ int
toJSON (Stamp (MongoStamp int)) = JSNumber . toRational . fromIntegral $ int
toJSON (MinMax mk) = undefined
fromJSON JSNull = Just Null
fromJSON (JSString str) = Just . String $ fromByteString_ str
fromJSON (JSNumber num) | denominator num == 1 = Just . Int64 $ floor num
| otherwise = Just . Float $ fromRational num
fromJSON j@(JSObject _) = Doc <$> fromJSON j
fromJSON (JSBool b) = Just $ Bool b
fromJSON (JSArray jsa) = Array <$> mapM fromJSON jsa
instance Val ByteString where
val bs = String (fromByteString_ bs)
cast' (String str) = Just $ toByteString str
cast' (JavaScr (Javascript _ str)) = Just $ toByteString str
cast' (Sym (Symbol str)) = Just $ toByteString str
cast' (Bin (Binary str)) = Just str
cast' (Fun (Function str)) = Just str
cast' _ = Nothing
-- |Convert JSON into Bson Value. See Also: 'toBsonHook'
toBson :: JSON a => a -> Value
toBson = fromJust . fromJSON . toJSON
-- |Convert Bson into JSON Value.
fromBson :: JSON a => Value -> Maybe a
fromBson = fromJSON . toJSON
-- |Field name specific version 'toBson'.
toBsonHook :: JSON a => [(ByteString, JSValue -> Maybe Value)] -> a -> Value
toBsonHook fs = sub . toJSON
where
sub (JSObject dic) = Doc $
mapMaybe (\(k, v) -> (fromByteString_ k :=) <$> ((P.lookup k fs >>= ($v)) <|> (Just . toBson $ v)) ) $ toList dic
sub a = toBson a | konn/libkonn | src/Text/JSON/AttoJSON/Bson.hs | bsd-3-clause | 3,524 | 0 | 18 | 938 | 1,274 | 650 | 624 | 69 | 2 |
import Text.Pandoc.JSON
import Text.Pandoc.Walk
import Data.Monoid
-- http://stackoverflow.com/questions/26406816/pandoc-is-there-a-way-to-include-an-appendix-of-links-in-a-pdf-from-markdown/26415375#26415375
main :: IO ()
main = toJSONFilter appendLinkTable
appendLinkTable :: Pandoc -> Pandoc
appendLinkTable (Pandoc m bs) = Pandoc m (bs ++ linkTable bs)
linkTable :: [Block] -> [Block]
linkTable p = [Header 2 ("linkTable", [], []) [Str "Links"] , Para links]
where
links = concatMap makeRow $ query getLink p
getLink (Link txt (url, _)) = [(url,txt)]
getLink _ = []
makeRow (url, txt) = txt ++ [Str ":", Space, Link [Str url] (url, ""), LineBreak]
| psteinb/gtc2017 | tools/filters/linkTable.hs | bsd-3-clause | 674 | 0 | 11 | 107 | 245 | 133 | 112 | 13 | 2 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Duration.GA.Corpus
( corpus
) where
import Prelude
import Data.String
import Duckling.Duration.Types
import Duckling.Lang
import Duckling.Resolve
import Duckling.Testing.Types
import Duckling.TimeGrain.Types (Grain(..))
corpus :: Corpus
corpus = (testContext {lang = GA}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (DurationData 1 Second)
[ "aon soicind amhain"
, "aon soicind"
, "1 tshoicindi"
, "1 tsoicind"
]
, examples (DurationData 30 Minute)
[ "leathuair"
, "30 noimead"
]
, examples (DurationData 14 Day)
[ "coicís"
]
]
| rfranek/duckling | Duckling/Duration/GA/Corpus.hs | bsd-3-clause | 1,056 | 0 | 9 | 282 | 174 | 107 | 67 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Config() where
| wfaler/mywai | src/Web/Config.hs | bsd-3-clause | 61 | 0 | 3 | 7 | 10 | 7 | 3 | 2 | 0 |
{-# LANGUAGE RecordWildCards #-}
module Website where
import Data.Char (toLower)
import Data.Function (on)
import Data.List (find, groupBy, nub, sort)
import Data.Version (showVersion, versionBranch)
import Development.Shake
import Text.Hastache
import Text.Hastache.Context
import Dirs
import Paths
import PlatformDB
import Releases
import ReleaseFiles
import Templates
import Types
websiteRules :: FilePath -> Rules ()
websiteRules templateSite = do
websiteDir */> \dst -> do
bcCtx <- buildConfigContext
let rlsCtx = releasesCtx
ctx = ctxConcat [rlsCtx, historyCtx, bcCtx, errorCtx]
copyExpandedDir ctx templateSite dst
fileCtx :: (Monad m) => FileInfo -> MuContext m
fileCtx (dist, url, mHash) = mkStrContext ctx
where
ctx "osNameAndArch" = MuVariable $ distName dist
ctx "url" = MuVariable url
ctx "mHash" = maybe (MuBool False) MuVariable mHash
ctx "isOSX" = MuBool $ distIsFor OsOSX dist
ctx "isWindows" = MuBool $ distIsFor OsWindows dist
ctx "isLinux" = MuBool $ distIsFor OsLinux dist
ctx "isSource" = MuBool $ dist == DistSource
ctx _ = MuNothing
releaseCtx :: (Monad m) => ReleaseFiles -> MuContext m
releaseCtx (ver, (month, year), files) = mkStrContext ctx
where
ctx "version" = MuVariable ver
ctx "year" = MuVariable $ show year
ctx "month" = MuVariable $ monthName month
ctx "files" = mapListContext fileCtx files
ctx _ = MuNothing
releasesCtx :: (Monad m) => MuContext m
releasesCtx = mkStrContext ctx
where
ctx "years" = mapListStrContext yearCtx years
ctx "current" = MuList [releaseCtx currentFiles]
ctx _ = MuNothing
yearCtx [] _ = MuBool False
yearCtx (r0:_) "year" = MuVariable $ show $ releaseYear r0
yearCtx rs "releases" = mapListContext releaseCtx rs
yearCtx _ _ = MuNothing
years = groupBy ((==) `on` releaseYear) priorFiles
releaseYear :: ReleaseFiles -> Int
releaseYear (_ver, (_month, year), _files) = year
monthName :: Int -> String
monthName i = maybe (show i) id $ lookup i monthNames
where
monthNames = zip [1..] $
words "January Feburary March April May June \
\July August September October November December"
historyCtx :: (Monad m) => MuContext m
historyCtx = mkStrContext outerCtx
where
outerCtx "history" = MuList [mkStrContext ctx]
outerCtx _ = MuNothing
ctx "hpReleases" = mapListStrContext rlsCtx releasesNewToOld
ctx "ncols" = MuVariable $ length releasesNewToOld + 1
ctx "sections" = MuList
[ sectionCtx "Compiler" [isGhc, not . isLib]
, sectionCtx "Core Libraries, Provided with GHC" [isGhc, isLib]
, sectionCtx "Additional Platform Libraries" [not . isGhc, isLib]
, sectionCtx "Programs and Tools" [isTool]
]
ctx _ = MuNothing
rlsCtx rls "hpVersion" = MuVariable . showVersion . hpVersion . relVersion $ rls
rlsCtx _ _ = MuNothing
sectionCtx :: (Monad m) => String -> [IncludeType -> Bool] -> MuContext m
sectionCtx name tests = mkStrContext ctx
where
ctx "name" = MuVariable name
ctx "components" = mapListStrContext pCtx packages
ctx _ = MuNothing
packages = sortOnLower . nub . map pkgName . concat $
map (packagesByIncludeFilter $ \i -> all ($i) tests)
releasesNewToOld
sortOnLower = map snd . sort . map (\s -> (map toLower s, s))
pCtx pName "package" = MuVariable pName
pCtx pName "hackageUrl" =
MuVariable $ "http://hackage.haskell.org/package/" ++ pName
pCtx pName "releases" = mapListStrContext pvCtx $ packageVersionInfo pName
pCtx _ _ = MuNothing
pvCtx (c, _) "class" = MuVariable c
pvCtx (_, v) "version" = MuVariable v
pvCtx _ _ = MuNothing
packageVersionInfo :: String -> [(String, String)]
packageVersionInfo pName = curr $ zipWith comp vers (drop 1 vers ++ [Nothing])
where
comp Nothing _ = ("missing", "—")
comp (Just v) Nothing = ("update", showVersion v)
comp (Just v) (Just w) | maj v == maj w = ("same", showVersion v)
| otherwise = ("update", showVersion v)
maj = take 3 . versionBranch
curr ((c, v) : cvs) = (c ++ " current", v) : cvs
curr [] = []
vers = map (fmap pkgVersion . find ((==pName) . pkgName) . map snd . relIncludes)
releasesNewToOld
releasesNewToOld :: [Release]
releasesNewToOld = reverse releases
| thomie/haskell-platform | hptool/src/Website.hs | bsd-3-clause | 4,521 | 0 | 15 | 1,156 | 1,449 | 748 | 701 | 100 | 8 |
module Reflex.Monad.Time
( MonadTime (..)
, delay_
, animate
, animateClip
, animateOn
, play
, playClip
, playClamp
, playOn
, match
, matchBy
, pushFor
) where
import Reflex.Animation
import Reflex.Monad
import Reflex
import Data.VectorSpace
import Data.Functor
import Control.Applicative
import qualified Data.List.NonEmpty as NE
import Data.List.NonEmpty (NonEmpty)
import Control.Monad
class (MonadReflex t m, RealFrac time) => MonadTime t time m | m -> t time where
-- | A behavior for time, must be up to date
-- (i.e. represents current time not previous time)
getTime :: m (Behavior t time)
-- | Fire an event at or just after a period of time
after :: time -> m (Event t ())
-- | Delay an event by a period of time, returns a list in case
-- two delayed events occur within the sampling rate of the framework
delay :: Event t (a, time) -> m (Event t (NonEmpty a))
-- | Delay a void event stream
delay_ :: (MonadTime t time m) => Event t time -> m (Event t ())
delay_ e = void <$> delay (((), ) <$> e)
-- | Sample a Clip during it's period, outside it's period return Nothing
animateClip :: (Reflex t, RealFrac time) => Clip time a -> Behavior t time -> Behavior t (Maybe a)
animateClip clip = animate $ toMaybe clip
-- | Animate an infinite animation using framework time
animate :: (Reflex t, RealFrac time) => Animation time a -> Behavior t time -> Behavior t a
animate anim time = sampleAt anim <$> time
-- | Helper for animateOn using the underlying representation (time -> a)
sampleOn :: (Reflex t, RealFrac time) => Event t (time -> a) -> Behavior t time -> Event t (Behavior t a)
sampleOn e t = attachWith startAt t e where
startAt start f = f . subtract start <$> t
-- | Create a Behavior from an infinite animation on the occurance of the event
animateOn :: (Reflex t, RealFrac time) => Event t (Animation time a) -> Behavior t time -> Event t (Behavior t a)
animateOn e = sampleOn (sampleAt <$> e)
-- | Record time offset from the current time
fromNow :: MonadTime t time m => m (Behavior t time)
fromNow = do
time <- getTime
start <- sample time
return (subtract start <$> time)
-- | Play an animation clip, giving a Behavior of it's value and an Event firing as it finishes
playClip :: MonadTime t time m => Clip time a -> m (Behavior t (Maybe a), Event t ())
playClip clip = do
(b, done) <- playClamp clip
b' <- switcher (Just <$> b) (constant Nothing <$ done)
return (b', done)
-- | Play an animation clip, except clamp the ends so the Behavior is no longer 'Maybe a'
playClamp :: MonadTime t time m => Clip time a -> m (Behavior t a, Event t ())
playClamp clip = do
b <- play (clamped clip)
done <- after (period clip)
return (b, done)
-- | Play an infinite animation starting now
play :: MonadTime t time m => Animation time a -> m (Behavior t a)
play anim = do
time <- fromNow
return (sampleAt anim <$> time)
-- | Play an animation clip starting on the occurance of an Event
-- if another play event occurs before the last one has finished, switch to that one instead.
playOn :: MonadTime t time m => Event t (Clip time a) -> m (Behavior t (Maybe a), Event t ())
playOn e = do
time <- getTime
done <- delay_ (period <$> e)
b <- hold (constant Nothing) $
leftmost [constant Nothing <$ done, fmap Just <$> animateOn (clamped <$> e) time]
return (join b, done)
-- | Helper functions using filter with Eq
match :: (Reflex t, Eq a) => a -> Event t a -> Event t ()
match a = matchBy (== a)
matchBy :: (Reflex t) => (a -> Bool) -> Event t a -> Event t ()
matchBy f = void . ffilter f
-- | Helper for pushAlways
pushFor :: Reflex t => Event t a -> (a -> PushM t b) -> Event t b
pushFor = flip pushAlways
| Saulzar/reflex-animation | src/Reflex/Monad/Time.hs | bsd-3-clause | 3,834 | 0 | 14 | 917 | 1,269 | 645 | 624 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
module Main (main) where
import Data.Binary.Get
import qualified Data.ByteString.Lazy as BL
import Data.List
import Data.List.Split
import Text.Printf
import Codec.Tracker.XM
import Codec.Tracker.XM.Header
import Codec.Tracker.XM.Instrument
import Codec.Tracker.XM.Pattern
n2key :: Int -> String
n2key 97 = "###"
n2key n = ((cycle notes) !! (n - 1)) ++ (show $ div n 12)
where notes = ["C ","C#","D ","D#","E ","F ","F#","G ","G#","A ","A#","B "]
pprintInstrument :: Instrument -> IO ()
pprintInstrument Instrument{..} = do
BL.putStr $ BL.pack instrumentName
putStrLn $ " (" ++ show sampleNum ++ ")"
pprintHeader :: Header -> IO ()
pprintHeader Header{..} = do
putStr "Song name.......: "
BL.putStrLn $ BL.pack songName
putStr "Tracker name....: "
BL.putStrLn $ BL.pack trackerName
putStrLn $ "Version.........: " ++ show version
putStrLn $ "Orders..........: " ++ show songLength
putStrLn $ "Restart position: " ++ show restartPosition
putStrLn $ "Instruments.....: " ++ show numInstruments
putStrLn $ "Channels........: " ++ show numChannels
putStrLn $ "Patterns........: " ++ show numPatterns
putStrLn $ "Initial speed...: " ++ show initialSpeed
putStrLn $ "Initial tempo...: " ++ show initialTempo
pprintPattern :: Int -> Pattern -> IO ()
pprintPattern n Pattern{..} = do
putStrLn $ "Packed size: " ++ show packedSize ++ " Rows: " ++ show numRows
mapM_ putStrLn (map (foldr (++) ([])) (map (intersperse " | ") (chunksOf n (map show patternData))))
main :: IO ()
main = do
file <- BL.getContents
let xm = runGet getModule file
putStrLn "Header:"
putStrLn "======="
pprintHeader $ header xm
putStrLn "<>"
print (orders xm)
putStrLn "<>"
putStrLn "Instruments:"
putStrLn "============"
mapM_ pprintInstrument (instruments xm)
putStrLn "<>"
putStrLn "Patterns:"
putStrLn "========="
mapM_ (pprintPattern $ fromIntegral . numChannels . header $ xm) (patterns xm)
putStrLn "<>"
| riottracker/modfile | examples/readXM.hs | bsd-3-clause | 2,138 | 0 | 15 | 504 | 699 | 341 | 358 | 55 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE UnliftedFFITypes #-}
{-# LANGUAGE GHCForeignImportPrim #-}
{-# LANGUAGE UnboxedTuples #-}
-- #if !MIN_VERSION_base(4,8,0)
-- {-# LANGUAGE OverlappingInstances #-}
-- #endif
module Servant.Isomaniac where
-- #if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
-- #endif
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TQueue (TQueue, newTQueue, readTQueue, writeTQueue)
import Control.Concurrent.STM.TMVar (TMVar, newEmptyTMVar, putTMVar, takeTMVar)
import Control.Monad
import Control.Monad.Trans.Except
import Data.Aeson (FromJSON, ToJSON, decodeStrict, encode)
import qualified Data.ByteString as B
import Data.ByteString.Lazy (ByteString, fromStrict, toStrict)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Functor.Identity (Identity(..))
import qualified Data.Text.Encoding as Text
import Data.List
import Data.Proxy
import Data.String.Conversions
import Data.Text (Text, unpack, pack)
import qualified Data.JSString as JS
import GHC.TypeLits
import GHCJS.Buffer (toByteString, fromByteString, getArrayBuffer, createFromArrayBuffer)
import qualified GHCJS.Buffer as Buffer
import GHCJS.Foreign.Callback
import GHCJS.Marshal (FromJSVal(..))
import GHCJS.Marshal.Pure (PFromJSVal(..), PToJSVal(..))
import JavaScript.Cast (unsafeCast)
import GHCJS.Types (JSVal(..), isNull, isUndefined)
import GHCJS.Buffer (freeze)
import JavaScript.Web.MessageEvent as WebSockets
import JavaScript.Web.WebSocket (WebSocket, WebSocketRequest(..))
-- import JavaScript.TypedArray.ArrayBuffer.Internal
import qualified JavaScript.Web.WebSocket as WebSockets
import JavaScript.TypedArray.ArrayBuffer (ArrayBuffer, MutableArrayBuffer)
import qualified JavaScript.TypedArray.ArrayBuffer as ArrayBuffer
-- import GHCJS.Buffer (SomeArrayBuffer(..))
-- import Network.HTTP.Isomaniac (Response, Manager)
-- import Network.HTTP.Media
-- import qualified Network.HTTP.Types as H
-- import qualified Network.HTTP.Types.Header as HTTP
import Servant.API hiding (getResponse)
import Servant.Common.BaseUrl
import Servant.Common.Req
import Network.HTTP.Media (renderHeader)
import Web.HttpApiData
-- import JavaScript.TypedArray.ArrayBuffer.Internal (SomeArrayBuffer(..))
import Web.ISO.Diff
import Web.ISO.Patch
import Web.ISO.Types
import GHC.Exts (State#)
data ReqAction action
= ReqAction Req (B.ByteString -> Maybe action)
instance Functor ReqAction where
fmap f (ReqAction req decoder) = ReqAction req (\json -> fmap f (decoder json))
data MUV m model ioData action remote = MUV
{ model :: model
, browserIO :: TQueue action -> action -> model -> IO ioData
, update :: action -> ioData -> model -> (model, Maybe remote)
, view :: model -> (HTML action, [Canvas])
}
class HasIsomaniac layout where
type Isomaniac layout :: *
isomaniacWithRoute :: Proxy layout -> Req -> BaseUrl -> Isomaniac layout
isomaniac :: (HasIsomaniac layout) => Proxy layout -> BaseUrl -> Isomaniac layout
isomaniac p baseURL = isomaniacWithRoute p defReq baseURL
instance (HasIsomaniac a, HasIsomaniac b) => HasIsomaniac (a :<|> b) where
type Isomaniac (a :<|> b) = Isomaniac a :<|> Isomaniac b
isomaniacWithRoute Proxy req baseurl =
isomaniacWithRoute (Proxy :: Proxy a) req baseurl :<|>
isomaniacWithRoute (Proxy :: Proxy b) req baseurl
instance (KnownSymbol capture, ToHttpApiData a, HasIsomaniac sublayout)
=> HasIsomaniac (Capture capture a :> sublayout) where
type Isomaniac (Capture capture a :> sublayout) =
a -> Isomaniac sublayout
isomaniacWithRoute Proxy req baseurl val =
isomaniacWithRoute (Proxy :: Proxy sublayout)
(appendToPath p req)
baseurl
where p = toUrlPiece val
-- | If you have a 'Put' endpoint in your API, the client
-- side querying function that is created when calling 'client'
-- will just require an argument that specifies the scheme, host
-- and port to send the request to.
instance
{-# OVERLAPPABLE #-}
(FromJSON a, MimeUnrender ct a) => HasIsomaniac (Put (ct ': cts) a) where
type Isomaniac (Put (ct ': cts) a) = ReqAction a
isomaniacWithRoute Proxy req baseurl =
ReqAction (req { method = "POST" }) decodeStrict
instance
{-# OVERLAPPING #-}
HasIsomaniac (Put (ct ': cts) ()) where
type Isomaniac (Put (ct ': cts) ()) = ReqAction ()
isomaniacWithRoute Proxy req baseurl =
ReqAction (req { method = "POST" }) (const (Just ()))
{-
-- | If you have a 'Put xs (Headers ls x)' endpoint, the client expects the
-- corresponding headers.
instance
{-# OVERLAPPING #-}
( MimeUnrender ct a, BuildHeadersTo ls
) => HasIsomaniac (Put (ct ': cts) (Headers ls a)) where
type Isomaniac (Put (ct ': cts) (Headers ls a)) = Req
clientWithRoute Proxy req baseurl manager= do
(hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodPut req baseurl manager
return $ Headers { getResponse = resp
, getHeadersHList = buildHeadersTo hdrs
}
-}
instance {-# OVERLAPPABLE #-}
(FromJSON a, MimeUnrender ct a, cts' ~ (ct ': cts)) => HasIsomaniac (Delete cts' a) where
type Isomaniac (Delete cts' a) = ReqAction a
isomaniacWithRoute Proxy req baseurl =
ReqAction (req { method = "DELETE" }) decodeStrict
instance {-# OVERLAPPING #-}
HasIsomaniac (Delete cts ()) where
type Isomaniac (Delete cts ()) = ReqAction ()
isomaniacWithRoute Proxy req baseurl =
ReqAction (req { method = "DELETE" }) (const $ Just ())
{-
-- | If you have a 'Delete xs (Headers ls x)' endpoint, the client expects the
-- corresponding headers.
instance
{-# OVERLAPPING #-}
( FromJSON a, MimeUnrender ct a, BuildHeadersTo ls, cts' ~ (ct ': cts)
) => HasIsomaniac (Delete cts' (Headers ls a)) where
type Isomaniac (Delete cts' (Headers ls a)) = ExceptT ServantError IO (Headers ls a)
isomaniacWithRoute Proxy req baseurl manager = do
(hdrs, resp) <- performRequestCT (Proxy :: Proxy ct) H.methodDelete req baseurl manager
return $ Headers { getResponse = resp
, getHeadersHList = buildHeadersTo hdrs
}
-}
{-
instance (KnownSymbol sym, ToText a, HasIsomaniac sublayout)
=> HasIsomaniac (Header sym a :> sublayout) where
type Isomaniac (Header sym a :> sublayout) =
Maybe a -> Isomaniac sublayout
isomaniacWithRoute Proxy req baseurl mval =
isomaniacWithRoute (Proxy :: Proxy sublayout)
(maybe req
(\value -> Servant.Common.Req.addHeader hname value req)
mval
)
baseurl
manager
where hname = symbolVal (Proxy :: Proxy sym)
-}
instance {-# OVERLAPPABLE #-}
(FromJSON result, MimeUnrender ct result) => HasIsomaniac (Get (ct ': cts) result) where
type Isomaniac (Get (ct ': cts) result) = ReqAction result
isomaniacWithRoute Proxy req baseurl = ReqAction (req { method = "GET" }) decodeStrict
-- snd <$> performRequestCT (Proxy :: Proxy ct) H.methodGet req baseurl manager
-- | If you use a 'ReqBody' in one of your endpoints in your API,
-- the corresponding querying function will automatically take
-- an additional argument of the type specified by your 'ReqBody'.
-- That function will take care of encoding this argument as JSON and
-- of using it as the request body.
--
-- All you need is for your type to have a 'ToJSON' instance.
--
-- Example:
--
-- > type MyApi = "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > addBook :: Book -> ExceptT String IO Book
-- > addBook = client myApi host manager
-- > where host = BaseUrl Http "localhost" 8080
-- > -- then you can just use "addBook" to query that endpoint
instance (MimeRender ct a, HasIsomaniac sublayout)
=> HasIsomaniac (ReqBody (ct ': cts) a :> sublayout) where
type Isomaniac (ReqBody (ct ': cts) a :> sublayout) =
a -> Isomaniac sublayout
isomaniacWithRoute Proxy req baseurl body =
isomaniacWithRoute (Proxy :: Proxy sublayout)
(let ctProxy = Proxy :: Proxy ct
bdy = mimeRender ctProxy body
ct = contentType ctProxy
in req { reqBody = Just (bdy, ct)
{- , headers = ("Content-Type", Text.decodeUtf8 $ renderHeader ct) : (headers req) -}
}) baseurl
{-
isomaniacWithRoute (Proxy :: Proxy sublayout)
(let ctProxy = Proxy :: Proxy ct
in setRQBody (mimeRender ctProxy body)
(contentType ctProxy)
req
)
baseurl manager
-}
-- | Make the querying function append @path@ to the request path.
instance (KnownSymbol path, HasIsomaniac sublayout) => HasIsomaniac (path :> sublayout) where
type Isomaniac (path :> sublayout) = Isomaniac sublayout
isomaniacWithRoute Proxy req =
isomaniacWithRoute (Proxy :: Proxy sublayout) $
appendToPath p req
where p = pack $ symbolVal (Proxy :: Proxy path)
-- | If you have a 'Post' endpoint in your API, the client
-- side querying function that is created when calling 'client'
-- will just require an argument that specifies the scheme, host
-- and port to send the request to.
instance
{-# OVERLAPPABLE #-}
(FromJSON a, MimeUnrender ct a) => HasIsomaniac (Post (ct ': cts) a) where
type Isomaniac (Post (ct ': cts) a) = ReqAction a
isomaniacWithRoute Proxy req baseurl = ReqAction (req { method = "POST" }) decodeStrict
{-
snd <$> performRequestCT (Proxy :: Proxy ct) H.methodPost req baseurl manager
-}
instance
{-# OVERLAPPING #-}
HasIsomaniac (Post (ct ': cts) ()) where
type Isomaniac (Post (ct ': cts) ()) = ReqAction ()
isomaniacWithRoute Proxy req baseurl =
ReqAction (req { method = "POST" }) (const (Just ()))
{-
void $ performRequestNoBody H.methodPost req baseurl manager
-}
-- | If you use a 'QueryParam' in one of your endpoints in your API,
-- the corresponding querying function will automatically take
-- an additional argument of the type specified by your 'QueryParam',
-- enclosed in Maybe.
--
-- If you give Nothing, nothing will be added to the query string.
--
-- If you give a non-'Nothing' value, this function will take care
-- of inserting a textual representation of this value in the query string.
--
-- You can control how values for your type are turned into
-- text by specifying a 'ToText' instance for your type.
--
-- Example:
--
-- > type MyApi = "books" :> QueryParam "author" Text :> Get '[JSON] [Book]
-- >
-- > myApi :: Proxy MyApi
-- > myApi = Proxy
-- >
-- > getBooksBy :: Maybe Text -> ExceptT String IO [Book]
-- > getBooksBy = client myApi host
-- > where host = BaseUrl Http "localhost" 8080
-- > -- then you can just use "getBooksBy" to query that endpoint.
-- > -- 'getBooksBy Nothing' for all books
-- > -- 'getBooksBy (Just "Isaac Asimov")' to get all books by Isaac Asimov
instance (KnownSymbol sym, ToHttpApiData a, HasIsomaniac sublayout)
=> HasIsomaniac (QueryParam sym a :> sublayout) where
type Isomaniac (QueryParam sym a :> sublayout) =
Maybe a -> Isomaniac sublayout
-- if mparam = Nothing, we don't add it to the query string
isomaniacWithRoute Proxy req baseurl mparam =
isomaniacWithRoute (Proxy :: Proxy sublayout) req -- FIMXE actually add the query params
{-
(maybe req
(flip (appendToQueryString pname) req . Just)
mparamText
) -}
baseurl
{-
where pname = cs pname'
pname' = symbolVal (Proxy :: Proxy sym)
mparamText = fmap toQueryParam mparam
-}
mainLoopRemote :: (Show action) =>
-- -> (Text -> action)
(TQueue action -> IO (remote -> IO ()))
-> JSDocument
-> JSNode
-> MUV m model ioData action remote -- (ReqAction action)
-- -> (forall a. m a -> IO a)
-> Maybe action
-> IO ()
mainLoopRemote initRemote document body (MUV model calcIoData update view) {- runM -} mInitAction =
do queue <- atomically newTQueue
let (vdom, canvases) = view model
-- update HTML
html <- renderHTML (handleAction queue) document vdom
removeChildren body
appendChild body html
-- update Canvases
mapM_ drawCanvas canvases
w <- window
-- addEventListener w KeyDown (\e -> js_alert (JS.pack (show (keyCode e))) >> defaultPrevented e >>= \b -> js_alert (JS.pack (show b)) >> preventDefault e >> defaultPrevented e >>= \b -> js_alert (JS.pack (show b)) ) False
-- addEventListener document KeyUp (\e -> defaultPrevented e >>= \b -> js_alert (JS.pack (show b)) >> preventDefault e >> defaultPrevented e >>= \b -> js_alert (JS.pack (show b)) ) False
-- remoteLoop queue xhr
handleRemote <- initRemote queue
case mInitAction of
(Just initAction) ->
handleAction queue initAction
Nothing -> pure ()
loop handleRemote {- xhr -} queue {- decodeVar -} model vdom
where
handleAction queue = \action -> atomically $ writeTQueue queue action
-- remoteLoop queue xhr = forkIO $
-- return ()
loop handleRemote {- xhr -} queue {- decodeVar -} model oldVDom =
do action <- atomically $ readTQueue queue
ioData <- calcIoData queue action model
let (model', mremote') = update action ioData model
let (vdom, canvases) = view model'
diffs = diff oldVDom (Just vdom)
-- putStrLn $ "action --> " ++ show action
-- putStrLn $ "diff --> " ++ show diffs
-- update HTML
apply (handleAction queue) document body oldVDom diffs
-- update Canvases
mapM_ drawCanvas canvases
-- html <- renderHTML (handleAction queue) document vdom
-- removeChildren body
-- appendJSChild body html
case mremote' of
Nothing -> pure ()
(Just remote) -> handleRemote remote
{-
(Just (ReqAction req decoder)) ->
do atomically $ putTMVar decodeVar decoder
open xhr (method req) ({- "http://localhost:8000" <> -} reqPath req) True
setResponseType xhr "arraybuffer" -- FIXME: do we need to do this everytime?
setRequestHeader xhr "Accept" "application/json" -- FIXME, use reqAccept
mapM_ (\(h, v) -> setRequestHeader xhr h v) (headers req)
case reqBody req of
Nothing -> send xhr
(Just (bdy, ct)) ->
do setRequestHeader xhr "Content-Type" (Text.decodeUtf8 $ renderHeader ct)
let (buffer, _, _) = (fromByteString $ toStrict bdy)
sendArrayBuffer xhr buffer
print "xhr sent."
-- mapM_ (\a -> reqAccept (setRequestHeader "Accept"
-- FIXME: QueryString
-}
{-
(Just remote) ->
do open xhr "POST" url True
sendString xhr (textToJSString remote)
-}
loop handleRemote {- xhr -} queue {- decodeVar -} model' vdom
{-
foreign import javascript unsafe
"$2.slice($1)" js_slice1_imm :: Int -> SomeArrayBuffer any -> SomeArrayBuffer any
foreign import javascript unsafe
"$3.slice($1,$2)" js_slice_imm :: Int -> Int -> SomeArrayBuffer any -> SomeArrayBuffer any
slice :: Int -> Maybe Int -> SomeArrayBuffer any -> SomeArrayBuffer any
slice begin (Just end) b = js_slice_imm begin end b
slice begin _ b = js_slice1_imm begin b
{-# INLINE slice #-}
-}
sendRemoteWS :: (ToJSON remote) => WebSocket -> remote -> IO ()
sendRemoteWS ws remote =
do let jstr = JS.pack (C.unpack $ encode remote)
WebSockets.send jstr ws
foreign import javascript unsafe "console[\"log\"]($1)" consoleLog :: JS.JSString -> IO ()
foreign import javascript unsafe "function(buf){ if (!buf) { throw \"checkArrayBuffer: !buf\"; }; if (!(buf instanceof ArrayBuffer)) { throw \"checkArrayBuffer: buf is not an ArrayBuffer\"; }}($1)" checkArrayBuffer :: MutableArrayBuffer -> IO ()
-- if(!buf || !(buf instanceof ArrayBuffer))
-- throw "h$wrapBuffer: not an ArrayBuffer"
-- foreign import javascript unsafe
-- "new ArrayBuffer($1)" js_create :: Int -> State# s -> (# State# s, JSVal #)
foreign import javascript unsafe
"new ArrayBuffer($1)" js_create :: Int -> IO MutableArrayBuffer
create :: Int -> IO MutableArrayBuffer
create n = js_create n
{-# INLINE create #-}
logMessage :: MessageEvent -> IO ()
logMessage messageEvent =
case WebSockets.getData messageEvent of
(StringData str) -> consoleLog str
(ArrayBufferData r) -> do consoleLog "Got ArrayBufferData"
marray <- ArrayBuffer.thaw r
let jsval = (pToJSVal marray)
buf = createFromArrayBuffer r :: Buffer.Buffer
ab <- create 10
checkArrayBuffer marray
consoleLog ("checkArrayBuffer passed.")
consoleLog (JS.pack (show (isUndefined jsval)))
consoleLog (JS.pack (show (isNull jsval)))
consoleLog (JS.pack (show (toByteString 0 Nothing buf)))
-- -- (show ((decodeStrict (toByteString 0 Nothing (createFromArrayBuffer r))) :: Maybe WebSocketRes)))
incomingWS :: (MessageEvent -> Maybe action) -> TQueue action -> MessageEvent -> IO ()
incomingWS decodeAction queue messageEvent =
do logMessage messageEvent
case decodeAction messageEvent of
Nothing -> consoleLog "Failed to decode messageEvent"
(Just action) -> atomically $ writeTQueue queue action
initRemoteWS :: (ToJSON remote) => JS.JSString -> (MessageEvent -> Maybe action) -> TQueue action -> IO (remote -> IO ())
initRemoteWS url' decodeAction queue =
do let request = WebSocketRequest { url = url'
, protocols = []
, onClose = Nothing
, onMessage = Just (incomingWS decodeAction queue)
}
ws <- WebSockets.connect request
pure (sendRemoteWS ws)
initRemoteXHR :: TQueue action -> IO (ReqAction action -> IO ())
initRemoteXHR queue =
do decodeVar <- atomically newEmptyTMVar
-- xhr request
xhr <- newXMLHttpRequest
-- cb <- asyncCallback (handleXHR queue decodeVar xhr)
addEventListener xhr ProgressLoad (\e -> handleXHR queue decodeVar xhr) False
pure (sendRemoteXHR xhr decodeVar)
where
handleXHR queue decodeVar xhr =
do -- FIXME: check status
rs <- getReadyState xhr
putStrLn $ "xhr ready state = " ++ show rs
status <- getStatus xhr
putStrLn $ "xhr status = " ++ show status
case rs of
4 -> do decode <- atomically $ takeTMVar decodeVar
txt <- getResponseType xhr
print txt
txt <- getStatusText xhr
print txt
ref <- getResponse xhr
if isNull ref
then print "response was null."
else pure ()
buf <- Buffer.createFromArrayBuffer <$> (ArrayBuffer.unsafeFreeze $ pFromJSVal ref)
let bs = toByteString 0 Nothing buf
case decode bs of
Nothing -> return ()
(Just action) ->
atomically $ writeTQueue queue action
_ -> pure ()
sendRemoteXHR :: XMLHttpRequest -> TMVar (B.ByteString -> Maybe action) -> ReqAction action -> IO ()
sendRemoteXHR xhr decodeVar (ReqAction req decoder) =
do atomically $ putTMVar decodeVar decoder
open xhr (method req) ({- "http://localhost:8000" <> -} reqPath req) True
setResponseType xhr "arraybuffer" -- FIXME: do we need to do this everytime?
setRequestHeader xhr "Accept" "application/json" -- FIXME, use reqAccept
mapM_ (\(h, v) -> setRequestHeader xhr h v) (headers req)
case reqBody req of
Nothing -> send xhr
(Just (bdy, ct)) ->
do setRequestHeader xhr "Content-Type" (Text.decodeUtf8 $ renderHeader ct)
let (buffer, _, _) = (fromByteString $ toStrict bdy)
sendArrayBuffer xhr buffer
print "xhr sent."
-- mapM_ (\a -> reqAccept (setRequestHeader "Accept"
-- FIXME: QueryString
muv :: (Show action) =>
MUV m model ioData action (ReqAction action)
-- -> (forall a. m a -> IO a)
-> Maybe action
-> IO ()
muv muv {- runM -} initAction =
do (Just document) <- currentDocument
murvElem
<- do mmurv <- getElementById document "murv"
case mmurv of
(Just murv) -> return (toJSNode murv)
Nothing ->
do (Just bodyList) <- getElementsByTagName document "body"
(Just body) <- item bodyList 0
return body
mainLoopRemote initRemoteXHR document murvElem muv {- runM -} initAction
muvWS :: (Show action, ToJSON remote) =>
MUV m model ioData action remote
-- -> (forall a. m a -> IO a)
-> JS.JSString
-> (MessageEvent -> Maybe action)
-> Maybe action
-> IO ()
muvWS muv {- runM -} url decodeAction initAction =
do (Just document) <- currentDocument
murvElem
<- do mmurv <- getElementById document "murv"
case mmurv of
(Just murv) -> return (toJSNode murv)
Nothing ->
do (Just bodyList) <- getElementsByTagName document "body"
(Just body) <- item bodyList 0
return body
mainLoopRemote (initRemoteWS url decodeAction) document murvElem muv {- runM -} initAction
runIdent :: Identity a -> IO a
runIdent = pure . runIdentity
| stepcut/servant-isomaniac | Servant/Isomaniac.hs | bsd-3-clause | 23,331 | 9 | 18 | 6,793 | 4,172 | 2,190 | 1,982 | 297 | 4 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
module Network.Mattermost.Lenses where
import Network.Mattermost.Types.Internal
import Network.Mattermost.Types
import Network.Mattermost.WebSocket.Types
import Network.Mattermost.TH
-- | This is the same type alias as in @Control.Lens@, and so can be used
-- anywhere lenses are needed.
type Lens' a b = forall f. Functor f => (b -> f b) -> (a -> f a)
-- * 'ConnectionData' lenses
suffixLenses ''ConnectionData
-- * 'Login' lenses
suffixLenses ''Login
-- * 'Team' lenses
suffixLenses ''Team
-- * 'TeamMember' lenses
suffixLenses ''TeamMember
-- * 'NotifyProps' lenses
suffixLenses ''NotifyProps
-- * 'Channel' lenses
suffixLenses ''Channel
-- * 'ChannelData' lenses
suffixLenses ''ChannelData
-- * 'User' lenses
suffixLenses ''User
-- * 'Post' lenses
suffixLenses ''Post
-- * 'PostProps' lenses
suffixLenses ''PostProps
suffixLenses ''PostPropAttachment
-- * 'PendingPost' lenses
suffixLenses ''PendingPost
-- * 'Posts' lenses
suffixLenses ''Posts
-- * 'Reaction' lenses
suffixLenses ''Reaction
-- * 'WebsocketEvent' lenses
suffixLenses ''WebsocketEvent
-- * 'WEData' lenses
suffixLenses ''WEData
-- * 'WEBroadcast' lenses
suffixLenses ''WEBroadcast
-- * 'CommandResponse' lenses
suffixLenses ''CommandResponse
suffixLenses ''CommandResponseType
| dagit/mattermost-api | src/Network/Mattermost/Lenses.hs | bsd-3-clause | 1,328 | 0 | 10 | 185 | 250 | 125 | 125 | 27 | 0 |
module Language.Iso.Target.Ruby where
import Language.Iso.App
import Language.Iso.Fls
import Language.Iso.Ite
import Language.Iso.Tru
import Language.Iso.Var
newtype Ruby = Ruby { runRuby :: String }
instance Show Ruby where
show (Ruby js) = js
instance Var Ruby where
var x = Ruby x
instance App Ruby where
app f x = Ruby $ "(" ++ runRuby f ++ ")(" ++ runRuby x ++ ")"
instance Fls Ruby where
fls = Ruby $ "false"
instance Tru Ruby where
tru = Ruby $ "true"
instance Ite Ruby where
ite b t f = Ruby $
"if " ++ runRuby b ++
" then " ++ runRuby t ++
" else " ++ runRuby f ++
" end"
| joneshf/iso | src/Language/Iso/Target/Ruby.hs | bsd-3-clause | 661 | 0 | 12 | 192 | 227 | 121 | 106 | 23 | 0 |
{-|
Module : Database.Taxi.Segment.InMemorySegment
Description : Operations on the in-memory segment
Stability : Experimental
Maintainer : guha.rabishankar@gmail.com
-}
module Database.Taxi.Segment.InMemorySegment where
import Data.Binary (Binary)
import Data.Maybe (fromMaybe)
import Data.Set (Set)
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Trie as T
import Database.Taxi.Prelude
import Database.Taxi.Segment.Flush as F
import Database.Taxi.Segment.Types
empty :: InMemorySegment p
empty = InMemorySegment T.empty
insert :: Ord p => InMemorySegment p -> Text -> p -> InMemorySegment p
insert (InMemorySegment trie) term p =
InMemorySegment $ T.insert termBS postings trie
where
postings = case T.lookup termBS trie of
Nothing -> S.singleton p
Just val -> S.insert p val
termBS = toByteString term
lookup :: InMemorySegment p -> Text -> Set p
lookup (InMemorySegment trie) term =
fromMaybe S.empty $ T.lookup (toByteString term) trie
flush :: (Binary p, Binary doc, Ord doc)
=> InMemorySegment p
-> FilePath
-> Set doc
-> (Set p -> Set doc -> (Set p, Set doc))
-> IO (ExternalSegment p, Set doc)
flush = F.flush
| rabisg/taxi | Database/Taxi/Segment/InMemorySegment.hs | bsd-3-clause | 1,419 | 0 | 14 | 436 | 375 | 198 | 177 | 29 | 2 |
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
module Ivory.Language.MemArea where
import Prelude ()
import Prelude.Compat
import Ivory.Language.Area
import Ivory.Language.Init
import Ivory.Language.Proxy
import Ivory.Language.Ref
import Ivory.Language.Scope
import Ivory.Language.Type
import qualified Ivory.Language.Syntax as I
import qualified MonadLib as M
import qualified MonadLib.Derive as M
-- Running Initializers --------------------------------------------------------
-- | This is used to generate fresh names for compound initializers.
newtype AreaInitM a = AreaInitM
{ unAreaInitM :: M.ReaderT String (M.StateT Int M.Id) a }
areaInit_iso :: M.Iso (M.ReaderT String (M.StateT Int M.Id)) AreaInitM
areaInit_iso = M.Iso AreaInitM unAreaInitM
instance Functor AreaInitM where
fmap = M.derive_fmap areaInit_iso
{-# INLINE fmap #-}
instance Applicative AreaInitM where
pure = M.derive_pure areaInit_iso
(<*>) = M.derive_apply areaInit_iso
{-# INLINE pure #-}
{-# INLINE (<*>) #-}
instance Monad AreaInitM where
return = pure
(>>=) = M.derive_bind areaInit_iso
{-# INLINE return #-}
{-# INLINE (>>=) #-}
instance M.ReaderM AreaInitM String where
ask = M.derive_ask areaInit_iso
{-# INLINE ask #-}
instance M.StateM AreaInitM Int where
get = M.derive_get areaInit_iso
set = M.derive_set areaInit_iso
{-# INLINE get #-}
{-# INLINE set #-}
instance FreshName AreaInitM where
freshName s = do
i <- M.get
M.set $! i + 1
name <- M.ask
return (I.VarLitName ("_iv_" ++ name ++ "_" ++ s ++ show i))
runAreaInitM :: String -> AreaInitM a -> a
runAreaInitM s x = fst (M.runId (M.runStateT 0 (M.runReaderT s(unAreaInitM x))))
areaInit :: String -> Init area -> (I.Init, [Binding])
areaInit s ini = runAreaInitM s (runInit (getInit ini))
-- Memory Areas ----------------------------------------------------------------
-- | Externally defined memory areas.
data MemArea (area :: Area *)
= MemImport I.AreaImport
| MemArea I.Area [I.Area]
deriving (Eq, Show)
-- XXX do not export
memSym :: MemArea area -> I.Sym
memSym m = case m of
MemImport i -> I.aiSym i
MemArea a _ -> I.areaSym a
-- | Create an area from an auxillary binding.
bindingArea :: Bool -> Binding -> I.Area
bindingArea isConst b = I.Area
{ I.areaSym = bindingSym b
, I.areaConst = isConst
, I.areaType = bindingType b
, I.areaInit = bindingInit b
}
makeArea :: I.Sym -> Bool -> I.Type -> I.Init -> I.Area
makeArea sym isConst ty ini = I.Area
{ I.areaSym = sym
, I.areaConst = isConst
, I.areaType = ty
, I.areaInit = ini
}
-- | Define a global constant. Requires an IvoryZero constraint to ensure the
-- area has an initializers, but does not explicilty initialize to 0 so that the
-- value is placed in the .bss section.
area :: forall area. (IvoryArea area, IvoryZero area)
=> I.Sym -> Maybe (Init area) -> MemArea area
area sym (Just ini) = MemArea a1 as
where
(ini', binds) = areaInit sym ini
ty = ivoryArea (Proxy :: Proxy area)
a1 = makeArea sym False ty ini'
as = map (bindingArea False) binds
area sym Nothing = MemArea a1 []
where
ty = ivoryArea (Proxy :: Proxy area)
a1 = makeArea sym False ty I.zeroInit
-- | Import an external symbol from a header.
importArea :: IvoryArea area => I.Sym -> String -> MemArea area
importArea name header = MemImport I.AreaImport
{ I.aiSym = name
, I.aiConst = False
, I.aiFile = header
}
-- Constant Memory Areas -------------------------------------------------------
newtype ConstMemArea (area :: Area *) = ConstMemArea (MemArea area)
-- | Constant memory area definition.
constArea :: forall area. IvoryArea area
=> I.Sym -> Init area -> ConstMemArea area
constArea sym ini = ConstMemArea $ MemArea a1 as
where
(ini', binds) = areaInit sym ini
ty = ivoryArea (Proxy :: Proxy area)
a1 = makeArea sym True ty ini'
as = map (bindingArea True) binds
-- | Import an external symbol from a header.
importConstArea :: IvoryArea area => I.Sym -> String -> ConstMemArea area
importConstArea name header = ConstMemArea $ MemImport I.AreaImport
{ I.aiSym = name
, I.aiConst = False
, I.aiFile = header
}
-- Area Usage ------------------------------------------------------------------
-- | Turn a memory area into a reference.
class IvoryAddrOf (mem :: Area * -> *) ref | mem -> ref, ref -> mem where
addrOf :: IvoryArea area => mem area -> ref 'Global area
-- XXX do not export
primAddrOf :: IvoryArea area => MemArea area -> I.Expr
primAddrOf mem = I.ExpAddrOfGlobal (memSym mem)
instance IvoryAddrOf MemArea Ref where
addrOf mem = wrapExpr (primAddrOf mem)
instance IvoryAddrOf ConstMemArea ConstRef where
addrOf (ConstMemArea mem) = wrapExpr (primAddrOf mem)
| GaloisInc/ivory | ivory/src/Ivory/Language/MemArea.hs | bsd-3-clause | 4,992 | 0 | 15 | 1,003 | 1,391 | 744 | 647 | 109 | 2 |
{-# LANGUAGE RankNTypes #-}
module Language.Angler.Options where
import Language.Angler.Monad (foldActions)
import Control.Lens
import Data.Default (Default(..))
import System.Console.GetOpt (ArgDescr(..), OptDescr(..), usageInfo)
import System.Exit (exitWith, ExitCode(..))
import System.Directory (doesDirectoryExist)
data Options
= Options
{ _opt_warnings :: Bool
-- stages printing
, _opt_options :: Bool
, _opt_tokens :: Bool
, _opt_ast :: Bool
, _opt_mixfix :: Bool
, _opt_compact :: Bool
-- behaviour
, _opt_stdin :: Bool
-- , _opt_symbols :: Bool
-- , _opt_execute :: Bool
-- path managing for module searching
, _opt_stdlib :: Bool
, _opt_path :: [FilePath]
}
makeLenses ''Options
instance Show Options where
show opt = showBoolOpts [ ("warnings", opt_warnings)
, ("stdin", opt_stdin)
, ("stdlib", opt_stdlib) ] ++
"path: " ++ showPaths (view opt_path opt) ++ "\n" ++
showBoolOpts [ ("options", opt_options)
, ("tokens", opt_tokens)
, ("ast", opt_ast)
, ("mixfix", opt_mixfix)
, ("compact", opt_compact) ]
where
showBoolOpts :: [(String, Getting Bool Options Bool)] -> String
showBoolOpts = concatMap (uncurry showBoolOpt)
showBoolOpt :: String -> Getting Bool Options Bool -> String
showBoolOpt desc l = desc ++ ": " ++ (if view l opt then "ON" else "OFF") ++ "\n"
showPaths :: [FilePath] -> String
showPaths = concat . fmap quoteFile
where
quoteFile :: FilePath -> FilePath
quoteFile f = " " ++ if elem ' ' f then "\"" ++ f ++ "\"" else f
instance Default Options where
def = Options
{ _opt_warnings = True
, _opt_options = False
, _opt_tokens = False
, _opt_ast = False
, _opt_mixfix = False
, _opt_compact = False
, _opt_stdin = False
-- , _opt_symbols = False
-- , _opt_execute = True
, _opt_stdlib = True
, _opt_path = ["."] -- search path
}
optionDescrs :: [OptDescr (Options -> IO Options)]
optionDescrs =
[ Option ['h'] ["help"] ((NoArg . const . putLnSuccess) help)
"shows this help message"
, Option ['v'] ["version"] ((NoArg . const . putLnSuccess) version)
"shows version number"
, Option ['w'] ["warnings"] (NoArg (optBool True opt_warnings))
"shows all warnings (default)"
, Option ['W'] ["no-warnings"] (NoArg (optBool False opt_warnings))
"suppress all warnings"
, Option ['i'] ["stdin"] (NoArg (optBool True opt_stdin))
"reads the program to interpret from standard input until EOF ('^D')"
, Option [] ["no-stdin"] (NoArg (optBool False opt_stdin))
"reads the program from a file passed as argument (default)"
, Option [] ["stdlib"] (NoArg (optBool True opt_stdlib))
"adds the standard library to the path (default)"
, Option [] ["no-stdlib"] (NoArg (optBool False opt_stdlib))
"removes the standard library from the path"
, Option ['p'] ["path"] (ReqArg optPath "PATH")
"adds a directory to the path"
, Option ['V'] ["verbose"] (NoArg (optVerbose True))
("to show output for the several stages of interpreting, " ++
"this turns on the following flags: options, tokens, ast, mixfix, compact")
, Option [] ["no-verbose"] (NoArg (optVerbose False))
"avoids showing output for the several stages of interpreting (default)"
, Option [] ["options"] (NoArg (optBool True opt_options))
"shows the options passed to the program"
, Option [] ["no-options"] (NoArg (optBool False opt_options))
"avoids showing the options passed to the program (default)"
, Option [] ["tokens"] (NoArg (optBool True opt_tokens))
"shows the tokens recognized by the lexer"
, Option [] ["no-tokens"] (NoArg (optBool False opt_tokens))
"avoids showing the tokens recognized by the lexer (default)"
, Option [] ["ast"] (NoArg (optBool True opt_ast))
"shows the parsed AST"
, Option [] ["no-ast"] (NoArg (optBool False opt_ast))
"avoids showing the parsed AST (default)"
, Option [] ["mixfix"] (NoArg (optBool True opt_mixfix))
"shows the parsed AST after passing the mixfix parser"
, Option [] ["no-mixfix"] (NoArg (optBool False opt_mixfix))
"avoids showing the parsed AST after passing the mixfix parser (default)"
, Option [] ["compact-ast"] (NoArg (optBool True opt_compact))
"shows the AST after compacting it"
, Option [] ["no-compact-ast"] (NoArg (optBool False opt_compact))
"avoids showing AST after compacting it (default)"
]
where
optVerbose :: Bool -> Options -> IO Options
optVerbose b = foldActions $ fmap (optBool b) [opt_options, opt_tokens, opt_ast, opt_mixfix, opt_compact]
optBool :: Bool -> ASetter' Options Bool -> Options -> IO Options
optBool b lns = return . set lns b
optPath :: String -> Options -> IO Options
optPath dir opt = doesDirectoryExist dir >>= \ans ->
if ans then return (over opt_path (|> dir) opt)
else ioError (userError ("directory '" ++ dir ++ "' does not exist"))
putLnSuccess :: String -> IO Options
putLnSuccess str = putStrLn str >> exitWith ExitSuccess
help :: String
help = flip usageInfo optionDescrs "usage: angler [OPTIONS...] [FILE]\n"
version :: String
version = "Angler version 0.1.0.0"
| angler-lang/angler-lang | src/Language/Angler/Options.hs | bsd-3-clause | 6,518 | 0 | 15 | 2,412 | 1,459 | 801 | 658 | -1 | -1 |
module Main where
import TestUtil
import Test.HUnit hiding (path)
import Database.TokyoCabinet
import Database.TokyoCabinet.Storable
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Int
import Data.Word
import Control.Monad.Trans (liftIO)
e @=?: a = liftIO $ e @=? a
check :: (TCDB tc, Eq a, Storable a) => tc -> a -> a -> TCM ()
check tc k v = do put tc k v
get tc k >>= (Just v @=?:)
iterinit tc
iternext tc >>= (Just k @=?:)
bdb :: TCM BDB
bdb = new
hdb :: TCM HDB
hdb = new
fdb :: TCM FDB
fdb = new
string = "100"
bstring = S.pack "100"
lstring = L.pack "100000"
int = 100 :: Int
int8 = 100 :: Int8
int16 = 100 :: Int16
int32 = 100 :: Int32
int64 = 100 :: Int64
word8 = 100 :: Word8
word16 = 100 :: Word16
word32 = 100 :: Word32
word64 = 100 :: Word64
double = 100 :: Double
float = 100 :: Float
char = '1'
dbname tc = "foo" ++ (defaultExtension tc)
make_check :: (TCDB tc, Eq a, Storable a) => TCM tc -> a -> IO Bool
make_check tcm k = runTCM $ do
tc <- tcm
liftIO $ withoutFile (dbname tc) $ \fn ->
runTCM $ do
open tc fn [OWRITER, OCREAT]
check tc k k
close tc
tests = test [
make_check bdb string
, make_check hdb string
, make_check fdb string
, make_check bdb bstring
, make_check hdb bstring
, make_check fdb bstring
, make_check bdb lstring
, make_check hdb lstring
, make_check fdb lstring
, make_check bdb int
, make_check hdb int
, make_check fdb int
, make_check bdb [int]
, make_check hdb [int]
, make_check fdb [int]
, make_check bdb int8
, make_check hdb int8
, make_check fdb int8
, make_check bdb [int8]
, make_check hdb [int8]
, make_check fdb [int8]
, make_check bdb int16
, make_check hdb int16
, make_check fdb int16
, make_check bdb [int16]
, make_check hdb [int16]
, make_check fdb [int16]
, make_check bdb int32
, make_check hdb int32
, make_check fdb int32
, make_check bdb [int32]
, make_check hdb [int32]
, make_check fdb [int32]
, make_check bdb int64
, make_check hdb int64
, make_check fdb int64
, make_check bdb [int64]
, make_check hdb [int64]
, make_check fdb [int64]
, make_check bdb word8
, make_check hdb word8
, make_check fdb word8
, make_check bdb [word8]
, make_check hdb [word8]
, make_check fdb [word8]
, make_check bdb word16
, make_check hdb word16
, make_check fdb word16
, make_check bdb [word16]
, make_check hdb [word16]
, make_check fdb [word16]
, make_check bdb word32
, make_check hdb word32
, make_check fdb word32
, make_check bdb [word32]
, make_check hdb [word32]
, make_check fdb [word32]
, make_check bdb word64
, make_check hdb word64
, make_check fdb word64
, make_check bdb [word64]
, make_check hdb [word64]
, make_check fdb [word64]
, make_check bdb double
, make_check hdb double
, make_check bdb [double]
, make_check hdb [double]
, make_check bdb float
, make_check hdb float
, make_check bdb [float]
, make_check hdb [float]
, make_check bdb char
, make_check hdb char
, make_check fdb char
, make_check bdb [char]
, make_check hdb [char]
, make_check fdb [char]
]
main = runTestTT tests
| tom-lpsd/tokyocabinet-haskell | tests/StorableTest.hs | bsd-3-clause | 3,896 | 0 | 14 | 1,424 | 1,226 | 650 | 576 | 125 | 1 |
-- File created: 2009-07-26 16:26:13
module Haschoo.Evaluator.Eval (eval, maybeEval, evalBody, define) where
import Control.Monad (msum)
import Control.Monad.Error (throwError, catchError)
import Control.Monad.State (get)
import Control.Monad.Trans (liftIO)
import Data.IORef (IORef, readIORef, modifyIORef)
import qualified Data.ListTrie.Patricia.Map.Enum as TM
import Data.ListTrie.Patricia.Map.Enum (TrieMap)
import Haschoo.Types ( Haschoo
, ScmValue( ScmPrim, ScmFunc, ScmMacro
, ScmList, ScmDottedList
, ScmVoid, ScmIdentifier)
, MacroCall(..)
, Context, addToContext, contextLookup)
import Haschoo.Utils (lazyMapM, modifyM)
import Haschoo.Evaluator.Utils (tooFewArgs)
eval :: ScmValue -> Haschoo ScmValue
eval = evalWithSpecialCases TM.empty
evalWithSpecialCases :: TrieMap Char [IORef Context]
-> ScmValue -> Haschoo ScmValue
evalWithSpecialCases specials (ScmIdentifier s) =
case TM.lookup s specials of
Just specialCtx -> lookupId specialCtx
Nothing -> lookupId =<< get
where
lookupId ctx = do
lookups <- lazyMapM (fmap (contextLookup s) . readIORef) ctx
case msum lookups of
Nothing -> throwError $ "Unbound identifier '" ++ s ++ "'"
Just v -> return v
evalWithSpecialCases _ (ScmList []) = throwError "Empty application"
evalWithSpecialCases sp (ScmList (x:xs)) = do
evaledHead <- evalWithSpecialCases sp x
case evaledHead of
ScmPrim _ f -> f xs
ScmFunc _ f -> do
args <- mapM (evalWithSpecialCases sp) xs
result <- liftIO $ f args
case result of
Left s -> throwError s
Right val -> return val
m@(ScmMacro _ _) -> evalMacro sp m (MCList xs)
_ -> throwError "Can't apply non-function"
evalWithSpecialCases sp (ScmDottedList (x:xs) y) = do
evaledHead <- evalWithSpecialCases sp x
case evaledHead of
m@(ScmMacro _ _) -> evalMacro sp m (MCDotted xs y)
_ -> throwError "Ill-formed procedure application: no dots allowed"
evalWithSpecialCases _ v = return v
evalMacro :: TrieMap Char [IORef Context]
-> ScmValue -> MacroCall -> Haschoo ScmValue
evalMacro sp (ScmMacro _ f) xs = do
(expansion, frees) <- f xs
evalWithSpecialCases (TM.union frees sp) expansion
evalMacro _ _ _ = error "evalMacro :: the impossible happened: not a macro"
maybeEval :: ScmValue -> Haschoo (Maybe ScmValue)
maybeEval = (`catchError` const (return Nothing)) . fmap Just . eval
evalBody :: [ScmValue] -> Haschoo ScmValue
evalBody (ScmList (ScmIdentifier i : xs) : ds)
| i == "define" = scmDefine xs >> evalBody ds
| i == "begin" = evalBody (xs ++ ds)
evalBody ds@(_:_) = fmap last . mapM eval $ ds
evalBody [] = return ScmVoid
define :: String -> ScmValue -> Haschoo ()
define var body = eval body >>= modifyM . f
where
f e (c:cs) = do
liftIO $ modifyIORef c (addToContext var e)
return (c:cs)
f _ [] = error "define :: the impossible happened: empty context stack"
scmDefine :: [ScmValue] -> Haschoo ()
scmDefine [ScmIdentifier var, expr] = define var expr
scmDefine (ScmList (ScmIdentifier func : params) : body) =
define func . ScmList $ ScmIdentifier "lambda" : ScmList params : body
scmDefine (ScmDottedList (ScmIdentifier func : params) final : body) =
define func . ScmList $ ScmIdentifier "lambda"
: (if null params
then final
else ScmDottedList params final)
: body
scmDefine (_:_:_) = throwError "define :: expected identifier"
scmDefine _ = tooFewArgs "define"
| Deewiant/haschoo | Haschoo/Evaluator/Eval.hs | bsd-3-clause | 3,901 | 0 | 15 | 1,136 | 1,223 | 622 | 601 | 80 | 8 |
{-# LANGUAGE PatternGuards #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Elab.Value(elabVal, elabValBind, elabDocTerms,
elabExec, elabREPL) where
import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.DSL
import Idris.Error
import Idris.Delaborate
import Idris.Imports
import Idris.Coverage
import Idris.DataOpts
import Idris.Providers
import Idris.Primitives
import Idris.Inliner
import Idris.PartialEval
import Idris.DeepSeq
import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting)
import IRTS.Lang
import Idris.Elab.Utils
import Idris.Elab.Term
import Idris.Core.TT
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate hiding (Unchecked)
import Idris.Core.Execute
import Idris.Core.Typecheck
import Idris.Core.CaseTree
import Idris.Docstrings
import Prelude hiding (id, (.))
import Control.Category
import Control.Applicative hiding (Const)
import Control.DeepSeq
import Control.Monad
import Control.Monad.State.Strict as State
import Data.List
import Data.Maybe
import qualified Data.Traversable as Traversable
import Debug.Trace
import qualified Data.Map as Map
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Char(isLetter, toLower)
import Data.List.Split (splitOn)
import Util.Pretty(pretty, text)
-- | Elaborate a value, returning any new bindings created (this will only
-- happen if elaborating as a pattern clause)
elabValBind :: ElabInfo -> ElabMode -> Bool -> PTerm -> Idris (Term, Type, [(Name, Type)])
elabValBind info aspat norm tm_in
= do ctxt <- getContext
i <- getIState
let tm = addImpl [] i tm_in
logLvl 10 (showTmImpls tm)
-- try:
-- * ordinary elaboration
-- * elaboration as a Type
-- * elaboration as a function a -> b
(ElabResult tm' defer is ctxt' newDecls highlights, _) <-
tclift (elaborate ctxt (idris_datatypes i) (sMN 0 "val") infP initEState
(build i info aspat [Reflection] (sMN 0 "val") (infTerm tm)))
-- Extend the context with new definitions created
setContext ctxt'
processTacticDecls info newDecls
sendHighlighting highlights
let vtm = orderPats (getInferTerm tm')
def' <- checkDef (fileFC "(input)") iderr defer
let def'' = map (\(n, (i, top, t)) -> (n, (i, top, t, True))) def'
addDeferred def''
mapM_ (elabCaseBlock info []) is
logLvl 3 ("Value: " ++ show vtm)
(vtm_in, vty) <- recheckC (fileFC "(input)") id [] vtm
let vtm = if norm then normalise (tt_ctxt i) [] vtm_in
else vtm_in
let bargs = getPBtys vtm
return (vtm, vty, bargs)
elabVal :: ElabInfo -> ElabMode -> PTerm -> Idris (Term, Type)
elabVal info aspat tm_in
= do (tm, ty, _) <- elabValBind info aspat False tm_in
return (tm, ty)
elabDocTerms :: ElabInfo -> Docstring (Either Err PTerm) -> Idris (Docstring DocTerm)
elabDocTerms info str = do typechecked <- Traversable.mapM decorate str
return $ checkDocstring mkDocTerm typechecked
where decorate (Left err) = return (Left err)
decorate (Right pt) = fmap (fmap fst) (tryElabVal info ERHS pt)
tryElabVal :: ElabInfo -> ElabMode -> PTerm -> Idris (Either Err (Term, Type))
tryElabVal info aspat tm_in
= idrisCatch (fmap Right $ elabVal info aspat tm_in)
(return . Left)
mkDocTerm :: String -> [String] -> String -> Either Err Term -> DocTerm
mkDocTerm lang attrs src (Left err)
| map toLower lang == "idris" = Failing err
| otherwise = Unchecked
mkDocTerm lang attrs src (Right tm)
| map toLower lang == "idris" = if "example" `elem` map (map toLower) attrs
then Example tm
else Checked tm
| otherwise = Unchecked
-- | Try running the term directly (as IO ()), then printing it as an Integer
-- (as a default numeric tye), then printing it as any Showable thing
elabExec :: FC -> PTerm -> PTerm
elabExec fc tm = runtm (PAlternative [] FirstSuccess
[printtm (PApp fc (PRef fc [] (sUN "the"))
[pexp (PConstant NoFC (AType (ATInt ITBig))), pexp tm]),
tm,
printtm tm
])
where
runtm t = PApp fc (PRef fc [] (sUN "run__IO")) [pexp t]
printtm t = PApp fc (PRef fc [] (sUN "printLn"))
[pimp (sUN "ffi") (PRef fc [] (sUN "FFI_C")) False, pexp t]
elabREPL :: ElabInfo -> ElabMode -> PTerm -> Idris (Term, Type)
elabREPL info aspat tm
= idrisCatch (elabVal info aspat tm) catchAmbig
where
catchAmbig (CantResolveAlts _)
= elabVal info aspat (PDisamb [[txt "List"]] tm)
catchAmbig e = ierror e
| athanclark/Idris-dev | src/Idris/Elab/Value.hs | bsd-3-clause | 4,947 | 0 | 19 | 1,359 | 1,525 | 807 | 718 | 104 | 4 |
-- |
-- Module: Database.TinkerPop
-- Copyright: (c) 2015 The gremlin-haskell Authors
-- License : BSD3
-- Maintainer : nakaji.dayo@gmail.com
-- Stability : experimental
-- Portability : non-portable
--
module Database.TinkerPop where
import Database.TinkerPop.Types
import Database.TinkerPop.Internal
import Prelude
import qualified Network.WebSockets as WS
import Control.Exception
import qualified Data.Map.Strict as M
import Data.Text (unpack)
import Data.Aeson (encode, Value)
import qualified Control.Monad.STM as S
import qualified Control.Concurrent.STM.TChan as S
import qualified Control.Concurrent.STM.TVar as S
import qualified Control.Concurrent.MVar as MV
import qualified Data.UUID as U
import qualified Data.UUID.V4 as U
import Control.Lens
-- | Connect to Gremlin Server
run :: String -> Int -> (Connection -> IO ()) -> IO ()
run host port app = do
handle (wsExceptionHandler "main thread") $ WS.runClient host port "/" $ \ws -> do
done <- MV.newEmptyMVar
cs <- S.newTVarIO M.empty
let conn = Connection ws cs
_ <- handler conn done
app conn
close conn
MV.takeMVar done
-- | Send script toGremlin Server and get the result by List
--
-- Individual responses are combined in internal.
submit :: Connection -> Gremlin -> Maybe Binding -> IO (Either String [Value])
submit conn body binding = do
req <- buildRequest body binding
chan <- S.newTChanIO
S.atomically $ S.modifyTVar (conn ^. chans) $ M.insert (req ^. requestId) chan
WS.sendTextData (conn ^. socket) (encode req)
recv chan []
where
recv chan xs = do
eres <- S.atomically $ S.readTChan chan
case eres of
Right r
| inStatus2xx statusCode -> do
let xs' = case (r ^. result ^. data') of
Just d -> xs ++ d
Nothing -> xs
if statusCode == 206 then recv chan xs' else return $ Right xs'
| otherwise -> return $ Left (unpack $ r ^. status ^. message)
where statusCode = (r ^. status ^. code)
Left x -> return $ Left x
-- | Build request data
buildRequest :: Gremlin -> Maybe Binding -> IO RequestMessage
buildRequest body binding = do
uuid <- U.toText <$> U.nextRandom
return $ RequestMessage uuid "eval" "" $
RequestArgs body binding "gremlin-groovy" Nothing
| nakaji-dayo/gremlin-haskell | src/Database/TinkerPop.hs | bsd-3-clause | 2,424 | 0 | 21 | 634 | 688 | 359 | 329 | 50 | 4 |
{-# LINE 1 "GHC.Generics.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Generics
-- Copyright : (c) Universiteit Utrecht 2010-2011, University of Oxford 2012-2014
-- License : see libraries/base/LICENSE
--
-- Maintainer : libraries@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- @since 4.6.0.0
--
-- If you're using @GHC.Generics@, you should consider using the
-- <http://hackage.haskell.org/package/generic-deriving> package, which
-- contains many useful generic functions.
module GHC.Generics (
-- * Introduction
--
-- |
--
-- Datatype-generic functions are based on the idea of converting values of
-- a datatype @T@ into corresponding values of a (nearly) isomorphic type @'Rep' T@.
-- The type @'Rep' T@ is
-- built from a limited set of type constructors, all provided by this module. A
-- datatype-generic function is then an overloaded function with instances
-- for most of these type constructors, together with a wrapper that performs
-- the mapping between @T@ and @'Rep' T@. By using this technique, we merely need
-- a few generic instances in order to implement functionality that works for any
-- representable type.
--
-- Representable types are collected in the 'Generic' class, which defines the
-- associated type 'Rep' as well as conversion functions 'from' and 'to'.
-- Typically, you will not define 'Generic' instances by hand, but have the compiler
-- derive them for you.
-- ** Representing datatypes
--
-- |
--
-- The key to defining your own datatype-generic functions is to understand how to
-- represent datatypes using the given set of type constructors.
--
-- Let us look at an example first:
--
-- @
-- data Tree a = Leaf a | Node (Tree a) (Tree a)
-- deriving 'Generic'
-- @
--
-- The above declaration (which requires the language pragma @DeriveGeneric@)
-- causes the following representation to be generated:
--
-- @
-- instance 'Generic' (Tree a) where
-- type 'Rep' (Tree a) =
-- 'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False)
-- ('S1' '(MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec0' a))
-- ':+:'
-- 'C1' ('MetaCons \"Node\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec0' (Tree a))
-- ':*:'
-- 'S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec0' (Tree a))))
-- ...
-- @
--
-- /Hint:/ You can obtain information about the code being generated from GHC by passing
-- the @-ddump-deriv@ flag. In GHCi, you can expand a type family such as 'Rep' using
-- the @:kind!@ command.
--
-- This is a lot of information! However, most of it is actually merely meta-information
-- that makes names of datatypes and constructors and more available on the type level.
--
-- Here is a reduced representation for 'Tree' with nearly all meta-information removed,
-- for now keeping only the most essential aspects:
--
-- @
-- instance 'Generic' (Tree a) where
-- type 'Rep' (Tree a) =
-- 'Rec0' a
-- ':+:'
-- ('Rec0' (Tree a) ':*:' 'Rec0' (Tree a))
-- @
--
-- The @Tree@ datatype has two constructors. The representation of individual constructors
-- is combined using the binary type constructor ':+:'.
--
-- The first constructor consists of a single field, which is the parameter @a@. This is
-- represented as @'Rec0' a@.
--
-- The second constructor consists of two fields. Each is a recursive field of type @Tree a@,
-- represented as @'Rec0' (Tree a)@. Representations of individual fields are combined using
-- the binary type constructor ':*:'.
--
-- Now let us explain the additional tags being used in the complete representation:
--
-- * The @'S1' ('MetaSel 'Nothing 'NoSourceUnpackedness 'NoSourceStrictness
-- 'DecidedLazy)@ tag indicates several things. The @'Nothing@ indicates
-- that there is no record field selector associated with this field of
-- the constructor (if there were, it would have been marked @'Just
-- \"recordName\"@ instead). The other types contain meta-information on
-- the field's strictness:
--
-- * There is no @{\-\# UNPACK \#-\}@ or @{\-\# NOUNPACK \#-\}@ annotation
-- in the source, so it is tagged with @'NoSourceUnpackedness@.
--
-- * There is no strictness (@!@) or laziness (@~@) annotation in the
-- source, so it is tagged with @'NoSourceStrictness@.
--
-- * The compiler infers that the field is lazy, so it is tagged with
-- @'DecidedLazy@. Bear in mind that what the compiler decides may be
-- quite different from what is written in the source. See
-- 'DecidedStrictness' for a more detailed explanation.
--
-- The @'MetaSel@ type is also an instance of the type class 'Selector',
-- which can be used to obtain information about the field at the value
-- level.
--
-- * The @'C1' ('MetaCons \"Leaf\" 'PrefixI 'False)@ and
-- @'C1' ('MetaCons \"Node\" 'PrefixI 'False)@ invocations indicate that the enclosed part is
-- the representation of the first and second constructor of datatype @Tree@, respectively.
-- Here, the meta-information regarding constructor names, fixity and whether
-- it has named fields or not is encoded at the type level. The @'MetaCons@
-- type is also an instance of the type class 'Constructor'. This type class can be used
-- to obtain information about the constructor at the value level.
--
-- * The @'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)@ tag
-- indicates that the enclosed part is the representation of the
-- datatype @Tree@. Again, the meta-information is encoded at the type level.
-- The @'MetaData@ type is an instance of class 'Datatype', which
-- can be used to obtain the name of a datatype, the module it has been
-- defined in, the package it is located under, and whether it has been
-- defined using @data@ or @newtype@ at the value level.
-- ** Derived and fundamental representation types
--
-- |
--
-- There are many datatype-generic functions that do not distinguish between positions that
-- are parameters or positions that are recursive calls. There are also many datatype-generic
-- functions that do not care about the names of datatypes and constructors at all. To keep
-- the number of cases to consider in generic functions in such a situation to a minimum,
-- it turns out that many of the type constructors introduced above are actually synonyms,
-- defining them to be variants of a smaller set of constructors.
-- *** Individual fields of constructors: 'K1'
--
-- |
--
-- The type constructor 'Rec0' is a variant of 'K1':
--
-- @
-- type 'Rec0' = 'K1' 'R'
-- @
--
-- Here, 'R' is a type-level proxy that does not have any associated values.
--
-- There used to be another variant of 'K1' (namely 'Par0'), but it has since
-- been deprecated.
-- *** Meta information: 'M1'
--
-- |
--
-- The type constructors 'S1', 'C1' and 'D1' are all variants of 'M1':
--
-- @
-- type 'S1' = 'M1' 'S'
-- type 'C1' = 'M1' 'C'
-- type 'D1' = 'M1' 'D'
-- @
--
-- The types 'S', 'C' and 'D' are once again type-level proxies, just used to create
-- several variants of 'M1'.
-- *** Additional generic representation type constructors
--
-- |
--
-- Next to 'K1', 'M1', ':+:' and ':*:' there are a few more type constructors that occur
-- in the representations of other datatypes.
-- **** Empty datatypes: 'V1'
--
-- |
--
-- For empty datatypes, 'V1' is used as a representation. For example,
--
-- @
-- data Empty deriving 'Generic'
-- @
--
-- yields
--
-- @
-- instance 'Generic' Empty where
-- type 'Rep' Empty =
-- 'D1' ('MetaData \"Empty\" \"Main\" \"package-name\" 'False) 'V1'
-- @
-- **** Constructors without fields: 'U1'
--
-- |
--
-- If a constructor has no arguments, then 'U1' is used as its representation. For example
-- the representation of 'Bool' is
--
-- @
-- instance 'Generic' Bool where
-- type 'Rep' Bool =
-- 'D1' ('MetaData \"Bool\" \"Data.Bool\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"False\" 'PrefixI 'False) 'U1' ':+:' 'C1' ('MetaCons \"True\" 'PrefixI 'False) 'U1')
-- @
-- *** Representation of types with many constructors or many fields
--
-- |
--
-- As ':+:' and ':*:' are just binary operators, one might ask what happens if the
-- datatype has more than two constructors, or a constructor with more than two
-- fields. The answer is simple: the operators are used several times, to combine
-- all the constructors and fields as needed. However, users /should not rely on
-- a specific nesting strategy/ for ':+:' and ':*:' being used. The compiler is
-- free to choose any nesting it prefers. (In practice, the current implementation
-- tries to produce a more or less balanced nesting, so that the traversal of the
-- structure of the datatype from the root to a particular component can be performed
-- in logarithmic rather than linear time.)
-- ** Defining datatype-generic functions
--
-- |
--
-- A datatype-generic function comprises two parts:
--
-- 1. /Generic instances/ for the function, implementing it for most of the representation
-- type constructors introduced above.
--
-- 2. A /wrapper/ that for any datatype that is in `Generic`, performs the conversion
-- between the original value and its `Rep`-based representation and then invokes the
-- generic instances.
--
-- As an example, let us look at a function 'encode' that produces a naive, but lossless
-- bit encoding of values of various datatypes. So we are aiming to define a function
--
-- @
-- encode :: 'Generic' a => a -> [Bool]
-- @
--
-- where we use 'Bool' as our datatype for bits.
--
-- For part 1, we define a class @Encode'@. Perhaps surprisingly, this class is parameterized
-- over a type constructor @f@ of kind @* -> *@. This is a technicality: all the representation
-- type constructors operate with kind @* -> *@ as base kind. But the type argument is never
-- being used. This may be changed at some point in the future. The class has a single method,
-- and we use the type we want our final function to have, but we replace the occurrences of
-- the generic type argument @a@ with @f p@ (where the @p@ is any argument; it will not be used).
--
-- > class Encode' f where
-- > encode' :: f p -> [Bool]
--
-- With the goal in mind to make @encode@ work on @Tree@ and other datatypes, we now define
-- instances for the representation type constructors 'V1', 'U1', ':+:', ':*:', 'K1', and 'M1'.
-- *** Definition of the generic representation types
--
-- |
--
-- In order to be able to do this, we need to know the actual definitions of these types:
--
-- @
-- data 'V1' p -- lifted version of Empty
-- data 'U1' p = 'U1' -- lifted version of ()
-- data (':+:') f g p = 'L1' (f p) | 'R1' (g p) -- lifted version of 'Either'
-- data (':*:') f g p = (f p) ':*:' (g p) -- lifted version of (,)
-- newtype 'K1' i c p = 'K1' { 'unK1' :: c } -- a container for a c
-- newtype 'M1' i t f p = 'M1' { 'unM1' :: f p } -- a wrapper
-- @
--
-- So, 'U1' is just the unit type, ':+:' is just a binary choice like 'Either',
-- ':*:' is a binary pair like the pair constructor @(,)@, and 'K1' is a value
-- of a specific type @c@, and 'M1' wraps a value of the generic type argument,
-- which in the lifted world is an @f p@ (where we do not care about @p@).
-- *** Generic instances
--
-- |
--
-- The instance for 'V1' is slightly awkward (but also rarely used):
--
-- @
-- instance Encode' 'V1' where
-- encode' x = undefined
-- @
--
-- There are no values of type @V1 p@ to pass (except undefined), so this is
-- actually impossible. One can ask why it is useful to define an instance for
-- 'V1' at all in this case? Well, an empty type can be used as an argument to
-- a non-empty type, and you might still want to encode the resulting type.
-- As a somewhat contrived example, consider @[Empty]@, which is not an empty
-- type, but contains just the empty list. The 'V1' instance ensures that we
-- can call the generic function on such types.
--
-- There is exactly one value of type 'U1', so encoding it requires no
-- knowledge, and we can use zero bits:
--
-- @
-- instance Encode' 'U1' where
-- encode' 'U1' = []
-- @
--
-- In the case for ':+:', we produce 'False' or 'True' depending on whether
-- the constructor of the value provided is located on the left or on the right:
--
-- @
-- instance (Encode' f, Encode' g) => Encode' (f ':+:' g) where
-- encode' ('L1' x) = False : encode' x
-- encode' ('R1' x) = True : encode' x
-- @
--
-- In the case for ':*:', we append the encodings of the two subcomponents:
--
-- @
-- instance (Encode' f, Encode' g) => Encode' (f ':*:' g) where
-- encode' (x ':*:' y) = encode' x ++ encode' y
-- @
--
-- The case for 'K1' is rather interesting. Here, we call the final function
-- 'encode' that we yet have to define, recursively. We will use another type
-- class 'Encode' for that function:
--
-- @
-- instance (Encode c) => Encode' ('K1' i c) where
-- encode' ('K1' x) = encode x
-- @
--
-- Note how 'Par0' and 'Rec0' both being mapped to 'K1' allows us to define
-- a uniform instance here.
--
-- Similarly, we can define a uniform instance for 'M1', because we completely
-- disregard all meta-information:
--
-- @
-- instance (Encode' f) => Encode' ('M1' i t f) where
-- encode' ('M1' x) = encode' x
-- @
--
-- Unlike in 'K1', the instance for 'M1' refers to 'encode'', not 'encode'.
-- *** The wrapper and generic default
--
-- |
--
-- We now define class 'Encode' for the actual 'encode' function:
--
-- @
-- class Encode a where
-- encode :: a -> [Bool]
-- default encode :: (Generic a, Encode' (Rep a)) => a -> [Bool]
-- encode x = encode' ('from' x)
-- @
--
-- The incoming 'x' is converted using 'from', then we dispatch to the
-- generic instances using 'encode''. We use this as a default definition
-- for 'encode'. We need the 'default encode' signature because ordinary
-- Haskell default methods must not introduce additional class constraints,
-- but our generic default does.
--
-- Defining a particular instance is now as simple as saying
--
-- @
-- instance (Encode a) => Encode (Tree a)
-- @
--
-- The generic default is being used. In the future, it will hopefully be
-- possible to use @deriving Encode@ as well, but GHC does not yet support
-- that syntax for this situation.
--
-- Having 'Encode' as a class has the advantage that we can define
-- non-generic special cases, which is particularly useful for abstract
-- datatypes that have no structural representation. For example, given
-- a suitable integer encoding function 'encodeInt', we can define
--
-- @
-- instance Encode Int where
-- encode = encodeInt
-- @
-- *** Omitting generic instances
--
-- |
--
-- It is not always required to provide instances for all the generic
-- representation types, but omitting instances restricts the set of
-- datatypes the functions will work for:
--
-- * If no ':+:' instance is given, the function may still work for
-- empty datatypes or datatypes that have a single constructor,
-- but will fail on datatypes with more than one constructor.
--
-- * If no ':*:' instance is given, the function may still work for
-- datatypes where each constructor has just zero or one field,
-- in particular for enumeration types.
--
-- * If no 'K1' instance is given, the function may still work for
-- enumeration types, where no constructor has any fields.
--
-- * If no 'V1' instance is given, the function may still work for
-- any datatype that is not empty.
--
-- * If no 'U1' instance is given, the function may still work for
-- any datatype where each constructor has at least one field.
--
-- An 'M1' instance is always required (but it can just ignore the
-- meta-information, as is the case for 'encode' above).
-- ** Generic constructor classes
--
-- |
--
-- Datatype-generic functions as defined above work for a large class
-- of datatypes, including parameterized datatypes. (We have used 'Tree'
-- as our example above, which is of kind @* -> *@.) However, the
-- 'Generic' class ranges over types of kind @*@, and therefore, the
-- resulting generic functions (such as 'encode') must be parameterized
-- by a generic type argument of kind @*@.
--
-- What if we want to define generic classes that range over type
-- constructors (such as 'Functor', 'Traversable', or 'Foldable')?
-- *** The 'Generic1' class
--
-- |
--
-- Like 'Generic', there is a class 'Generic1' that defines a
-- representation 'Rep1' and conversion functions 'from1' and 'to1',
-- only that 'Generic1' ranges over types of kind @* -> *@.
-- The 'Generic1' class is also derivable.
--
-- The representation 'Rep1' is ever so slightly different from 'Rep'.
-- Let us look at 'Tree' as an example again:
--
-- @
-- data Tree a = Leaf a | Node (Tree a) (Tree a)
-- deriving 'Generic1'
-- @
--
-- The above declaration causes the following representation to be generated:
--
-- @
-- instance 'Generic1' Tree where
-- type 'Rep1' Tree =
-- 'D1' ('MetaData \"Tree\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"Leaf\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- 'Par1')
-- ':+:'
-- 'C1' ('MetaCons \"Node\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec1' Tree)
-- ':*:'
-- 'S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec1' Tree)))
-- ...
-- @
--
-- The representation reuses 'D1', 'C1', 'S1' (and thereby 'M1') as well
-- as ':+:' and ':*:' from 'Rep'. (This reusability is the reason that we
-- carry around the dummy type argument for kind-@*@-types, but there are
-- already enough different names involved without duplicating each of
-- these.)
--
-- What's different is that we now use 'Par1' to refer to the parameter
-- (and that parameter, which used to be @a@), is not mentioned explicitly
-- by name anywhere; and we use 'Rec1' to refer to a recursive use of @Tree a@.
-- *** Representation of @* -> *@ types
--
-- |
--
-- Unlike 'Rec0', the 'Par1' and 'Rec1' type constructors do not
-- map to 'K1'. They are defined directly, as follows:
--
-- @
-- newtype 'Par1' p = 'Par1' { 'unPar1' :: p } -- gives access to parameter p
-- newtype 'Rec1' f p = 'Rec1' { 'unRec1' :: f p } -- a wrapper
-- @
--
-- In 'Par1', the parameter @p@ is used for the first time, whereas 'Rec1' simply
-- wraps an application of @f@ to @p@.
--
-- Note that 'K1' (in the guise of 'Rec0') can still occur in a 'Rep1' representation,
-- namely when the datatype has a field that does not mention the parameter.
--
-- The declaration
--
-- @
-- data WithInt a = WithInt Int a
-- deriving 'Generic1'
-- @
--
-- yields
--
-- @
-- class 'Rep1' WithInt where
-- type 'Rep1' WithInt =
-- 'D1' ('MetaData \"WithInt\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"WithInt\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ('Rec0' Int)
-- ':*:'
-- 'S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- 'Par1'))
-- @
--
-- If the parameter @a@ appears underneath a composition of other type constructors,
-- then the representation involves composition, too:
--
-- @
-- data Rose a = Fork a [Rose a]
-- @
--
-- yields
--
-- @
-- class 'Rep1' Rose where
-- type 'Rep1' Rose =
-- 'D1' ('MetaData \"Rose\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"Fork\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- 'Par1'
-- ':*:'
-- 'S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- ([] ':.:' 'Rec1' Rose)))
-- @
--
-- where
--
-- @
-- newtype (':.:') f g p = 'Comp1' { 'unComp1' :: f (g p) }
-- @
-- *** Representation of unlifted types
--
-- |
--
-- If one were to attempt to derive a Generic instance for a datatype with an
-- unlifted argument (for example, 'Int#'), one might expect the occurrence of
-- the 'Int#' argument to be marked with @'Rec0' 'Int#'@. This won't work,
-- though, since 'Int#' is of kind @#@ and 'Rec0' expects a type of kind @*@.
-- In fact, polymorphism over unlifted types is disallowed completely.
--
-- One solution would be to represent an occurrence of 'Int#' with 'Rec0 Int'
-- instead. With this approach, however, the programmer has no way of knowing
-- whether the 'Int' is actually an 'Int#' in disguise.
--
-- Instead of reusing 'Rec0', a separate data family 'URec' is used to mark
-- occurrences of common unlifted types:
--
-- @
-- data family URec a p
--
-- data instance 'URec' ('Ptr' ()) p = 'UAddr' { 'uAddr#' :: 'Addr#' }
-- data instance 'URec' 'Char' p = 'UChar' { 'uChar#' :: 'Char#' }
-- data instance 'URec' 'Double' p = 'UDouble' { 'uDouble#' :: 'Double#' }
-- data instance 'URec' 'Int' p = 'UFloat' { 'uFloat#' :: 'Float#' }
-- data instance 'URec' 'Float' p = 'UInt' { 'uInt#' :: 'Int#' }
-- data instance 'URec' 'Word' p = 'UWord' { 'uWord#' :: 'Word#' }
-- @
--
-- Several type synonyms are provided for convenience:
--
-- @
-- type 'UAddr' = 'URec' ('Ptr' ())
-- type 'UChar' = 'URec' 'Char'
-- type 'UDouble' = 'URec' 'Double'
-- type 'UFloat' = 'URec' 'Float'
-- type 'UInt' = 'URec' 'Int'
-- type 'UWord' = 'URec' 'Word'
-- @
--
-- The declaration
--
-- @
-- data IntHash = IntHash Int#
-- deriving 'Generic'
-- @
--
-- yields
--
-- @
-- instance 'Generic' IntHash where
-- type 'Rep' IntHash =
-- 'D1' ('MetaData \"IntHash\" \"Main\" \"package-name\" 'False)
-- ('C1' ('MetaCons \"IntHash\" 'PrefixI 'False)
-- ('S1' ('MetaSel 'Nothing
-- 'NoSourceUnpackedness
-- 'NoSourceStrictness
-- 'DecidedLazy)
-- 'UInt'))
-- @
--
-- Currently, only the six unlifted types listed above are generated, but this
-- may be extended to encompass more unlifted types in the future.
-----------------------------------------------------------------------------
-- * Generic representation types
V1, U1(..), Par1(..), Rec1(..), K1(..), M1(..)
, (:+:)(..), (:*:)(..), (:.:)(..)
-- ** Unboxed representation types
, URec(..)
, type UAddr, type UChar, type UDouble
, type UFloat, type UInt, type UWord
-- ** Synonyms for convenience
, Rec0, R
, D1, C1, S1, D, C, S
-- * Meta-information
, Datatype(..), Constructor(..), Selector(..)
, Fixity(..), FixityI(..), Associativity(..), prec
, SourceUnpackedness(..), SourceStrictness(..), DecidedStrictness(..)
, Meta(..)
-- * Generic type classes
, Generic(..), Generic1(..)
) where
-- We use some base types
import Data.Either ( Either (..) )
import Data.Maybe ( Maybe(..), fromMaybe )
import GHC.Integer ( Integer, integerToInt )
import GHC.Prim ( Addr#, Char#, Double#, Float#, Int#, Word# )
import GHC.Ptr ( Ptr )
import GHC.Types
-- Needed for instances
import GHC.Arr ( Ix )
import GHC.Base ( Alternative(..), Applicative(..), Functor(..)
, Monad(..), MonadPlus(..), String )
import GHC.Classes ( Eq(..), Ord(..) )
import GHC.Enum ( Bounded, Enum )
import GHC.Read ( Read(..), lex, readParen )
import GHC.Show ( Show(..), showString )
-- Needed for metadata
import Data.Proxy ( Proxy(..), KProxy(..) )
import GHC.TypeLits ( Nat, Symbol, KnownSymbol, KnownNat, symbolVal, natVal )
--------------------------------------------------------------------------------
-- Representation types
--------------------------------------------------------------------------------
-- | Void: used for datatypes without constructors
data V1 (p :: *)
deriving (Functor, Generic, Generic1)
deriving instance Eq (V1 p)
deriving instance Ord (V1 p)
deriving instance Read (V1 p)
deriving instance Show (V1 p)
-- | Unit: used for constructors without arguments
data U1 (p :: *) = U1
deriving (Generic, Generic1)
instance Eq (U1 p) where
_ == _ = True
instance Ord (U1 p) where
compare _ _ = EQ
instance Read (U1 p) where
readsPrec d = readParen (d > 10) (\r -> [(U1, s) | ("U1",s) <- lex r ])
instance Show (U1 p) where
showsPrec _ _ = showString "U1"
instance Functor U1 where
fmap _ _ = U1
instance Applicative U1 where
pure _ = U1
_ <*> _ = U1
instance Alternative U1 where
empty = U1
_ <|> _ = U1
instance Monad U1 where
_ >>= _ = U1
instance MonadPlus U1
-- | Used for marking occurrences of the parameter
newtype Par1 p = Par1 { unPar1 :: p }
deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)
instance Applicative Par1 where
pure a = Par1 a
Par1 f <*> Par1 x = Par1 (f x)
instance Monad Par1 where
Par1 x >>= f = f x
-- | Recursive calls of kind * -> *
newtype Rec1 f (p :: *) = Rec1 { unRec1 :: f p }
deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)
instance Applicative f => Applicative (Rec1 f) where
pure a = Rec1 (pure a)
Rec1 f <*> Rec1 x = Rec1 (f <*> x)
instance Alternative f => Alternative (Rec1 f) where
empty = Rec1 empty
Rec1 l <|> Rec1 r = Rec1 (l <|> r)
instance Monad f => Monad (Rec1 f) where
Rec1 x >>= f = Rec1 (x >>= \a -> unRec1 (f a))
instance MonadPlus f => MonadPlus (Rec1 f)
-- | Constants, additional parameters and recursion of kind *
newtype K1 (i :: *) c (p :: *) = K1 { unK1 :: c }
deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)
instance Applicative f => Applicative (M1 i c f) where
pure a = M1 (pure a)
M1 f <*> M1 x = M1 (f <*> x)
instance Alternative f => Alternative (M1 i c f) where
empty = M1 empty
M1 l <|> M1 r = M1 (l <|> r)
instance Monad f => Monad (M1 i c f) where
M1 x >>= f = M1 (x >>= \a -> unM1 (f a))
instance MonadPlus f => MonadPlus (M1 i c f)
-- | Meta-information (constructor names, etc.)
newtype M1 (i :: *) (c :: Meta) f (p :: *) = M1 { unM1 :: f p }
deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)
-- | Sums: encode choice between constructors
infixr 5 :+:
data (:+:) f g (p :: *) = L1 (f p) | R1 (g p)
deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)
-- | Products: encode multiple arguments to constructors
infixr 6 :*:
data (:*:) f g (p :: *) = f p :*: g p
deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)
instance (Applicative f, Applicative g) => Applicative (f :*: g) where
pure a = pure a :*: pure a
(f :*: g) <*> (x :*: y) = (f <*> x) :*: (g <*> y)
instance (Alternative f, Alternative g) => Alternative (f :*: g) where
empty = empty :*: empty
(x1 :*: y1) <|> (x2 :*: y2) = (x1 <|> x2) :*: (y1 <|> y2)
instance (Monad f, Monad g) => Monad (f :*: g) where
(m :*: n) >>= f = (m >>= \a -> fstP (f a)) :*: (n >>= \a -> sndP (f a))
where
fstP (a :*: _) = a
sndP (_ :*: b) = b
instance (MonadPlus f, MonadPlus g) => MonadPlus (f :*: g)
-- | Composition of functors
infixr 7 :.:
newtype (:.:) f (g :: * -> *) (p :: *) = Comp1 { unComp1 :: f (g p) }
deriving (Eq, Ord, Read, Show, Functor, Generic, Generic1)
instance (Applicative f, Applicative g) => Applicative (f :.: g) where
pure x = Comp1 (pure (pure x))
Comp1 f <*> Comp1 x = Comp1 (fmap (<*>) f <*> x)
instance (Alternative f, Applicative g) => Alternative (f :.: g) where
empty = Comp1 empty
Comp1 x <|> Comp1 y = Comp1 (x <|> y)
-- | Constants of kind @#@
data family URec (a :: *) (p :: *)
-- | Used for marking occurrences of 'Addr#'
data instance URec (Ptr ()) p = UAddr { uAddr# :: Addr# }
deriving (Eq, Ord, Functor, Generic, Generic1)
-- | Used for marking occurrences of 'Char#'
data instance URec Char p = UChar { uChar# :: Char# }
deriving (Eq, Ord, Show, Functor, Generic, Generic1)
-- | Used for marking occurrences of 'Double#'
data instance URec Double p = UDouble { uDouble# :: Double# }
deriving (Eq, Ord, Show, Functor, Generic, Generic1)
-- | Used for marking occurrences of 'Float#'
data instance URec Float p = UFloat { uFloat# :: Float# }
deriving (Eq, Ord, Show, Functor, Generic, Generic1)
-- | Used for marking occurrences of 'Int#'
data instance URec Int p = UInt { uInt# :: Int# }
deriving (Eq, Ord, Show, Functor, Generic, Generic1)
-- | Used for marking occurrences of 'Word#'
data instance URec Word p = UWord { uWord# :: Word# }
deriving (Eq, Ord, Show, Functor, Generic, Generic1)
-- | Type synonym for 'URec': 'Addr#'
type UAddr = URec (Ptr ())
-- | Type synonym for 'URec': 'Char#'
type UChar = URec Char
-- | Type synonym for 'URec': 'Double#'
type UDouble = URec Double
-- | Type synonym for 'URec': 'Float#'
type UFloat = URec Float
-- | Type synonym for 'URec': 'Int#'
type UInt = URec Int
-- | Type synonym for 'URec': 'Word#'
type UWord = URec Word
-- | Tag for K1: recursion (of kind *)
data R
-- | Type synonym for encoding recursion (of kind *)
type Rec0 = K1 R
-- | Tag for M1: datatype
data D
-- | Tag for M1: constructor
data C
-- | Tag for M1: record selector
data S
-- | Type synonym for encoding meta-information for datatypes
type D1 = M1 D
-- | Type synonym for encoding meta-information for constructors
type C1 = M1 C
-- | Type synonym for encoding meta-information for record selectors
type S1 = M1 S
-- | Class for datatypes that represent datatypes
class Datatype d where
-- | The name of the datatype (unqualified)
datatypeName :: t d (f :: * -> *) a -> [Char]
-- | The fully-qualified name of the module where the type is declared
moduleName :: t d (f :: * -> *) a -> [Char]
-- | The package name of the module where the type is declared
packageName :: t d (f :: * -> *) a -> [Char]
-- | Marks if the datatype is actually a newtype
isNewtype :: t d (f :: * -> *) a -> Bool
isNewtype _ = False
instance (KnownSymbol n, KnownSymbol m, KnownSymbol p, SingI nt)
=> Datatype ('MetaData n m p nt) where
datatypeName _ = symbolVal (Proxy :: Proxy n)
moduleName _ = symbolVal (Proxy :: Proxy m)
packageName _ = symbolVal (Proxy :: Proxy p)
isNewtype _ = fromSing (sing :: Sing nt)
-- | Class for datatypes that represent data constructors
class Constructor c where
-- | The name of the constructor
conName :: t c (f :: * -> *) a -> [Char]
-- | The fixity of the constructor
conFixity :: t c (f :: * -> *) a -> Fixity
conFixity _ = Prefix
-- | Marks if this constructor is a record
conIsRecord :: t c (f :: * -> *) a -> Bool
conIsRecord _ = False
instance (KnownSymbol n, SingI f, SingI r)
=> Constructor ('MetaCons n f r) where
conName _ = symbolVal (Proxy :: Proxy n)
conFixity _ = fromSing (sing :: Sing f)
conIsRecord _ = fromSing (sing :: Sing r)
-- | Datatype to represent the fixity of a constructor. An infix
-- | declaration directly corresponds to an application of 'Infix'.
data Fixity = Prefix | Infix Associativity Int
deriving (Eq, Show, Ord, Read, Generic)
-- | This variant of 'Fixity' appears at the type level.
data FixityI = PrefixI | InfixI Associativity Nat
-- | Get the precedence of a fixity value.
prec :: Fixity -> Int
prec Prefix = 10
prec (Infix _ n) = n
-- | Datatype to represent the associativity of a constructor
data Associativity = LeftAssociative
| RightAssociative
| NotAssociative
deriving (Eq, Show, Ord, Read, Enum, Bounded, Ix, Generic)
-- | The unpackedness of a field as the user wrote it in the source code. For
-- example, in the following data type:
--
-- @
-- data E = ExampleConstructor Int
-- {\-\# NOUNPACK \#-\} Int
-- {\-\# UNPACK \#-\} Int
-- @
--
-- The fields of @ExampleConstructor@ have 'NoSourceUnpackedness',
-- 'SourceNoUnpack', and 'SourceUnpack', respectively.
data SourceUnpackedness = NoSourceUnpackedness
| SourceNoUnpack
| SourceUnpack
deriving (Eq, Show, Ord, Read, Enum, Bounded, Ix, Generic)
-- | The strictness of a field as the user wrote it in the source code. For
-- example, in the following data type:
--
-- @
-- data E = ExampleConstructor Int ~Int !Int
-- @
--
-- The fields of @ExampleConstructor@ have 'NoSourceStrictness',
-- 'SourceLazy', and 'SourceStrict', respectively.
data SourceStrictness = NoSourceStrictness
| SourceLazy
| SourceStrict
deriving (Eq, Show, Ord, Read, Enum, Bounded, Ix, Generic)
-- | The strictness that GHC infers for a field during compilation. Whereas
-- there are nine different combinations of 'SourceUnpackedness' and
-- 'SourceStrictness', the strictness that GHC decides will ultimately be one
-- of lazy, strict, or unpacked. What GHC decides is affected both by what the
-- user writes in the source code and by GHC flags. As an example, consider
-- this data type:
--
-- @
-- data E = ExampleConstructor {\-\# UNPACK \#-\} !Int !Int Int
-- @
--
-- * If compiled without optimization or other language extensions, then the
-- fields of @ExampleConstructor@ will have 'DecidedStrict', 'DecidedStrict',
-- and 'DecidedLazy', respectively.
--
-- * If compiled with @-XStrictData@ enabled, then the fields will have
-- 'DecidedStrict', 'DecidedStrict', and 'DecidedStrict', respectively.
--
-- * If compiled with @-O2@ enabled, then the fields will have 'DecidedUnpack',
-- 'DecidedStrict', and 'DecidedLazy', respectively.
data DecidedStrictness = DecidedLazy
| DecidedStrict
| DecidedUnpack
deriving (Eq, Show, Ord, Read, Enum, Bounded, Ix, Generic)
-- | Class for datatypes that represent records
class Selector s where
-- | The name of the selector
selName :: t s (f :: * -> *) a -> [Char]
-- | The selector's unpackedness annotation (if any)
selSourceUnpackedness :: t s (f :: * -> *) a -> SourceUnpackedness
-- | The selector's strictness annotation (if any)
selSourceStrictness :: t s (f :: * -> *) a -> SourceStrictness
-- | The strictness that the compiler inferred for the selector
selDecidedStrictness :: t s (f :: * -> *) a -> DecidedStrictness
instance (SingI mn, SingI su, SingI ss, SingI ds)
=> Selector ('MetaSel mn su ss ds) where
selName _ = fromMaybe "" (fromSing (sing :: Sing mn))
selSourceUnpackedness _ = fromSing (sing :: Sing su)
selSourceStrictness _ = fromSing (sing :: Sing ss)
selDecidedStrictness _ = fromSing (sing :: Sing ds)
-- | Representable types of kind *.
-- This class is derivable in GHC with the DeriveGeneric flag on.
class Generic a where
-- | Generic representation type
type Rep a :: * -> *
-- | Convert from the datatype to its representation
from :: a -> (Rep a) x
-- | Convert from the representation to the datatype
to :: (Rep a) x -> a
-- | Representable types of kind * -> *.
-- This class is derivable in GHC with the DeriveGeneric flag on.
class Generic1 f where
-- | Generic representation type
type Rep1 f :: * -> *
-- | Convert from the datatype to its representation
from1 :: f a -> (Rep1 f) a
-- | Convert from the representation to the datatype
to1 :: (Rep1 f) a -> f a
--------------------------------------------------------------------------------
-- Meta-data
--------------------------------------------------------------------------------
-- | Datatype to represent metadata associated with a datatype (@MetaData@),
-- constructor (@MetaCons@), or field selector (@MetaSel@).
--
-- * In @MetaData n m p nt@, @n@ is the datatype's name, @m@ is the module in
-- which the datatype is defined, @p@ is the package in which the datatype
-- is defined, and @nt@ is @'True@ if the datatype is a @newtype@.
--
-- * In @MetaCons n f s@, @n@ is the constructor's name, @f@ is its fixity,
-- and @s@ is @'True@ if the constructor contains record selectors.
--
-- * In @MetaSel mn su ss ds@, if the field is uses record syntax, then @mn@ is
-- 'Just' the record name. Otherwise, @mn@ is 'Nothing. @su@ and @ss@ are the
-- field's unpackedness and strictness annotations, and @ds@ is the
-- strictness that GHC infers for the field.
data Meta = MetaData Symbol Symbol Symbol Bool
| MetaCons Symbol FixityI Bool
| MetaSel (Maybe Symbol)
SourceUnpackedness SourceStrictness DecidedStrictness
--------------------------------------------------------------------------------
-- Derived instances
--------------------------------------------------------------------------------
deriving instance Generic [a]
deriving instance Generic (Maybe a)
deriving instance Generic (Either a b)
deriving instance Generic Bool
deriving instance Generic Ordering
deriving instance Generic (Proxy t)
deriving instance Generic ()
deriving instance Generic ((,) a b)
deriving instance Generic ((,,) a b c)
deriving instance Generic ((,,,) a b c d)
deriving instance Generic ((,,,,) a b c d e)
deriving instance Generic ((,,,,,) a b c d e f)
deriving instance Generic ((,,,,,,) a b c d e f g)
deriving instance Generic1 []
deriving instance Generic1 Maybe
deriving instance Generic1 (Either a)
deriving instance Generic1 Proxy
deriving instance Generic1 ((,) a)
deriving instance Generic1 ((,,) a b)
deriving instance Generic1 ((,,,) a b c)
deriving instance Generic1 ((,,,,) a b c d)
deriving instance Generic1 ((,,,,,) a b c d e)
deriving instance Generic1 ((,,,,,,) a b c d e f)
--------------------------------------------------------------------------------
-- Copied from the singletons package
--------------------------------------------------------------------------------
-- | The singleton kind-indexed data family.
data family Sing (a :: k)
-- | A 'SingI' constraint is essentially an implicitly-passed singleton.
-- If you need to satisfy this constraint with an explicit singleton, please
-- see 'withSingI'.
class SingI (a :: k) where
-- | Produce the singleton explicitly. You will likely need the @ScopedTypeVariables@
-- extension to use this method the way you want.
sing :: Sing a
-- | The 'SingKind' class is essentially a /kind/ class. It classifies all kinds
-- for which singletons are defined. The class supports converting between a singleton
-- type and the base (unrefined) type which it is built from.
class (kparam ~ 'KProxy) => SingKind (kparam :: KProxy k) where
-- | Get a base type from a proxy for the promoted kind. For example,
-- @DemoteRep ('KProxy :: KProxy Bool)@ will be the type @Bool@.
type DemoteRep kparam :: *
-- | Convert a singleton to its unrefined version.
fromSing :: Sing (a :: k) -> DemoteRep kparam
-- Singleton symbols
data instance Sing (s :: Symbol) where
SSym :: KnownSymbol s => Sing s
instance KnownSymbol a => SingI a where sing = SSym
instance SingKind ('KProxy :: KProxy Symbol) where
type DemoteRep ('KProxy :: KProxy Symbol) = String
fromSing (SSym :: Sing s) = symbolVal (Proxy :: Proxy s)
-- Singleton booleans
data instance Sing (a :: Bool) where
STrue :: Sing 'True
SFalse :: Sing 'False
instance SingI 'True where sing = STrue
instance SingI 'False where sing = SFalse
instance SingKind ('KProxy :: KProxy Bool) where
type DemoteRep ('KProxy :: KProxy Bool) = Bool
fromSing STrue = True
fromSing SFalse = False
-- Singleton Maybe
data instance Sing (b :: Maybe a) where
SNothing :: Sing 'Nothing
SJust :: Sing a -> Sing ('Just a)
instance SingI 'Nothing where sing = SNothing
instance SingI a => SingI ('Just a) where sing = SJust sing
instance SingKind ('KProxy :: KProxy a) =>
SingKind ('KProxy :: KProxy (Maybe a)) where
type DemoteRep ('KProxy :: KProxy (Maybe a)) =
Maybe (DemoteRep ('KProxy :: KProxy a))
fromSing SNothing = Nothing
fromSing (SJust a) = Just (fromSing a)
-- Singleton Fixity
data instance Sing (a :: FixityI) where
SPrefix :: Sing 'PrefixI
SInfix :: Sing a -> Integer -> Sing ('InfixI a n)
instance SingI 'PrefixI where sing = SPrefix
instance (SingI a, KnownNat n) => SingI ('InfixI a n) where
sing = SInfix (sing :: Sing a) (natVal (Proxy :: Proxy n))
instance SingKind ('KProxy :: KProxy FixityI) where
type DemoteRep ('KProxy :: KProxy FixityI) = Fixity
fromSing SPrefix = Prefix
fromSing (SInfix a n) = Infix (fromSing a) (I# (integerToInt n))
-- Singleton Associativity
data instance Sing (a :: Associativity) where
SLeftAssociative :: Sing 'LeftAssociative
SRightAssociative :: Sing 'RightAssociative
SNotAssociative :: Sing 'NotAssociative
instance SingI 'LeftAssociative where sing = SLeftAssociative
instance SingI 'RightAssociative where sing = SRightAssociative
instance SingI 'NotAssociative where sing = SNotAssociative
instance SingKind ('KProxy :: KProxy Associativity) where
type DemoteRep ('KProxy :: KProxy Associativity) = Associativity
fromSing SLeftAssociative = LeftAssociative
fromSing SRightAssociative = RightAssociative
fromSing SNotAssociative = NotAssociative
-- Singleton SourceUnpackedness
data instance Sing (a :: SourceUnpackedness) where
SNoSourceUnpackedness :: Sing 'NoSourceUnpackedness
SSourceNoUnpack :: Sing 'SourceNoUnpack
SSourceUnpack :: Sing 'SourceUnpack
instance SingI 'NoSourceUnpackedness where sing = SNoSourceUnpackedness
instance SingI 'SourceNoUnpack where sing = SSourceNoUnpack
instance SingI 'SourceUnpack where sing = SSourceUnpack
instance SingKind ('KProxy :: KProxy SourceUnpackedness) where
type DemoteRep ('KProxy :: KProxy SourceUnpackedness) = SourceUnpackedness
fromSing SNoSourceUnpackedness = NoSourceUnpackedness
fromSing SSourceNoUnpack = SourceNoUnpack
fromSing SSourceUnpack = SourceUnpack
-- Singleton SourceStrictness
data instance Sing (a :: SourceStrictness) where
SNoSourceStrictness :: Sing 'NoSourceStrictness
SSourceLazy :: Sing 'SourceLazy
SSourceStrict :: Sing 'SourceStrict
instance SingI 'NoSourceStrictness where sing = SNoSourceStrictness
instance SingI 'SourceLazy where sing = SSourceLazy
instance SingI 'SourceStrict where sing = SSourceStrict
instance SingKind ('KProxy :: KProxy SourceStrictness) where
type DemoteRep ('KProxy :: KProxy SourceStrictness) = SourceStrictness
fromSing SNoSourceStrictness = NoSourceStrictness
fromSing SSourceLazy = SourceLazy
fromSing SSourceStrict = SourceStrict
-- Singleton DecidedStrictness
data instance Sing (a :: DecidedStrictness) where
SDecidedLazy :: Sing 'DecidedLazy
SDecidedStrict :: Sing 'DecidedStrict
SDecidedUnpack :: Sing 'DecidedUnpack
instance SingI 'DecidedLazy where sing = SDecidedLazy
instance SingI 'DecidedStrict where sing = SDecidedStrict
instance SingI 'DecidedUnpack where sing = SDecidedUnpack
instance SingKind ('KProxy :: KProxy DecidedStrictness) where
type DemoteRep ('KProxy :: KProxy DecidedStrictness) = DecidedStrictness
fromSing SDecidedLazy = DecidedLazy
fromSing SDecidedStrict = DecidedStrict
fromSing SDecidedUnpack = DecidedUnpack
| phischu/fragnix | builtins/base/GHC.Generics.hs | bsd-3-clause | 44,986 | 18 | 12 | 10,107 | 6,428 | 3,821 | 2,607 | -1 | -1 |
{-# LANGUAGE ExistentialQuantification #-}
module Common.Drawable where
class Drawable_ a where
render :: a -> IO ()
data Drawable = forall a. Drawable_ a => Drawable a | Zielon/Bounce | src/Common/Drawable.hs | bsd-3-clause | 175 | 0 | 9 | 33 | 51 | 27 | 24 | 5 | 0 |
module End.Constant.Settings where
screenWidth :: Int
screenHeight :: Int
halfScreenWidth :: Int
halfScreenHeight :: Int
tileBit :: Int
mapWidth :: Int
mapHeight :: Int
mapWidthPx :: Int
mapHeightPx :: Int
screenWidth = 1000
screenHeight = 1000
halfScreenWidth = screenWidth `div` 2
halfScreenHeight = screenHeight `div` 2
tileBit = 32
mapWidth = 100
mapHeight = 100
mapWidthPx = mapWidth * 32
mapHeightPx = mapHeight * 32
| kwrooijen/sdl-game | End/Constant/Settings.hs | gpl-3.0 | 514 | 0 | 5 | 156 | 117 | 71 | 46 | 19 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="da-DK">
<title>SOAP Scanner | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_da_DK/helpset_da_DK.hs | apache-2.0 | 974 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
module Propellor.Property.Postfix where
import Propellor
import qualified Propellor.Property.Apt as Apt
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Service as Service
import qualified Propellor.Property.User as User
import qualified Data.Map as M
import Data.List
import Data.Char
installed :: Property NoInfo
installed = Apt.serviceInstalledRunning "postfix"
restarted :: Property NoInfo
restarted = Service.restarted "postfix"
reloaded :: Property NoInfo
reloaded = Service.reloaded "postfix"
-- | Configures postfix as a satellite system, which
-- relays all mail through a relay host, which defaults to smtp.domain,
-- but can be changed by @mainCf "relayhost"@.
--
-- The smarthost may refuse to relay mail on to other domains, without
-- further configuration/keys. But this should be enough to get cron job
-- mail flowing to a place where it will be seen.
satellite :: Property NoInfo
satellite = check (not <$> mainCfIsSet "relayhost") setup
`requires` installed
where
setup = trivial $ property "postfix satellite system" $ do
hn <- asks hostName
let (_, domain) = separate (== '.') hn
ensureProperties
[ Apt.reConfigure "postfix"
[ ("postfix/main_mailer_type", "select", "Satellite system")
, ("postfix/root_address", "string", "root")
, ("postfix/destinations", "string", "localhost")
, ("postfix/mailname", "string", hn)
]
, mainCf ("relayhost", "smtp." ++ domain)
`onChange` reloaded
]
-- | Sets up a file by running a property (which the filename is passed
-- to). If the setup property makes a change, postmap will be run on the
-- file, and postfix will be reloaded.
mappedFile
:: Combines (Property x) (Property NoInfo)
=> FilePath
-> (FilePath -> Property x)
-> Property (CInfo x NoInfo)
mappedFile f setup = setup f
`onChange` cmdProperty "postmap" [f]
-- | Run newaliases command, which should be done after changing
-- @/etc/aliases@.
newaliases :: Property NoInfo
newaliases = trivial $ cmdProperty "newaliases" []
-- | The main config file for postfix.
mainCfFile :: FilePath
mainCfFile = "/etc/postfix/main.cf"
-- | Sets a main.cf @name=value@ pair. Does not reload postfix immediately.
mainCf :: (String, String) -> Property NoInfo
mainCf (name, value) = check notset set
`describe` ("postfix main.cf " ++ setting)
where
setting = name ++ "=" ++ value
notset = (/= Just value) <$> getMainCf name
set = cmdProperty "postconf" ["-e", setting]
-- | Gets a main.cf setting.
getMainCf :: String -> IO (Maybe String)
getMainCf name = parse . lines <$> readProcess "postconf" [name]
where
parse (l:_) = Just $
case separate (== '=') l of
(_, (' ':v)) -> v
(_, v) -> v
parse [] = Nothing
-- | Checks if a main.cf field is set. A field that is set to
-- the empty string is considered not set.
mainCfIsSet :: String -> IO Bool
mainCfIsSet name = do
v <- getMainCf name
return $ v /= Nothing && v /= Just ""
-- | Parses main.cf, and removes any initial configuration lines that are
-- overridden to other values later in the file.
--
-- For example, to add some settings, removing any old settings:
--
-- > mainCf `File.containsLines`
-- > [ "# I like bars."
-- > , "foo = bar"
-- > ] `onChange` dedupMainCf
--
-- Note that multiline configurations that continue onto the next line
-- are not currently supported.
dedupMainCf :: Property NoInfo
dedupMainCf = File.fileProperty "postfix main.cf dedupped" dedupCf mainCfFile
dedupCf :: [String] -> [String]
dedupCf ls =
let parsed = map parse ls
in dedup [] (keycounts $ rights parsed) parsed
where
parse l
| "#" `isPrefixOf` l = Left l
| "=" `isInfixOf` l =
let (k, v) = separate (== '=') l
in Right ((filter (not . isSpace) k), v)
| otherwise = Left l
fmt k v = k ++ " =" ++ v
keycounts = M.fromListWith (+) . map (\(k, _v) -> (k, (1 :: Integer)))
dedup c _ [] = reverse c
dedup c kc ((Left v):rest) = dedup (v:c) kc rest
dedup c kc ((Right (k, v)):rest) = case M.lookup k kc of
Just n | n > 1 -> dedup c (M.insert k (n - 1) kc) rest
_ -> dedup (fmt k v:c) kc rest
-- | Installs saslauthd and configures it for postfix, authenticating
-- against PAM.
--
-- Does not configure postfix to use it; eg @smtpd_sasl_auth_enable = yes@
-- needs to be set to enable use. See
-- <https://wiki.debian.org/PostfixAndSASL>.
saslAuthdInstalled :: Property NoInfo
saslAuthdInstalled = setupdaemon
`requires` Service.running "saslauthd"
`requires` postfixgroup
`requires` dirperm
`requires` Apt.installed ["sasl2-bin"]
`requires` smtpdconf
where
setupdaemon = "/etc/default/saslauthd" `File.containsLines`
[ "START=yes"
, "OPTIONS=\"-c -m " ++ dir ++ "\""
]
`onChange` Service.restarted "saslauthd"
smtpdconf = "/etc/postfix/sasl/smtpd.conf" `File.containsLines`
[ "pwcheck_method: saslauthd"
, "mech_list: PLAIN LOGIN"
]
dirperm = check (not <$> doesDirectoryExist dir) $
cmdProperty "dpkg-statoverride"
[ "--add", "root", "sasl", "710", dir ]
postfixgroup = (User "postfix") `User.hasGroup` (Group "sasl")
`onChange` restarted
dir = "/var/spool/postfix/var/run/saslauthd"
| sjfloat/propellor | src/Propellor/Property/Postfix.hs | bsd-2-clause | 5,152 | 74 | 16 | 936 | 1,388 | 764 | 624 | 97 | 4 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
module Main where
import Control.Monad.IO.Class (liftIO)
import Data.Aeson
import Data.Monoid
import Data.HashMap.Strict as HashMap
import Data.Text (pack)
import Web.Scotty
import Web.Scotty.CRUD
import Web.Scotty.CRUD.JSON (actorCRUD)
main :: IO ()
main = scotty 3000 $ do
let tab :: Table Row
tab = HashMap.fromList $
[("foo",HashMap.fromList [("firstname", "Roger"),("lastname","Rabbit"),("age", Number 21)])
,("abc",HashMap.fromList [("firstname", "Roger"),("lastname","Rabbit"),("bla",Bool True)])
] ++
[ ("abc-" <> pack (show n),HashMap.fromList [("firstname", "Roger"),("lastname","Rabbit"),("bla",Bool False)])
| n <- [1..100]
]
users <- liftIO $ actorCRUD
(\ _ -> return ()) -- do not store the updates anywhere
tab -- but supply an (updatable) table
scottyCRUD "/users" users
| ku-fpg/flat-json | examples/Service.hs | bsd-3-clause | 936 | 12 | 18 | 193 | 326 | 188 | 138 | 23 | 1 |
--------------------------------------------------------------------
-- |
-- Module : MediaWiki.API.Query.LogEvents
-- Description : Representing 'logevents' requests.
-- Copyright : (c) Sigbjorn Finne, 2008
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <sof@forkIO.com>
-- Stability : provisional
-- Portability: portable
--
-- Representing 'logevents' requests.
--
--------------------------------------------------------------------
module MediaWiki.API.Query.LogEvents where
import MediaWiki.API.Types
import MediaWiki.API.Utils
data LogEventsRequest
= LogEventsRequest
{ leProp :: [String]
, leType :: [String]
, leStart :: Maybe Timestamp
, leEnd :: Maybe Timestamp
, leDir :: Maybe TimeArrow
, leUser :: Maybe UserID
, leTitle :: Maybe PageName
, leLimit :: Maybe Int
}
instance APIRequest LogEventsRequest where
queryKind _ = QList "logevents"
showReq r =
[ opt1 "leprop" (leProp r)
, opt1 "letype" (leType r)
, mbOpt "lestart" id (leStart r)
, mbOpt "leend" id (leEnd r)
, mbOpt "ledir" (\ x -> if x==Earlier then "older" else "newer") (leDir r)
, mbOpt "leuser" id (leUser r)
, mbOpt "letitle" id (leTitle r)
, mbOpt "lelimit" show (leLimit r)
]
emptyLogEventsRequest :: LogEventsRequest
emptyLogEventsRequest = LogEventsRequest
{ leProp = []
, leType = []
, leStart = Nothing
, leEnd = Nothing
, leDir = Nothing
, leUser = Nothing
, leTitle = Nothing
, leLimit = Nothing
}
data LogEventsResponse
= LogEventsResponse
{ leEvents :: [LogEvent]
, leContinue :: Maybe String
}
emptyLogEventsResponse :: LogEventsResponse
emptyLogEventsResponse = LogEventsResponse
{ leEvents = []
, leContinue = Nothing
}
data LogEvent
= LogEvent
{ levLogId :: Maybe String
, levPage :: PageTitle
, levType :: Maybe String
, levAction :: Maybe String
, levParams :: [LogEventParam]
, levUser :: Maybe String
, levTimestamp :: Maybe Timestamp
, levComment :: Maybe String
}
emptyLogEvent :: LogEvent
emptyLogEvent
= LogEvent
{ levLogId = Nothing
, levPage = emptyPageTitle
, levType = Nothing
, levAction = Nothing
, levParams = []
, levUser = Nothing
, levTimestamp = Nothing
, levComment = Nothing
}
data LogEventParam
= LogEventMove
{ levMovePage :: PageTitle }
| LogEventPatrol
{ levPatrolCurrent :: Maybe String
, levPatrolPrevious :: Maybe String
, levPatrolAuto :: Maybe String
}
| LogEventRights
{ levRightsOld :: Maybe String
, levRightsNew :: Maybe String
}
| LogEventBlock
{ levBlockDuration :: Maybe String
, levBlockFlags :: Maybe String
}
| LogEventParam {levParamValue :: String }
| LogEventOther
{ levParamName :: String
, levParamAttrs :: [(String,String)]
}
| HyperGainZ/neobot | mediawiki/MediaWiki/API/Query/LogEvents.hs | bsd-3-clause | 3,082 | 0 | 11 | 894 | 673 | 397 | 276 | 80 | 1 |
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE PatternGuards #-}
module Migrations.M_14 (migration) where
import UpgradeEngine
import Data.List (foldl')
migration = Migration {
sourceVersion = 14
, targetVersion = 15
, actions = act
}
act :: IO ()
act = removeCryptoUname
removeCryptoUname = xformVmJSON xform where
xform = jsRm "/crypto-username"
| jean-edouard/manager | upgrade-db/Migrations/M_14.hs | gpl-2.0 | 1,139 | 0 | 7 | 244 | 100 | 66 | 34 | 12 | 1 |
module FrontEnd.Lex.Fixity where
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-}
import Control.Monad
import Control.Monad.Identity
import Data.Tree
import System.Environment
import Text.Show
data Fixity = L | R | N | Prefix | Prefixy | Postfix
deriving(Show,Eq)
type Prec = (Fixity,Int)
-- alternating operators and expressions, always succeeds.
simpleShunt :: (Show e, Show o)
=> (o -> Prec)
-> e -> [(o,e)]
-> (o -> e -> e -> e) -> e
simpleShunt getPrec e oes combine = runIdentity $ do
let ShuntSpec { .. } = shuntSpec
let lookupToken (Left e) = return $ Left e
lookupToken (Right o) = return $ Right (getPrec o)
operator ~(Right t) ~[x,y] = return $ combine t x y
ss = ShuntSpec { .. }
shunt ss (Left e:concat [ [Right o, Left e] | (o,e) <- oes])
data S t e = S {
stack :: [(Maybe t,Prec)],
output :: [e],
lastWasOp :: Bool
} deriving(Show)
initialState = S { stack = [], output = [], lastWasOp = True }
-- lookups must be idempotent.
data ShuntSpec m t e = ShuntSpec {
appPrec :: Prec, -- Precedence of application.
lookupToken :: t -> m (Either e Prec), -- A token is either an operator or an expression.
lookupUnary :: t -> m (Maybe Int), -- What to do when an unexpected op happens, either can be interpeted as unary or fail.
application :: e -> e -> m e, -- what to do on application
operator :: t -> [e] -> m e, -- what to do on operator
emptyInput :: m e, -- what to do on empty input
trailingOps :: e -> t -> m e, -- what to do with trailing operators
equalFixity :: Prec -> [Maybe t] -> m e-- what to do on nonassociate fixities
}
shuntSpec :: (Monad m, Show t) => ShuntSpec m t e
shuntSpec = ShuntSpec { .. } where
appPrec = (L,10)
lookupToken t = fail $ "ShuntSpec.lookupToken unspecified: " ++ show t
lookupUnary t = fail $ "Operator used in unary location: " ++ show t
application _ _ = fail $ "ShuntSpec.application unspecified"
operator t _ = fail $ "ShuntSpec.operator unspecified: " ++ show t
emptyInput = fail $ "Empty input to precedence parser"
trailingOps _ ts = fail $ "Trailing operators: " ++ show ts
equalFixity p ts = fail $ "Cannot mix operators of same fixity: "
++ show p ++ " " ++ show ts
shunt :: (Show t, Show e,Monad m)
=> ShuntSpec m t e -- specification
-> [t] -- token stream
-> m e
shunt ShuntSpec { .. } xs = f initialState xs where
f S { output = [e], stack = [] } [] = return e
f S { output = [], stack = [] } [] = emptyInput
f s@S { .. } (t:ts) = lookupToken t >>= \x -> case (x,lastWasOp) of
(Left o,True) -> f s { output = o:output, lastWasOp = False } ts
(Left o,False) -> op s { lastWasOp = True } (Nothing,appPrec) Nothing (t:ts)
(Right p@(Prefix,_),False) -> op s { lastWasOp = True } (Nothing,appPrec) Nothing (t:ts)
(Right p,False) -> op s { lastWasOp = True } (Just t,p) Nothing ts
(Right p@(Prefix,_),True) -> op s (Just t,p) Nothing ts
(Right p@(_,n),True) -> do
mn <- lookupUnary t
let Just n' = mplus mn (Just n)
op s (Just t,(Prefix,n')) Nothing ts
f s@S { output = (x:os) , stack = (t,(Prefix,_)):ss } [] = do
ne <- apop t [x]
f s { output = ne:os, stack = ss } []
f s@S { output = (x:y:os) , stack = (t,_):ss } [] = do
ne <- apop t [y,x]
f s { output = ne:os, stack = ss } []
f s@S { output = [e], stack = (Just t,_):ss } [] = do
ne <- trailingOps e t -- (catMaybes $ map fst stack)
f s { output = [ne], stack = ss } []
f s [] = error $ show s
op s@S { .. } o@(_,prec) me ts = g s where
g s@S { stack = [] } = f (addOut s { stack = [o] }) ts
g s@S { stack = (t,prec'@(Prefix,_)):ss, output = (x:rs) }
| prec' `gt` prec = do
ne <- apop t [x]
g s { stack = ss, output = ne:rs }
g s@S { stack = (t,prec'@(N,_)):ss, output = (x:y:rs) }
| prec' == prec = do equalFixity prec [t]
g s@S { stack = (t,prec'):ss, output = (x:y:rs) }
| prec' `gt` prec = do
ne <- apop t [y,x]
g s { stack = ss, output = ne:rs }
g s@S { .. } = f (addOut s { stack = o:stack }) ts
addOut s@S { ..} = case me of
Just e -> s { output = e:output }
Nothing -> s
apop t [x,y] = case t of
Nothing -> application x y
Just t' -> operator t' [x,y]
apop t xs = operator t' xs where
Just t' = t
_ `gt` (Prefix,_) = False
(Prefix,x) `gt` (_,y) = x >= y
(L,x) `gt` (_,y) = x >= y
(_,x) `gt` (_,y) = x > y
precs = procPrecs
[prec Prefix ["~"]
,prec R ["^"]
,prec L ["/","*","%"]
,prec R []
,prec L ["+","-"]
,prec L ["."]
,prec N ["=~"]
,prec Prefix ["!"]
,prec N ["<","<=",">=","!=","=="]
,prec L ["&&"]
,prec L ["||"]
]
prec p ws = (p,ws)
procPrecs ps = concatMap f (zip (reverse ps) [0 :: Int ..]) where
f ((p,ws),n) = [ (w,(p,n)) | w <- ws ]
main = do
xs <- getArgs
let ts = concatMap words xs
ShuntSpec { .. } = shuntSpec
let lookupToken x = return $ case lookup x precs of
Just y -> Right y
_ -> Left x
operator t [x,y] = return $ parens (x <+> t <+> y)
operator t ~[x] = return $ brackets (t <+> x)
application = \x y -> return $ parens (x <+> y)
lookupUnary = \_ -> return Nothing
--trailingOps e t = return $ "<" ++ e ++ " " ++ t ++ ">"
appPrec = (L,7)
res <- shunt ShuntSpec { .. } ts
r2 <- shunt (treeShuntSpec "" (return . (`lookup` precs))) { lookupUnary, appPrec } ts
-- mapM_ print precs
putStrLn res
putStrLn $ drawParenTree r2
x <+> y = x ++ " " ++ y
parens x = "(" ++ x ++ ")"
brackets x = "[" ++ x ++ "]"
treeShuntSpec :: (Monad m, Show t)
=> t -- token value to use for applications.
-> (t -> m (Maybe Prec)) -- lookup precedence
-> ShuntSpec m t (Tree t)
treeShuntSpec app lup = shuntSpec { application, operator, lookupToken } where
application x y = return $ Node app [x,y]
operator t xs = return $ Node t xs
lookupToken t = lup t >>= \x -> case x of
Just p -> return $ Right p
Nothing -> return $ Left (Node t [])
drawParenTree :: Tree String -> String
drawParenTree t = f t [] where
f (Node t []) = showString t
f (Node "" [x,y]) = showChar '(' . f x . showChar ' ' . f y . showChar ')'
f (Node t [x,y]) = showChar '(' . f x . showChar ' ' . showString t . showChar ' ' . f y . showChar ')'
f (Node t [x]) = showChar '(' . showString t . showChar ' ' . f x . showChar ')'
f (Node t xs) = showString t . showListWith id (map f xs)
| m-alvarez/jhc | src/FrontEnd/Lex/Fixity.hs | mit | 6,893 | 0 | 19 | 2,193 | 3,180 | 1,691 | 1,489 | -1 | -1 |
module AddOneParameter.Nested(sumSquares,sumSquares_y) where
{- add parameter 'y' to 'sumSquares'. 'sumSquares_y_1' to be added to the
export list -}
sumSquares y (x:xs) = sq x + (sumSquares y) xs + foo xs
where foo a = (sumSquares y) a + 1
sumSquares y [] = 0
sumSquares_y = undefined
sq x = x ^ pow
pow =2
| RefactoringTools/HaRe | test/testdata/AddOneParameter/Nested.expected.hs | bsd-3-clause | 318 | 0 | 10 | 66 | 112 | 58 | 54 | 7 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : RefacUnGuard
-- Copyright : (c) Jose Proenca 2005
-- License : GPL
--
-- Maintainer : jproenca@di.uminho.pt
-- Stability : experimental
-- Portability : portable
--
-- Refactoring that tries to convert guards to if then else, after merging
-- necessary matches.
--
-----------------------------------------------------------------------------
module RefacUnGuard(
-- * The refactoring
guardToIte, -- won't appear in report because no type information was given
{- | The main goal of this refactoring is to convert a function declaration
where guards can be found into another with no guards, and with /if then else/
expressions instead. But the biggest problem aboarded in this transformation is how to
remove this guards if they afect more than one match that can be merged into
a single one, where different name for the variables is used and some line swapping may
be needed.
This refactoring is then divided into three different sub-problems, that will
be explained in more detail in this document:
* Check which matches can be converted and swaped with matches defined
bellow, without changing the function behaviour;
* Merge the similar matches with guards to a single match, renaming the
needed variables;
* In each match replace the guards by /if then else/ when possible.
-}
-- * Stages of the refactoring
-- ** Consistency check
{- | Before any other evaluation each match is compared with the matches below
on the same declaration by 'isConsist'. It is then associated with a boolean
that states if the declaration has any inconsitency below. A match is said to
be inconsitent with a second one below it if the patterns are not disjoint and
if a constant value is found in the a pattern of the second match where a
variable was in the first one. All possibles patterns were contemplated.
-}
findConsist,
isConsist,
-- ** Merge of matches
{- | After knowing which matches can be manipulated and swaped, the next step
is to try to merge matches using all possible combinations.
Because there are sometimes the need to create fresh variables, a name that is
not the prefix of any of the variable names (in this case is the smaller
sequence of x's) is used as the base name and a counter is added to the
variable name. The 'mergeMatches' is a function that uses a state monad with
partiality, whith the base name and the conter inside the state, and that
fails when the merging of two matches is not possible.
Before trying to merge matches, the declarations of the consistent matches are
passed to inside the guards and to the main expressions, using the function 'declsToLet',
since after the merging the declarations will afect more than the original
expressions. This will duplicate the declarations inside the where clause.
-}
getInitSt,
dmerge,
{- | In the merge of two matches all the possible patterns were contemplated.
In some cases there is more than way to merge patterns. Each case will now be
explained in more detailed.
[Similar patterns] If the two patterns are equivalent according to the
function 'similar', then no transformation is applied. Since this is the first
test to be performed, the patterns are considered to be different in the
remaing tests;
[Variables] When two different varibles are found they are replaced by a fresh
variable, in the pattern, in the guards and in the main expression;
[Parentisis] They are initialy ignored, and in the end they are placed back;
[WildCard (underscore)] Can only be matched with a variable. In this case a
fresh variable will replace both the wild card and the variable, in every
important place of the match;
[var \@ pattern] If both matches have this construction, then the variable and
the associated pattern are splited into two different patterns, and after the
recursive evaluation the resulting variable is \"glued\" back to the resulting
pattern. If only one match have this construction, then the variable is
replaced by a fresh variable, so that the same variable can also be assigned
to the second pattern;
[Irrefutable pattern] When a irrefutable pattern is found, it is replaced by a
fresh variable, and inside the guards and in the main expression a /let/
constructor is added, assigning the irrefutable pattern to take the value of
the fresh variable. This way the fact that haskell uses lazy evaluation allows
the behaviour of the function to be the same as before;
[Constructors with fields] Whenever a constructor with fields is found, it is
converted into a pattern where the constructor is applied to the different
variable, using wild cards to when a variable name is not assigned;
[Application] When in both matches a application of a constructor is found,
and the constructors are similar (according to the 'similar' function), then
the list of arguments are added to the remaining patterns to be merged, and in
the end they are extracted and \"glued\" with constructor again;
[Infix application] Same approach to normal application was taken.
[Tupples and lists] Each pattern inside the tupple or list is added to the
remaining patterns to be merged, and in the end they are \"glued\" again with
the tuple or list constructor.
-}
mergeMatches,
-- ** Conversion from guards to /if then else/'s
{- | The final stage is the most simple one, since there are not many cases to
evaluate. The function 'guards2ifs' is applied to each match with a guard and
with the consisty check mark. When the /otherwise/ guard is not found
the /else/ of the resultig expression issues an error message.
-}
guards2ifs,
-- * Auxiliary functions
{-| In this section some of the auxiliary functions used in this
refactoring are presented. This functions may be of some use in later refactorings.
-}
similar,
differ,
replaceExp,
declsToLet,
pRecToPApp
-- * Future work
{- | This refactoring tries to be as complete as possible, but it is still
possible to improve some cases. A possible improvement would be to infer the /otherwise/
case, as presented in the following example:
@
f x | x > 0 = 1
f x = 0
@
that could be initialy converted to
@
f x | x > 0 = 1
f x | otherwise = 0
@
but instead it does nothing to avoid overriding the last expression. This is
not very easy because a single expression in the end may be used to merge with
more then one group of matches above.
Another improvement would be to check if the declarations could also be merged
before converting them into /if then else/'s.
-}
) where
import RefacUtils
import PrettyPrint (pp)
import Data.Maybe
import Control.Monad.State
type Match = HsMatchI PNT (HsExpI PNT) (HsPatI PNT) [HsDeclI PNT]
guardToIte args
= do let fileName = ghead "filename" args
row = read (args!!1)::Int
col = read (args!!2)::Int
modInfo@(_,exps, mod, _)<-parseSourceFile fileName
let pn =locToPN fileName (row, col) mod
decls = definingDecls [pn] (hsModDecls mod) False False
if decls /= []
then do r <- applyRefac (replaceGuards (head decls)) (Just modInfo) fileName
writeRefactoredFiles False [r]
else error "\nInvalid cursor position!"
-- | Applies the transformation to a given declaration, using the auxiliary functions
-- defined bellow
replaceGuards d@(Dec (HsFunBind loc matches)) (_,_,mod)
= do let newMs1 = findConsist matches -- :: [(Bool,Match)]
initSt = getInitSt [m | (b,m) <- newMs1, b]
newMs2 = map declsToLet' newMs1
newMs3 = dmerge newMs2 initSt
newMs4 = map guards2ifs newMs3
update d
-- to see intermediate results use this line with the desired number
--(error (show [(b,pp m) | (b,m)<-newMs1]))
--(Dec (HsFunBind loc (map snd newMs1)))
(Dec (HsFunBind loc newMs4))
mod
replaceGuards decl (_,_,mod) = return mod
-- | Convert a match with guards to another match where the guards are
-- translated to /if then else/'s
guards2ifs :: (Bool,HsMatchP) -> HsMatchP
guards2ifs (True, HsMatch l i p (HsGuard lst) ds) = HsMatch l i p (HsBody $ g2i lst) ds
where
-- the empty list should never occur
g2i [] = error "empty list of guards!"
g2i [(loc,cond,exp)]
| isOtherwise cond = exp
| otherwise = mkIte cond exp undefError
g2i ((loc,cond,exp):xs) = mkIte cond exp (g2i xs)
isOtherwise (Exp (HsId (HsVar (PNT (PN (UnQual "otherwise")
(G (PlainModule "Prelude") "otherwise"
(N (Just _)))) Value (N (Just _))))))
= True
isOtherwise _ = False
mkIte e1 e2 e3 = Exp (HsIf e1 e2 e3)
undefError = (Exp (HsApp (Exp (HsId (HsVar (PNT (PN (UnQual "error")
(G (PlainModule "Prelude") "error"
(N (Just loc0)))) Value (N (Just loc0)))))) (Exp
(HsLit loc0 (HsString "UnMatched Pattern")))))
guards2ifs (_,x) = x
--------------------------
--- Consistency check ----
--------------------------
-- | Given a set of matches, checks which ones have guards that can be
-- removed without afecting the program's behaviour. This implies going throw
-- every pattern to check if each pair is similar, disjoint or inconsistent.
-- It uses the binary function 'isConsist'.
findConsist :: [HsMatchP] -> [(Bool,HsMatchP)]
findConsist [] = []
findConsist (m:ms)
= let ms' = findConsist ms
in case m of
(HsMatch _ _ pats (HsGuard _) _)
-> (and $ map (checkGuard m) $ map (isConsist pats . getPats) ms
, m) : ms'
_ -> (False,m) : ms'
where
getPats (HsMatch _ _ pats _ _) = pats
-- if a match is consistent with every match below, but not disjoint, then
-- the guard can only be removed if it exists
checkGuard (HsMatch _ _ _ (HsGuard _) _) Nothing = True
checkGuard (HsMatch _ _ _ _ _) Nothing = False
checkGuard _ (Just x) = x
-- | Checks if two lists of patterns are consistents. Possible results are:
--
-- - Just True - if disjoint patterns are found
--
-- - Just False - if an incongruence is found and there are no disjoint patterns
--
-- - Nothing - if no incongruence nor disjoint patterns are found
isConsist :: [HsPatP] -> [HsPatP] -> Maybe Bool
isConsist [] _ = Nothing
isConsist _ [] = Nothing
-- similar values -> continue
isConsist (p1:pats1) (p2:pats2) | p1 `similar` p2
= isConsist pats1 pats2
-- different constants -> True
isConsist (k1:pats1) (k2:pats2) | isConstant k1 && isConstant k2
= if k1 `differ` k2 then Just True
else isConsist pats1 pats2
-- var - const -> False
isConsist ((Pat (HsPId (HsVar _))):pats1) (k:pats2) | isConstant k
= case isConsist pats1 pats2 of
Just True -> Just True
_ -> Just False
-- const - var -> False
isConsist (k:pats1) ((Pat (HsPId (HsVar _))):pats2) | isConstant k
= case isConsist pats1 pats2 of
Just True -> Just True
_ -> Just False
-- var - var -> continue
isConsist ((Pat (HsPId (HsVar _))):pats1) ((Pat (HsPId (HsVar _))):pats2)
= isConsist pats1 pats2
---- const - _ -> Continue
--isConsist (k:pats1) (_:pats2) | isConstant k
-- = isConsist pats1 pats2
---- _ - var -> Continue
--isConsist (_:pats1) ((Pat (HsPId (HsVar _))):pats2)
-- = isConsist pats1 pats2
-- x - y -> unfold x and y, and check if they are consistent before continuing
isConsist (pat1:pats1) (pat2:pats2)
= case isConsist (unfoldPat pat1) (unfoldPat pat2) of
Just True -> Just True
Nothing -> isConsist pats1 pats2
_ -> case isConsist pats1 pats2 of
Just True -> Just True
_ -> Just False
-- Only used in the consistency check.
-- For each complex pattern, it is decomposed into a list of more simple patterns,
-- that will be checked for consistency.
unfoldPat :: HsPatP -> [HsPatP]
unfoldPat (Pat HsPWildCard) = [nameToPat "_"] -- name is not important
unfoldPat (Pat (HsPIrrPat p)) = [nameToPat "irr"] -- name is not important
unfoldPat (Pat (HsPAsPat i p)) = unfoldPat p
unfoldPat (Pat (HsPApp i ps))
= (Pat $ HsPId $ HsCon i) : (map unparen ps)
unfoldPat (Pat (HsPInfixApp p1 i p2))
= (Pat $ HsPId (HsCon i)) : (map unparen [p1,p2])
unfoldPat (Pat prec@(HsPRec constr fields))
= unfoldPat (Pat $ pRecToPApp prec)
unfoldPat (Pat (HsPList _ lst))
= (Pat $ HsPId $ HsCon $ nameToPNT "(:)"):lst -- the name is not important
unfoldPat (Pat (HsPTuple _ lst))
= (Pat $ HsPId $ HsCon $ nameToPNT "(tup)"):lst -- the name is not important
unfoldPat x@(Pat _) = [unparen x]
unparen (Pat (HsPParen m)) = unparen m
unparen x = x
-------------------------
--- merge of matches ----
-------------------------
-- To create fresh variables a partial State monad is used, to store the base name and the seed.
type ST = StateT St Maybe
data St = St {baseName :: String,
seed :: Int}
getSt :: ST St
getSt = do sd <- gets seed
bn <- gets baseName
return $ St bn sd
getSeed :: ST Int
getSeed = do n <- gets seed
modify (\s -> s {seed = n+1})
return n
getFreshVar :: ST String
getFreshVar = do s <- getSeed
n <- gets baseName
return (n++"_"++(show s))
-- | To get an initial state it is necessery to find a base name that is not prefix of any of the used names.
-- In this case it will be 'x' replicated until it is not a prefix. The
-- counter is initiated to zero.
getInitSt :: [HsMatchP] -> St
getInitSt ms
= let xs = (runIdentity $ applyTU strat ms) :: [Int]
base = replicate (maximum xs) 'x'
in St base 0
where strat = full_tdTU ((constTU [1]) `adhocTU` getNumberX)
getNumberX :: HsIdentI PNT -> Identity [Int]
getNumberX (HsVar pnt) =
let name = pNTtoName pnt
n = length $ takeWhile (=='x') name
in return $ [n+1]
getNumberX _ = return []
-- | Distributes the binary function 'mergeMatches'.
--
-- The state of each evaluation of 'mergeMatches' as to be extracted to be
-- passed to further calls. It doesn't make sense to put the same state
-- inside 'dmerge', because it would fail when the first 'mergeMatches' failed,
-- which is not desired.
dmerge :: [(Bool,HsMatchP)] -> St -> [(Bool,HsMatchP)]
dmerge [] _ = []
dmerge [x] _ = [x]
dmerge ((False,h):rest) st = (False,h):(dmerge rest st)
dmerge ((True,h):rest) st
= case dmerge2 h rest st of
Just (st',newMs) -> dmerge newMs st'
Nothing -> (True,h) : (dmerge rest st)
dmerge2 h [] _ = fail "end"
dmerge2 h ((False,t):rest) st
= do (st',newMs) <- dmerge2 h rest st
return (st',(False,t):newMs)
dmerge2 h ((True,t):rest) st
= case tryMergeMatches h t st of
Just (st',newM)
-> return (st',(True,newM):rest)
_ -> do (st',newMs) <- dmerge2 h rest st
return (st',(True,t):newMs)
tryMergeMatches h t st
= evalStateT
(do newM <- mergeMatches h t
st' <- getSt
return (st',newM))
st
{- | Tries to merge two matches with guards, using a state monad to create
fresh variables whith partiality to fail when no merging is possible.
-}
mergeMatches :: HsMatchP
-> HsMatchP
-> ST HsMatchP
-- no more patterns
mergeMatches (HsMatch l1 i1 [] (HsGuard lst1) ds) (HsMatch l2 i2 [] (HsGuard lst2) _)
= return $ HsMatch l1 i1 [] (HsGuard (lst1++lst2)) ds
-- similar values
mergeMatches (HsMatch l1 i1 (p1:pats1) e1 [])
(HsMatch l2 i2 (p2:pats2) e2 [])
| p1 `similar` p2
= do HsMatch l i ps e _ <- mergeMatches (HsMatch l1 i1 pats1 e1 [])
(HsMatch l2 i2 pats2 e2 [])
return $ HsMatch l i (p1:ps) e []
-- parentisis
mergeMatches (HsMatch l1 i1 ((Pat (HsPParen p1)):ps1) e1 [])
(HsMatch l2 i2 ((Pat (HsPParen p2)):ps2) e2 [])
= do HsMatch l i (p:ps) e _ <- mergeMatches (HsMatch l1 i1 (p1:ps1) e1 [])
(HsMatch l2 i2 (p2:ps2) e2 [])
return $ HsMatch l i ((Pat (HsPParen p)):ps) e []
mergeMatches (HsMatch l1 i1 ((Pat (HsPParen p1)):ps1) e1 []) m2
= do HsMatch l i (p:ps) e _ <- mergeMatches (HsMatch l1 i1 (p1:ps1) e1 []) m2
return $ HsMatch l i ((Pat (HsPParen p)):ps) e []
mergeMatches m1 (HsMatch l2 i2 ((Pat (HsPParen p2)):ps2) e2 [])
= do HsMatch l i (p:ps) e _ <- mergeMatches m1 (HsMatch l2 i2 (p2:ps2) e2 [])
return $ HsMatch l i ((Pat (HsPParen p)):ps) e []
-- WildCard
{-mergeMatches (HsMatch l1 i1 ((Pat HsPWildCard):ps1) e1 [])
(HsMatch l2 i2 ((Pat HsPWildCard):ps2) e2 [])
= do HsMatch l i (p:ps) e _ <- mergeMatches (HsMatch l1 i1 ps1 e1 [])
(HsMatch l2 i2 ps2 e2 [])
return $ HsMatch l i ((Pat HsPWildCard):ps) e []-}
mergeMatches (HsMatch l1 i1 ((Pat HsPWildCard):ps1) e1 [])
(HsMatch l2 i2 ((Pat (HsPId (HsVar var))):ps2) e2 [])
= do v <- getFreshVar
let e2' = replaceRhs var v Nothing e2
HsMatch l i ps e _ <- mergeMatches (HsMatch l1 i1 ps1 e1 [])
(HsMatch l2 i2 ps2 e2' [])
return $ HsMatch l i ((Pat $ HsPId $ HsVar $ changeName var v):ps) e []
mergeMatches (HsMatch l1 i1 ((Pat (HsPId (HsVar var))):ps1) e1 [])
(HsMatch l2 i2 ((Pat HsPWildCard):ps2) e2 [])
= do v <- getFreshVar
let e1' = replaceRhs var v Nothing e1
HsMatch l i ps e _ <- mergeMatches (HsMatch l1 i1 ps1 e1' [])
(HsMatch l2 i2 ps2 e2 [])
return $ HsMatch l i ((Pat $ HsPId $ HsVar $ changeName var v):ps) e []
-- x @ pat
mergeMatches (HsMatch l1 i1 ((Pat (HsPAsPat var1 p1)):ps1) e1 [])
(HsMatch l2 i2 ((Pat (HsPAsPat var2 p2)):ps2) e2 [])
= do HsMatch l i ((Pat (HsPId (HsVar var))):p:ps) e _ <-
mergeMatches (HsMatch l1 i1 ((Pat $ HsPId $ HsVar var1):p1:ps1) e1 [])
(HsMatch l2 i2 ((Pat $ HsPId $ HsVar var1):p2:ps2) e2 [])
return $ HsMatch l i ((Pat $ HsPAsPat var p):ps) e []
mergeMatches (HsMatch l1 i1 ((Pat (HsPAsPat var p1)):ps1) e1 [])
(HsMatch l2 i2 ps2 e2 [])
= do v <- getFreshVar
let e1' = replaceRhs var v Nothing e1
var' = changeName var v
HsMatch l i (p:ps) e _ <- mergeMatches (HsMatch l1 i1 (p1:ps1) e1' [])
(HsMatch l2 i2 ps2 e2 [])
return $ HsMatch l i ((Pat $ HsPAsPat var' p):ps) e []
mergeMatches (HsMatch l1 i1 ps1 e1 [])
(HsMatch l2 i2 ((Pat (HsPAsPat var p2)):ps2) e2 [])
= do v <- getFreshVar
let e2' = replaceRhs var v Nothing e2
var' = changeName var v
HsMatch l i (p:ps) e _ <- mergeMatches (HsMatch l1 i1 ps1 e1 [])
(HsMatch l2 i2 (p2:ps2) e2' [])
return $ HsMatch l i ((Pat $ HsPAsPat var' p):ps) e []
-- ~ pat
mergeMatches (HsMatch l1 i1 ((Pat (HsPIrrPat p1)):ps1) e1 [])
(HsMatch l2 i2 ps2 e2 [])
= do v <- getFreshVar
let e1' = addLet p1 (nameToExp v) e1
p1' = nameToPat v
mergeMatches (HsMatch l1 i1 (p1':ps1) e1' [])
(HsMatch l2 i2 ps2 e2 [])
mergeMatches (HsMatch l1 i1 ps1 e1 [])
(HsMatch l2 i2 ((Pat (HsPIrrPat p2)):ps2) e2 [])
= do v <- getFreshVar
let e2' = addLet p2 (nameToExp v) e2
p2' = nameToPat v
mergeMatches (HsMatch l1 i1 ps1 e1 [])
(HsMatch l2 i2 (p2':ps2) e2' [])
-- C { ...}
mergeMatches (HsMatch l1 i1 (Pat (r@(HsPRec _ _)):ps1) e1 [])
(HsMatch l2 i2 ps2 e2 [])
= mergeMatches (HsMatch l1 i1 ((Pat (pRecToPApp r)):ps1) e1 [])
(HsMatch l2 i2 ps2 e2 [])
mergeMatches (HsMatch l1 i1 ps1 e1 [])
(HsMatch l2 i2 (Pat (r@(HsPRec _ _)):ps2) e2 [])
= mergeMatches (HsMatch l1 i1 ps1 e1 [])
(HsMatch l2 i2 ((Pat (pRecToPApp r)):ps2) e2 [])
-- 2 variables (different)
mergeMatches (HsMatch l1 i1 ((Pat (HsPId (HsVar var1))):pats1) e1 [])
(HsMatch l2 i2 ((Pat (HsPId (HsVar var2))):pats2) e2 [])
= do v <- getFreshVar
let e1' = replaceRhs var1 v Nothing e1
e2' = replaceRhs var2 v (Just var1) e2
HsMatch l i ps e _ <- mergeMatches (HsMatch l1 i1 pats1 e1' [])
(HsMatch l2 i2 pats2 e2' [])
return $ HsMatch l i ((Pat $ HsPId $ HsVar $ changeName var1 v):ps) e []
-- application
mergeMatches (HsMatch l1 i1 ((Pat (HsPApp pnt1 lst1)):pats1) e1 [])
(HsMatch l2 i2 ((Pat (HsPApp pnt2 lst2)):pats2) e2 [])
| pnt1 `similar` pnt2
= do let n = length lst1 -- assuming equal lengths
HsMatch l i ps e _ <- mergeMatches (HsMatch l1 i1 (lst1++pats1) e1 [])
(HsMatch l2 i2 (lst2++pats2) e2 [])
let (lst',ps') = splitAt n ps
return $ HsMatch l i ((Pat (HsPApp pnt1 lst')):ps') e []
-- infix application
mergeMatches (HsMatch l1 i1 ((Pat (HsPInfixApp pl1 op1 pr1)):pats1) e1 [])
(HsMatch l2 i2 ((Pat (HsPInfixApp pl2 op2 pr2)):pats2) e2 [])
| op1 `similar` op2
= do HsMatch l i (pl:pr:ps) e _ <-
mergeMatches (HsMatch l1 i1 (pl1:pr1:pats1) e1 [])
(HsMatch l2 i2 (pl2:pr2:pats2) e2 [])
return $ HsMatch l i ((Pat (HsPInfixApp pl op2 pr)):ps) e []
-- tuples
mergeMatches (HsMatch l1 i1 ((Pat (HsPList loc1 lst1)):pats1) e1 [])
(HsMatch l2 i2 ((Pat (HsPList loc2 lst2)):pats2) e2 [])
= do let n = length lst1 -- assuming equal lengths
HsMatch l i ps e _ <- mergeMatches (HsMatch l1 i1 (lst1++pats1) e1 [])
(HsMatch l2 i2 (lst2++pats2) e2 [])
let (lst',ps') = splitAt n ps
return $ HsMatch l i ((Pat (HsPList loc1 lst')):ps') e []
-- lists
mergeMatches (HsMatch l1 i1 ((Pat (HsPTuple loc1 lst1)):pats1) e1 [])
(HsMatch l2 i2 ((Pat (HsPTuple loc2 lst2)):pats2) e2 [])
= do let n = length lst1 -- assuming equal lengths
HsMatch l i ps e _ <- mergeMatches (HsMatch l1 i1 (lst1++pats1) e1 [])
(HsMatch l2 i2 (lst2++pats2) e2 [])
let (lst',ps') = splitAt n ps
return $ HsMatch l i ((Pat (HsPTuple loc1 lst')):ps') e []
-- merge is not possible
mergeMatches m1 m2
= fail "no merge possible"
---------------------------
--- Auxiliary functions ---
---------------------------
-- puts declarations inside an expression by the use of let
declsToLet' :: (Bool,HsMatchP) -> (Bool,HsMatchP)
declsToLet' (False,m) = (False,m)
declsToLet' (True,HsMatch l i p rhs ds)
= (True,HsMatch l i p (declsToLet rhs ds) [])
-- | Places declarations inside an expression by the use of the /let/
-- constructor
declsToLet :: RhsP -> [HsDeclP] -> RhsP
declsToLet x [] = x
declsToLet (HsBody e) ds = HsBody (Exp (HsLet ds e))
declsToLet (HsGuard lst) ds = HsGuard $ map aux lst
where aux (l,e1,e2) = (l,Exp (HsLet ds e1) , Exp (HsLet ds e2))
addLet :: HsPatP -> HsExpP -> RhsP -> RhsP
addLet pat exp1 (HsBody exp2)
= HsBody $ Exp (HsLet [Dec $ HsPatBind loc0 pat (HsBody exp1) []] exp2)
addLet pat exp1 (HsGuard lst) = HsGuard $ map aux lst
where aux (l,e1,e2) = (l,
Exp (HsLet [Dec $ HsPatBind loc0 pat (HsBody exp1) []] e1),
Exp (HsLet [Dec $ HsPatBind loc0 pat (HsBody exp1) []] e2))
-- | Relplaces a variable by another, without checking if it will become bounded or not
-- (should be used fresh variables for that).
replaceRhs u v l (HsBody e) = HsBody (replaceExp u v l e)
replaceRhs u v lc (HsGuard lst) = HsGuard $
map (\(l,e1,e2)->(l,replaceExp u v lc e1,replaceExp u v lc e2))
lst
-- | Replaces a variable name (given a PNT) by changing the name to a new name
-- and, when another PNT is passed, also changes the source location to the
-- same the second PNT.
replaceExp :: Term t => PNT -> String -> Maybe PNT -> t -> t
--replaceExp pnt@(PNT (PN (UnQual "x") _) _ _) str l exp =
-- error $ "trying to replace "++ show pnt ++" by \""++str++"\" with possible location "++show l ++" in expression "++show exp--pp exp
replaceExp pnt str locPnt exp
= let exp1 = evalState (renamePN (pNTtoPN pnt) Nothing str False exp)
undefined --(([],undefined),undefined)
exp2 = let loc1 = getLoc pnt
loc2 = getSLoc $ fromJust locPnt
in replaceSLoc loc1 loc2 exp1
in if isJust locPnt then exp2
else exp1
where
getLoc = useLoc
getSLoc (PNT (PN _ (S loc)) _ _) = loc
replaceSLoc loc1 loc2 exp = runIdentity $ applyTP strat exp
where strat = full_tdTP (adhocTP idTP replace)
replace (S loc) | loc == loc1 = return $ S loc2
replace x = return x
-- changes the name of a PNT, preserving the remaining information
changeName (PNT (PN (Qual mod v) orig) a b) nv
= (PNT (PN (Qual mod nv) orig) a b)
changeName (PNT (PN (UnQual v) orig) a b) nv
= (PNT (PN (UnQual nv) orig) a b)
-- |Checks if two terms are similar, by using the defined equality, and after some
-- simplifications to the term:
--
-- * all locations are converted to the \"unknown\" location (are ignored)
--
-- * the origin location of the PN's is set to a null position in a file
-- with the same name that the variable, because two PN's are considered
-- to be equal if they have the same origin location, but in this case two
-- PN's should be similar if they have the same name.
similar :: (Eq t1, Term t1) => t1 -> t1 -> Bool
similar x y = unLocate x == unLocate y
where
unLocate = runIdentity . applyTP strat
where strat = full_buTP (idTP `adhocTP` getIdName `adhocTP` eraseLoc `adhocTP` unparenP `adhocTP` unparenE)
getIdName (PN v@(UnQual str) id) = return $ PN v (S (SrcLoc str 0 0 0))
getIdName (PN v@(Qual m str) id) = return $ PN v (S (SrcLoc (pp m ++ str) 0 0 0))
eraseLoc (SrcLoc _ _ _ _) = return loc0
unparenP :: HsPatI PNT -> Identity (HsPatI PNT)
unparenP (Pat (HsPParen p)) = return p
unparenP x = return x
unparenE :: HsExpI PNT -> Identity (HsExpI PNT)
unparenE (Exp (HsParen e)) = return e
unparenE x = return x
-- | Checks if two terms differ by negating the 'similar' definition
differ :: (Eq t1, Term t1) => t1 -> t1 -> Bool
differ x = not . similar x
-- | Checks if a given pattern is a constant. The possible constants are
-- constructors, literals and negations.
isConstant :: HsPatP -> Bool
isConstant (Pat (HsPId (HsCon _))) = True
isConstant (Pat (HsPLit _ _)) = True
isConstant (Pat (HsPNeg _ _)) = True
isConstant _ = False
-- | Converts a constructor with fields in a pattern to the corresponding patterns
-- with the same constructor but without the fields (ex: C {x = myx} --> C myx _)
pRecToPApp (HsPRec constr fields)
= let fieldsNames = getInfo constr
patFields = buildFields fieldsNames fields
in HsPApp constr patFields
where
getInfo x@(PNT _ --(PN name _)
(ConstrOf _ (TypeInfo {constructors = constrs})) _)
= let name = pNTtoName x -- case name of UnQual n -> n; Qual _ n -> n
fields = findFields constrs
findFields [] = Nothing
findFields ((ConInfo {conName = PN n _ , conFields = f}):tl)
| n == name = f
| otherwise = findFields tl
getFieldNames Nothing = error $ "No fields were found for the constructor "++ name
getFieldNames (Just fs) = [str | (PN str _) <- fs]
in getFieldNames fields
buildFields fNames usedFields = map (update usedFields) fNames
where update lst name =
case findName name lst of
Just pat -> pat
Nothing -> Pat HsPWildCard --nameToPat name -- the name doesn't matter, because is only to check consistency
findName _ [] = Nothing
findName name ((HsField pnt pat):fs)
| pNTtoName pnt == name = Just pat
| otherwise = findName name fs
| kmate/HaRe | old/refactorer/RefacUnGuard.hs | bsd-3-clause | 29,191 | 0 | 26 | 8,418 | 8,151 | 4,160 | 3,991 | 365 | 7 |
{-# OPTIONS_GHC -fwarn-missing-import-lists #-}
module T4489 where
import Data.Maybe
import Data.Maybe( Maybe(..) )
import Data.Maybe( Maybe(Just) )
| ezyang/ghc | testsuite/tests/rename/should_compile/T4489.hs | bsd-3-clause | 150 | 0 | 6 | 18 | 38 | 25 | 13 | 5 | 0 |
module Main where
import AIFunctions
import Proxy.Server.Server
import Proxy.Math.Graph
import Hope
import System.Random
import Data.Array
import Control.Monad.State
import Data.Graph.Inductive.Query.Monad ((><))
main :: IO ()
main = Proxy.Server.Server.run onStart potFieldAllAttack
{-
type AdjR = (Int,Int) -> [(Int,Int)]
type Dist b = (Int,Int) -> (Int,Int) -> b
main :: IO ()
main = do
bools <- mapM ioBool testProbabilites
let gridstates = mapM (state.buildGridState) gridSizes
grids = concatMap (evalState gridstates) bools
widthGraphs = map (f eightWay euclD) grids
paths = (pathF (0,1) (99,99))
where
putStr . show $ map paths widthGraphs
return ()
f :: (Real b) => AdjR -> Dist b -> Array (Int,Int) Bool -> (Int, WMGraph a b)
f ar d a = ((+1) . fst . snd . bounds $ a, graphFromGrid ar d a)
--pathF :: (Int,Int) -> (Int,Int) -> (Int,WMGraph a Float) -> Maybe [Node]
pathF o d (w,g) = liftM (map (nodeToPos w)) $ sSastar g (posToNode w o) (posToNode w d) (nodeEuclD w)
testProbabilites = [0.05]
gridSizes = [ (100,100) ]
euclD :: (Int,Int) -> (Int,Int) -> Float
euclD (x,y) (z,w) = sqrt . fromIntegral $ (x - z) ^ 2 + (y - w) ^ 2
nodeEuclD w n m = euclD (nodeToPos w n) (nodeToPos w m)
rows :: Int -> State [a] [[a]]
rows n = do
r <- state (splitAt n)
rs <- rows n
return (r : rs)
posToNode :: Int -> (Int,Int) -> Node
posToNode w (x,y) = w*y + x
nodeToPos :: Int -> Int -> (Int,Int)
nodeToPos w n = (n `rem` w , n `div` w)
graphFromGrid :: (Real b) => AdjR -> Dist b -> Array (Int,Int) Bool -> WMGraph a b
graphFromGrid ar d a = WM . accumArray second Nothing ((0,0),(n*m - 1, n*m -1)) . map (wrap.eToE.f) $ edges ar a
where eToE ((x,y),d) = ((posToNode n x , posToNode n y),d)
f (x,y) = ((x,y), d x y)
wrap = \(x,y) -> (x, Just y)
second _ x = x
(n,m) = ((+1) >< (+1)) . snd . bounds $ a
randomGridGraph :: AdjR -> Dist b -> Int -> Int -> Float -> WMGraph a b
randomGridGraph ar d n m = WM . accumArray second Nothing ((0,0),(n*m - 1, n*m -1)) . map (wrap.eToE.f) . edges ar . buildGrid n m
where eToE ((x,y),d) = ((posToNode n x , posToNode n y),d)
f (x,y) = ((x,y), d x y)
wrap = \(x,y) -> (x, Just y)
second _ x = x
buildRows :: Int -> Int -> Float -> [[Bool]]
buildRows n m = take m . evalState (rows n) . bools
buildGridState :: (Int,Int) -> [Bool] -> (Array (Int,Int) Bool, [Bool])
buildGridState (i,j) bs = (listArray ((0,0),(i-1,j-1)) as, cs)
where (as,cs) = splitAt (i*j) bs
buildGrid :: Int -> Int -> Float -> Array (Int,Int) Bool
buildGrid n m = listArray ((0,0),(n-1,m-1)) . bools
edges :: AdjR -> Array (Int,Int) Bool -> [((Int,Int),(Int,Int))]
edges f a = filter isValid . concatMap (potEdges f) . indices $ a
where isValid (x,y) = inRange (bounds a) x && inRange (bounds a) y && a ! x && a ! y
potEdges :: AdjR -> (Int,Int) -> [((Int,Int),(Int,Int))]
potEdges f x = zip (repeat x) (f x)
fourWay :: AdjR
fourWay (x,y) = [(x-1,y),(x+1,y), (x,y+1), (x,y-1)]
eightWay :: AdjR
eightWay (x,y) = filter (/= (x,y)) (range ((x-1,y-1),(x+1,y+1)))
randomGraph :: Int -> Float -> WMGraph b Int
randomGraph n = buildwGraph n . es
where es = flip zip (repeat 1) . allowed
allowed = map fst . filter snd . zip comp . bools
comp = [(i,j) | i <- [0..n-1] , j <- [0..n-1]]
ioBool :: Float -> IO [Bool]
ioBool p = do
g <- getStdGen
return (map (isObstructed p) (randomRs (0,1) g))
bools :: Float -> [Bool]
bools p = map (isObstructed p) (randomRs (0,1) (mkStdGen 5))
isObstructed :: Float -> Float -> Bool
isObstructed p i
| i > p = True
| i <= p = False
-} | mapinguari/SC_HS_Proxy | src/Main.hs | mit | 3,677 | 0 | 6 | 876 | 78 | 50 | 28 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Network.API.Mandrill.Webhooks where
import Control.Applicative (pure)
import Control.Monad (mzero)
import Data.Aeson (FromJSON, ToJSON, parseJSON,
toJSON)
import Data.Aeson (Value (String))
import Data.Aeson.TH (defaultOptions, deriveJSON)
import Data.Aeson.Types (fieldLabelModifier)
import Data.Set (Set)
import Data.Text (Text)
import qualified Data.Text as T
import Lens.Micro.TH (makeLenses)
import Network.API.Mandrill.HTTP (toMandrillResponse)
import Network.API.Mandrill.Settings
import Network.API.Mandrill.Types
import Network.HTTP.Client (Manager)
data EventHook
= EventSent
| EventDeferred
| EventHardBounced
| EventSoftBounced
| EventOpened
| EventClicked
| EventMarkedAsSpam
| EventUnsubscribed
| EventRejected
deriving (Ord,Eq)
instance Show EventHook where
show e = case e of
EventSent -> "send"
EventDeferred -> "deferral"
EventSoftBounced -> "soft_bounce"
EventHardBounced -> "hard_bounce"
EventOpened -> "open"
EventClicked -> "click"
EventMarkedAsSpam -> "spam"
EventUnsubscribed -> "unsub"
EventRejected -> "reject"
instance FromJSON EventHook where
parseJSON (String s) =
case s of
"send" -> pure EventSent
"deferral" -> pure EventDeferred
"soft_bounce" -> pure EventSoftBounced
"hard_bounce" -> pure EventHardBounced
"open" -> pure EventOpened
"click" -> pure EventClicked
"spam" -> pure EventMarkedAsSpam
"reject" -> pure EventRejected
"unsub" -> pure EventUnsubscribed
x -> fail ("can't parse " ++ show x)
instance ToJSON EventHook where
toJSON e = String (T.pack $ show e)
data WebhookAddRq =
WebhookAddRq
{ _warq_key :: MandrillKey
, _warq_url :: Text
, _warq_description :: Text
, _warq_events :: Set EventHook
} deriving Show
makeLenses ''WebhookAddRq
deriveJSON defaultOptions { fieldLabelModifier = drop 6 } ''WebhookAddRq
| adinapoli/mandrill | src/Network/API/Mandrill/Webhooks.hs | mit | 2,471 | 0 | 12 | 862 | 505 | 280 | 225 | 64 | 0 |
-- 肩検査のモジュール
module Typing (typing, typeOf) where
import Control.Applicative
import Control.Monad
import Control.Monad.Except
import Control.Monad.State
import Control.Lens
import Type
import AST
type TypeEnv = [(Var, Type)]
type TypingM = StateT TypeEnv (Either String)
typing :: AST () -> AST Type
typing ast = case evalStateT (typing' ast) [] of
Right ast' -> ast'
Left err' -> error err'
typing' :: AST t -> TypingM (AST Type)
typing' (AST sentences) = AST <$> mapM typingSentence sentences
where
typingSentence :: Sentence t -> TypingM (Sentence Type)
typingSentence sentence =
case sentence of
Assign var expr -> do t1 <- typeLookup var
e2 <- typingExpr expr
typeAssert t1 (typeOf e2)
return $ Assign var e2
If cond csq alt -> do e1 <- typingExpr cond
typeAssert S32Int (typeOf e1)
a1 <- typing' csq
a2 <- typing' alt
return $ If e1 a1 a2
While cond body -> do e1 <- typingExpr cond
typeAssert S32Int (typeOf e1)
a1 <- typing' body
return $ While e1 a1
Declare v t ini -> do e1 <- typingExpr ini
typeAssert t (typeOf e1)
putVar v t
return $ Declare v t e1
Store dat idx v -> do e1 <- typingExpr dat
e2 <- typingExpr idx
e3 <- typingExpr v
case (typeOf e1, typeOf e2, typeOf e3) of
(Pointer t, S32Int, s) | s == t -> return $ Store e1 e2 e3
otherwise -> lift (throwError "store mismatch")
Call name exprs -> do args <- forM exprs $ \e -> do
e' <- typingExpr e
typeAssert S32Int (typeOf e')
return e'
return $ Call name args
Data v d -> do putVar v (Pointer S32Int)
return $ Data v d
DebugStop -> return DebugStop
putVar v t = modify ((v, t):)
typeLookup :: Var -> TypingM Type
typeLookup var = do st <- get
case lookup var st of
Just x -> return x
Nothing -> throwError ("var not found in type checking" ++ show var)
typingExpr :: Expr t -> TypingM (Expr Type)
typingExpr expr =
case expr of
Arith _ o e1 e2 -> do t1 <- typingExpr e1
t2 <- typingExpr e2
case (typeOf t1, typeOf t2) of
(S32Int, S32Int) -> return $ Arith S32Int o t1 t2
otherwise -> lift (throwError "arithmetic operand error")
Comp _ o e1 e2 -> do t1 <- typingExpr e1
t2 <- typingExpr e2
case (typeOf t1, typeOf t2) of
(S32Int, S32Int) -> return $ Comp S32Int o t1 t2
otherwise -> lift (throwError "comparison operand error")
Load _ dat idx -> do t1 <- typingExpr dat
t2 <- typingExpr idx
case (typeOf t1, typeOf t2) of
(Pointer x, y) | x == y -> return $ Load y t1 t2
otherwise -> lift (throwError "indexing operation error")
ConstS32Int _ int -> return $ ConstS32Int S32Int int
GetVar _ var -> do t <- typeLookup var
return $ GetVar t var
typeOf expr =
case expr of
Arith t _ _ _ -> t
Comp t _ _ _ -> t
ConstS32Int t _ -> t
GetVar t _ -> t
Load t _ _ -> t
typeAssert :: Type -> Type -> TypingM ()
typeAssert t1 t2 | t1 /= t2 = lift (throwError ("type mismatch: " ++ show t1 ++ " != " ++ show t2))
| otherwise = return ()
testAST1 = AST [
Declare (Var "x") S32Int (ConstS32Int () 0),
Data (Var "y") [1, 2, 3],
While (Load () (GetVar () (Var "y")) (GetVar () (Var "x"))) (AST [DebugStop])
]
| ryna4c2e/chage | Typing.hs | mit | 4,641 | 0 | 19 | 2,238 | 1,451 | 680 | 771 | 91 | 9 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGPointList
(js_clear, clear, js_initialize, initialize, js_getItem, getItem,
js_insertItemBefore, insertItemBefore, js_replaceItem, replaceItem,
js_removeItem, removeItem, js_appendItem, appendItem,
js_getNumberOfItems, getNumberOfItems, SVGPointList,
castToSVGPointList, gTypeSVGPointList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"clear\"]()" js_clear ::
JSRef SVGPointList -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPointList.clear Mozilla SVGPointList.clear documentation>
clear :: (MonadIO m) => SVGPointList -> m ()
clear self = liftIO (js_clear (unSVGPointList self))
foreign import javascript unsafe "$1[\"initialize\"]($2)"
js_initialize ::
JSRef SVGPointList -> JSRef SVGPoint -> IO (JSRef SVGPoint)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPointList.initialize Mozilla SVGPointList.initialize documentation>
initialize ::
(MonadIO m) => SVGPointList -> Maybe SVGPoint -> m (Maybe SVGPoint)
initialize self item
= liftIO
((js_initialize (unSVGPointList self) (maybe jsNull pToJSRef item))
>>= fromJSRef)
foreign import javascript unsafe "$1[\"getItem\"]($2)" js_getItem
:: JSRef SVGPointList -> Word -> IO (JSRef SVGPoint)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPointList.getItem Mozilla SVGPointList.getItem documentation>
getItem ::
(MonadIO m) => SVGPointList -> Word -> m (Maybe SVGPoint)
getItem self index
= liftIO ((js_getItem (unSVGPointList self) index) >>= fromJSRef)
foreign import javascript unsafe "$1[\"insertItemBefore\"]($2, $3)"
js_insertItemBefore ::
JSRef SVGPointList -> JSRef SVGPoint -> Word -> IO (JSRef SVGPoint)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPointList.insertItemBefore Mozilla SVGPointList.insertItemBefore documentation>
insertItemBefore ::
(MonadIO m) =>
SVGPointList -> Maybe SVGPoint -> Word -> m (Maybe SVGPoint)
insertItemBefore self item index
= liftIO
((js_insertItemBefore (unSVGPointList self)
(maybe jsNull pToJSRef item)
index)
>>= fromJSRef)
foreign import javascript unsafe "$1[\"replaceItem\"]($2, $3)"
js_replaceItem ::
JSRef SVGPointList -> JSRef SVGPoint -> Word -> IO (JSRef SVGPoint)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPointList.replaceItem Mozilla SVGPointList.replaceItem documentation>
replaceItem ::
(MonadIO m) =>
SVGPointList -> Maybe SVGPoint -> Word -> m (Maybe SVGPoint)
replaceItem self item index
= liftIO
((js_replaceItem (unSVGPointList self) (maybe jsNull pToJSRef item)
index)
>>= fromJSRef)
foreign import javascript unsafe "$1[\"removeItem\"]($2)"
js_removeItem :: JSRef SVGPointList -> Word -> IO (JSRef SVGPoint)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPointList.removeItem Mozilla SVGPointList.removeItem documentation>
removeItem ::
(MonadIO m) => SVGPointList -> Word -> m (Maybe SVGPoint)
removeItem self index
= liftIO
((js_removeItem (unSVGPointList self) index) >>= fromJSRef)
foreign import javascript unsafe "$1[\"appendItem\"]($2)"
js_appendItem ::
JSRef SVGPointList -> JSRef SVGPoint -> IO (JSRef SVGPoint)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPointList.appendItem Mozilla SVGPointList.appendItem documentation>
appendItem ::
(MonadIO m) => SVGPointList -> Maybe SVGPoint -> m (Maybe SVGPoint)
appendItem self item
= liftIO
((js_appendItem (unSVGPointList self) (maybe jsNull pToJSRef item))
>>= fromJSRef)
foreign import javascript unsafe "$1[\"numberOfItems\"]"
js_getNumberOfItems :: JSRef SVGPointList -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPointList.numberOfItems Mozilla SVGPointList.numberOfItems documentation>
getNumberOfItems :: (MonadIO m) => SVGPointList -> m Word
getNumberOfItems self
= liftIO (js_getNumberOfItems (unSVGPointList self)) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/SVGPointList.hs | mit | 4,957 | 64 | 11 | 849 | 1,153 | 639 | 514 | 84 | 1 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
module Leankit.Types.User where
import Data.Aeson.TH
import Leankit.Types.TH
import Leankit.Types.Common
data User = User {
_id :: UserID,
_userName :: String,
_fullName :: Maybe String,
_emailAddress :: Maybe String,
_gravatarFeed :: Maybe String,
_gravatarLink :: Maybe String,
_role :: Maybe Int,
_roleName :: Maybe String,
_enabled :: Maybe Bool,
_isAccountOwner :: Maybe Bool,
_isDeleted :: Maybe Bool,
_dateFormat :: Maybe String,
_wip :: Maybe Int
} deriving (Eq, Show)
$(deriveFromJSON parseOptions ''User)
| dtorok/leankit-hsapi | Leankit/Types/User.hs | mit | 676 | 26 | 9 | 185 | 197 | 111 | 86 | 21 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Applicative (Applicative, (<$>), (<*>))
import Control.Exception (SomeException (..), try)
import Control.Lens
import Control.Monad
import Control.Monad.Error.Class (MonadError, catchError, throwError)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Reader (MonadReader, ReaderT, asks,
runReaderT)
import Control.Monad.Trans
import Control.Monad.Trans.Either (EitherT (..), runEitherT)
import Data.Aeson
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.Char (toLower, toUpper)
import Data.List (intercalate)
import Data.Maybe (listToMaybe)
import Data.Text (pack)
import Network.Wreq
import System.Environment (getArgs, getEnv)
type Word = String
newtype SynonymList = SynonymList {synonyms :: [Word]} deriving (Eq, Show)
newtype AntonymList = AntonymList {antonyms :: [Word]} deriving (Eq, Show)
instance FromJSON SynonymList where
parseJSON (Object v) = SynonymList <$> (v .: "synonyms")
instance FromJSON AntonymList where
parseJSON (Object v) = AntonymList <$> (v .: "antonyms")
data WordsConfig = WordsConfig
{ accessToken :: String }
newtype WordsApp a = WordsApp
{ runW :: EitherT WordsError (ReaderT WordsConfig IO) a }
deriving (Functor, Applicative, Monad,
MonadReader WordsConfig, MonadIO,
MonadError WordsError)
data WordsError = NoResults
| InvalidConfig
| InvalidArgs
deriving (Eq, Show, Read)
class Display d where
display :: d -> String
instance Display WordsError where
display | NoResults = "no results found"
| InvalidConfig = "invalid configuration"
| InvalidArgs = "invalid arguments"
data RequestType = Synonyms
| Antonyms
deriving (Eq, Show, Read)
data WordsRequest = WordsRequest { requestType :: RequestType
, word :: Word } deriving (Eq, Show)
type WordsEnv = EitherT WordsError IO
app :: WordsEnv String
app = do
cfg <- getConfig
req <- parseRequest
EitherT $ runWordsApp (handleRequest req) cfg
main :: IO ()
main = (runEitherT safe) >>= displayResults where
safe = app `catchError` errorHandler
runWordsApp :: WordsApp a -> WordsConfig -> IO (Either WordsError a)
runWordsApp w cfg = runReaderT (runEitherT (runW w)) cfg
getConfig :: WordsEnv WordsConfig
getConfig = do
e <- liftIO $ try (getEnv "WORDS_TOKEN")
case e of
Left (SomeException _) -> throwError InvalidConfig
Right token -> return (WordsConfig token)
guard' :: Bool -> WordsError -> WordsEnv ()
guard' b e = if b then return () else throwError e
capitalize :: String -> String
capitalize [] = []
capitalize (h:t) = toUpper h : map toLower t
parseReqString :: String -> WordsEnv RequestType
parseReqString s = do
let maybeRes = (listToMaybe . reads) (capitalize s) :: Maybe (RequestType, String)
(reqType, excess) <- maybe (throwError InvalidArgs) return maybeRes
guard' (null excess) InvalidArgs
return reqType
parseRequest :: WordsEnv WordsRequest
parseRequest = do
args <- liftIO getArgs
guard' (length args == 2) InvalidArgs
let [reqString, word] = args
reqType <- parseReqString reqString
return $ WordsRequest reqType word
displayResults :: Either WordsError String -> IO ()
displayResults (Left e) = putStrLn $ display e
displayResults (Right r) = putStrLn r
errorHandler :: WordsError -> WordsEnv String
errorHandler = return . display
handleRequest :: WordsRequest -> WordsApp String
handleRequest WordsRequest{..} = case requestType of
Synonyms -> liftM (intercalate ", ") (getSynonyms word)
Antonyms -> liftM (intercalate ", ") (getAntonyms word)
_ -> throwError InvalidArgs
listToMaybe' :: [a] -> Maybe [a]
listToMaybe' [] = Nothing
listToMaybe' xs = Just xs
getSynonyms :: Word -> WordsApp [Word]
getSynonyms w = do
json <- getJSONEndpoint w "synonyms"
let res = decode json >>= listToMaybe' . synonyms
maybe (throwError NoResults) return res
getAntonyms :: Word -> WordsApp [Word]
getAntonyms w = do
json <- getJSONEndpoint w "antonyms"
let res = decode json >>= listToMaybe' . antonyms
maybe (throwError NoResults) return res
-- URL utility functions
type URL = String
baseURL :: URL
baseURL = "http://www.wordsapi.com/words"
buildURL :: Word -> String -> URL
buildURL w endpoint = intercalate "/" [baseURL, w, endpoint]
tryGetWith :: Options -> URL -> WordsApp (Response ByteString)
tryGetWith opts url = do
req <- (liftIO . try) $ getWith opts url
case req of
Left (SomeException _) -> throwError NoResults
Right res -> return res
getJSON :: URL -> WordsApp ByteString
getJSON url = do
token <- asks accessToken
let opts = defaults & param "accessToken" .~ [pack token]
liftM (^. responseBody) $ tryGetWith opts url
getJSONEndpoint :: Word -> String -> WordsApp ByteString
getJSONEndpoint w e = getJSON (buildURL w e)
| charlescharles/words | src/Main.hs | mit | 5,460 | 0 | 12 | 1,446 | 1,648 | 856 | 792 | 126 | 3 |
{-| This library provides functions and datatypes for getting information
about Red Eclipse's game servers.
-}
{-# LANGUAGE RecordWildCards, TemplateHaskell #-}
module Network.RedEclipse.RedFlare
(serversList
,serverQuery
,redFlare
,Result(..)
,Report(..)
,VerInfo(..)
,Version
,Mode
,Mutator
,MasterMode
,GameState
,Platform
,Address(..)
,host
,port
,HostName
,PortNumber
,mapConcurrently) where
import Prelude hiding (take, takeWhile)
import Control.Monad (replicateM, zipWithM_, (<$!>), join)
import Data.Bits (Bits, testBit, zeroBits, (.|.), shift)
import Data.Maybe (mapMaybe, maybe)
import Data.Word (Word8)
import Network.Fancy
import qualified Data.ByteString as W
import qualified Data.ByteString.Char8 as C
import qualified Data.Vector as V
import Data.Aeson (ToJSON(..))
import Data.Aeson.TH (deriveToJSON, defaultOptions, Options(..))
import qualified System.Timeout as Timeout
import qualified System.IO as S
import Control.Concurrent (forkIO)
import Control.Concurrent.MVar (MVar, newEmptyMVar, takeMVar, putMVar)
import Control.DeepSeq (force)
import Data.Attoparsec.Zepto
import Control.Exception (catch, SomeException)
type Result a = Either String a
timeout :: String -> Int -> IO a -> IO (Result a)
timeout place duration action = do
emresult <- (Right <$> Timeout.timeout duration action) `catch` resultCatch
return . join $ maybe (Left $ "timeout: " ++ place) Right <$> emresult
resultCatch :: Monad m => SomeException -> m (Result a)
resultCatch = return . Left . show
secs :: Int -> Int
secs = (* 10^6)
type PortNumber = Int
host :: Address -> HostName
host (IP h _) = h
host (IPv4 h _) = h
host (IPv6 h _) = h
host (Unix h) = h
port :: Address -> Maybe PortNumber
port (IP _ p) = Just p
port (IPv4 _ p) = Just p
port (IPv6 _ p) = Just p
port (Unix _) = Nothing
incPort :: Address -> Address
incPort (IP h p) = IP h (p+1)
incPort (IPv4 h p) = IPv4 h (p+1)
incPort (IPv6 h p) = IPv6 h (p+1)
incPort (Unix h) = Unix h
-- * Red Flare
-- | Takes Red Eclipse server's hostname and port number and returns
-- either error string or server's state report.
serverQuery :: Address -> IO (Result Report)
serverQuery addr = do
rreport <- timeout "on receiving report" (secs 10) (withDgram addr getReport)
return $ (W.drop (length ping) <$> rreport) >>= parse reReport
where
getReport sock = do
send sock (W.pack ping) -- ping id
recv sock enetMaxMTU
ping = [0x02, 0x00]
-- | Red Eclipse uses enet library. Enet transfers data in UDP packets
-- of length no more than 4096.
enetMaxMTU = 4096
-- | Takes master server's hostname and port number. Returns a list
-- of server's connected to that master server.
serversList :: Address -> IO (Result [Address])
serversList masterAddr = do
rcfg <- timeout "on receiving servers list" (secs 10) (withStream masterAddr getServersCfg)
return (parseServers <$> rcfg)
where
getServersCfg handle = do
C.hPut handle (C.pack "list\n")
S.hFlush handle
force <$!> C.hGetContents handle
parseServers = mapMaybe parseAddServer . lines . C.unpack
parseAddServer line =
case words line of
("addserver":host:portString:_) -> Just $ IP host (read portString)
_ -> Nothing
-- | Takes master server's hostname and port number, requests a list of
-- connected servers and polls them to get their current state.
-- Returns a list of tuples where first element contains
-- server's address information and second contains either error string or
-- server's state report.
--
-- This function runs `serversList`, than maps `serverQuery` over the
-- result of `serversList` and zips results of both functions.
redFlare :: Address -> IO (Result [(Address, Result Report)])
redFlare addr = do
eservers <- serversList addr
case eservers of
Right servs -> (Right . zip servs) <$> mapConcurrently (serverQuery . incPort) servs
Left err -> return (Left err)
-- | Parse Red Eclipse's integer compression.
reInt :: Parser Int
reInt = do
w1 <- W.head <$> take 1
case w1 of
128 -> fromLE <$> take 2
129 -> fromLE <$> take 4
_ -> return (fromIntegral w1)
where fromLE = foldr1 (.|.) . zipWith (flip shift) [0,8..] . map fromIntegral . W.unpack
-- String functions
uncolorString :: String -> String
uncolorString ('\f':'[':cs) = uncolorString . drop 1 $ dropWhile (/= ']') cs
uncolorString ('\f':'(':cs) = uncolorString . drop 1 $ dropWhile (/= ')') cs
uncolorString ('\f':'z':cs) = uncolorString $ drop 2 cs
uncolorString ('\f':_ :cs) = uncolorString cs
uncolorString ( c :cs) = c : uncolorString cs
uncolorString [] = []
-- | Convert byte to unicode character supported by Red Eclipse.
wordToChar :: Word8 -> Char
wordToChar w = cube2UniChars V.! fromIntegral w
-- | Lookup table for Red Eclipse's unicode chars.
cube2UniChars = V.fromList "\x00ÀÁÂÃÄÅÆÇ\t\n\x0b\x0c\rÈÉÊËÌÍÎÏÑÒÓÔÕÖ\
\ØÙÚÛ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\
\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÜÝßàáâãäåæçèéêëìíîïñòóôõöøùúû\
\üýÿĄąĆćČčĎďĘęĚěĞğİıŁłŃńŇňŐőŒœŘřŚśŞşŠšŤťŮůŰűŸŹźŻżŽžЄБГДЖЗИЙЛПУФЦЧШ\
\ЩЪЫЬЭЮЯбвгджзийклмнптфцчшщъыьэюяєҐґ"
-- | Parse Red Eclipse's string into Haskell's string.
reString :: Parser String
reString = (map wordToChar . W.unpack) <$> (takeWhile (/= 0) <* take 1)
-- | Parse value's index in `xs` list from input stream
oneOf :: String -> [a] -> Parser a
oneOf what xs = do
idx <- reInt
case drop idx xs of
(x:_) -> return x
[] -> fail (what ++ " is out of range " ++ show idx)
-- | Parse bit mask from input stream and apply it to `xs` list
listOf :: [a] -> Parser [a]
listOf xs = map fst . filter snd . zip xs . bits <$> reInt
-- | Datatype to represent Red Eclipse server's version information.
data VerInfo = VerInfo {
versionMajor :: Int, -- ^ Major Red Eclipse version
versionMinor :: Int, -- ^ Minor Red Eclipse version
versionPatch :: Int, -- ^ Patch Red Eclipse version
versionPlatform :: Platform, -- ^ Platform for which Red Eclipse was compiled
versionArch :: Int -- ^ Architecture for which Red Eclipse was compiled
} deriving (Show, Read)
type Platform = String
platforms = ["Win", "OSX", "Linux/BSD"]
-- | Parse Red Eclipse server's version info
reVerInfo :: Parser VerInfo
reVerInfo = VerInfo <$> reInt
<*> reInt
<*> reInt
<*> oneOf "platform" platforms
<*> reInt
type Version = Int
versions = [220, 226, 229, 230]
validateVersion :: Version -> Parser Version
validateVersion v | v `elem` versions = return v
| otherwise = fail ("unknown version " ++ show v)
-- | Datatype to represent current state of Red Eclipse server
data Report = Report {
playerCnt :: Int, -- ^ Number of players currently connected to a server
version :: Version, -- ^ Protocol's version
gameMode :: Mode, -- ^ Game mode
mutators :: [Mutator], -- ^ List of game mutators
timeRemaining :: Int, -- ^ Time remaining before the end of a current match
serverClients :: Int, -- ^ Maximum number of players that can connect to a server
masterMode :: MasterMode, -- ^ Server's mode
numGameVars :: Int,
numGameMods :: Int,
verInfo :: Maybe VerInfo, -- ^ Server's version information
gameState :: Maybe GameState, -- ^ Current state of the game
timeLeft :: Maybe Int, -- ^ Time left before the end of a current match or overtime
mapName :: String, -- ^ Name of a map currently being played
serverDesc :: String, -- ^ Server's name
verBranch :: Maybe String, -- ^ More version information
playerNames :: [String], -- ^ List of players' names currently connected to a server
handles :: Maybe [String] -- ^ List of players' authentication handles in the same order
-- as `playerNames`. If player is not authenticated the handle is empty string.
} deriving (Show, Read)
type Mode = String
modes = ["demo", "edit", "deathmatch", "capture-the-flag", "defend-and-control", "bomber-ball", "race", "gauntlet"]
-- | Game mutator.
type Mutator = String
versionMuts :: Version -> [Mutator]
versionMuts 220 = ["multi", "ffa", "coop", "insta", "medieval", "kaboom", "duel", "survivor", "classic", "onslaught", "jetpack", "vampire", "expert", "resize"]
versionMuts _ = ["multi", "ffa", "coop", "insta", "medieval", "kaboom", "duel", "survivor", "classic", "onslaught", "freestyle", "vampire", "resize", "hard", "basic"]
gameSpecificMuts :: Version -> Mode -> [Mutator]
gameSpecificMuts n "deathmatch" | n `elem` [229, 230] = ["gladiator", "oldschool"]
gameSpecificMuts _ "capture-the-flag" = ["quick", "defend", "protect"]
gameSpecificMuts _ "defend-and-control" = ["quick", "king"]
gameSpecificMuts 220 "bomber-ball" = ["hold", "touchdown"]
gameSpecificMuts _ "bomber-ball" = ["hold", "basket", "attack"]
gameSpecificMuts 220 "race" = ["timed", "endurance", "gauntlet"]
gameSpecificMuts 220 "gauntlet" = ["timed", "hard"]
gameSpecificMuts _ _ = []
mutatorsOf :: Version -> Mode -> [Mutator]
mutatorsOf version mode = versionMuts version ++ gameSpecificMuts version mode
type MasterMode = String
masterModes = ["open", "veto", "locked", "private", "password"]
type GameState = String
gameStates :: Version -> [GameState]
gameStates 226 = ["waiting", "voting", "intermission", "playing", "overtime"]
gameStates n | n `elem` [229, 230] = ["waiting", "get-map", "send-map", "readying", "game-info", "playing", "overtime", "intermission", "voting"]
gameStates _ = []
parseIf :: Bool -> Parser a -> Parser (Maybe a)
parseIf False _ = return Nothing
parseIf True p = Just <$> p
-- | Parse server's report.
reReport :: Parser Report
reReport = do
playerCnt <- reInt
_attrCnt <- reInt
version <- reInt >>= validateVersion
gameMode <- oneOf "mode" modes
mutators <- listOf (mutatorsOf version gameMode)
timeRemaining <- reInt
serverClients <- reInt
masterMode <- oneOf "master mode" masterModes
numGameVars <- reInt
numGameMods <- reInt
verInfo <- parseIf (version /= 220) reVerInfo
gameState <- parseIf (version /= 220) (oneOf "game state" (gameStates version))
timeLeft <- parseIf (version /= 220) reInt
mapName <- reString
serverDesc <- uncolorString <$> reString
verBranch <- parseIf (version `elem` [229, 230]) reString
playerNames <- map uncolorString <$> replicateM playerCnt reString
handles <- parseIf (version /= 220) (replicateM playerCnt reString)
return Report {..}
-- * General utils
-- | Returns a bits of `b` as a list of `Bool` values.
bits :: Bits b => b -> [Bool]
bits b = map (testBit b) [0..]
mapConcurrently :: (a -> IO b) -> [a] -> IO [b]
mapConcurrently f as = do
vars <- mapM (const newEmptyMVar) as
zipWithM_ inOwnThread vars as
collect vars
where inOwnThread v a = forkIO $ f a >>= putMVar v
collect = mapM takeMVar
-- | ToJSON instances
deriveToJSON defaultOptions { omitNothingFields = True } ''Report
deriveToJSON defaultOptions { omitNothingFields = True } ''VerInfo
| zaquest/redflare | src/Network/RedEclipse/RedFlare.hs | mit | 11,669 | 0 | 13 | 2,647 | 3,080 | 1,672 | 1,408 | 217 | 3 |
module Toaster.Http.Prelude (
module X
) where
import Prelude as X hiding (writeFile, readFile, head, tail, init, last, mapM, length, null, all)
import Control.Applicative as X (Applicative, (<$>), (<*>), (*>), (<*), pure)
import Control.Monad as X (mzero, void, forever, when, unless, liftM, return, (>>=), (>>), Monad, ap, replicateM)
import Control.Monad.IO.Class as X (MonadIO, liftIO)
import Control.Monad.Trans as X (MonadTrans, lift)
import Data.Traversable as X (mapM)
import Data.Maybe as X (listToMaybe) | nhibberd/toaster | src/Toaster/Http/Prelude.hs | mit | 516 | 0 | 5 | 72 | 192 | 134 | 58 | 9 | 0 |
-- Determine the kinds
-- 1. Given
id' :: a -> a
id' a = a
-- What is the kind of a?
-- *
-- 2. r :: a -> f a
-- What are the kinds of a and f?
-- * and *???
-- String processing
-- Because this is the kind of thing linguist co-authors enjoy doing in their spare time.
-- 1. Write a recursive function that takes a text/string, breaks it into words
-- and replaces each instance of ”the” with ”a”. It’s intended- only to replace
-- exactly the word “the”.
notThe :: String -> Maybe String
notThe x = case x of
"the" -> Nothing
otherwise -> Just x
replaceThe :: String -> String
replaceThe = unwords . map (\x -> case notThe x of
Nothing -> "a"
(Just x) -> x) . words
-- 2. Write a recursive function that takes a text/string, breaks it into words,
-- and counts the number of instances of ”the” followed by a vowel-initial word.
-- -- >>> countTheBeforeVowel "the cow"
-- -- 0
-- -- >>> countTheBeforeVowel "the evil cow" -- 1
countTheBeforeVowel :: String -> Integer
countTheBeforeVowel = undefined
-- 3. Return the number of letters that are vowels in a word.
-- Hint: it’s helpful to break this into steps. Add any helper func- tions necessary to achieve your objectives.
-- a) Test for vowelhood
-- b) Return the vowels of a string
-- c) Count the number of elements returned
-- -- >>> countVowels "the cow"
-- -- 2
-- -- >>> countVowels "Mikolajczak" -- 4
-- countVowels :: String -> Integer countVowels = undefined
-- Validate the word
-- Use the Maybe type to write a function that counts the number of vowels in a string and the number of consonants. If the number of vowels exceeds the number of consonants, the function returns Nothing. In many human languages, vowels rarely exceed the number of consonants so when they do, it indicates the input isn’t a real word (that is, a valid input to your dataset):
-- newtype Word' =
-- Word' String deriving (Eq, Show)
-- vowels = "aeiou"
-- mkWord :: String -> Maybe Word'
-- mkWord = undefined It’s only Natural
-- You’ll be presented with a datatype to represent the natural numbers. The only values representable with the naturals are whole numbers from zero to infinity. Your task will be to implement functions to convert Naturals to Integers and Integers to Naturals. The conversion from Naturals to Integers won’t return Maybe because Integers are a strict superset of Naturals. Any Natural can be represented by an Integer, but the same is not true of any Integer. Negative numbers are not valid natural numbers.
-- -- As natural as any competitive bodybuilder
-- data Nat =
-- Zero
-- | Succ Nat
-- deriving (Eq, Show)
-- -- >>> natToInteger Zero
-- -- 0
-- -- >>> natToInteger (Succ Zero)
-- -- 1
-- -- >>> natToInteger (Succ (Succ Zero)) -- 2
-- natToInteger :: Nat -> Integer natToInteger = undefined
-- -- >>> integerToNat 0
-- -- Just Zero
-- -- >>> integerToNat 1
-- -- Just (Succ Zero)
-- -- >>> integerToNat 2
-- -- Just (Succ (Succ Zero))
-- -- >>> integerToNat (-1)
-- -- Nothing
-- integerToNat :: Integer -> Maybe Nat integerToNat = undefined
-- Small library for Maybe
-- Write the following functions. This may take some time.
-- 1. Simple boolean checks for Maybe values. -- >>> isJust (Just 1)
-- -- True
-- -- >>> isJust Nothing
-- -- False
-- isJust :: Maybe a -> Bool
-- -- >>> isNothing (Just 1)
-- -- False
-- -- >>> isNothing Nothing
-- -- True
-- isNothing :: Maybe a -> Bool
-- 2. The following is the Maybe catamorphism. You can turn a Maybe
-- value into anything else with this.
-- -- >>> mayybee 0 (+1) Nothing
-- -- 0
-- -- >>> mayybee 0 (+1) (Just 1)
-- -- 2
-- mayybee :: b -> (a -> b) -> Maybe a -> b
-- 3. In case you just want to provide a fallback value.
-- -- >>> fromMaybe 0 Nothing
-- -- 0
-- -- >>> fromMaybe 0 (Just 1)
-- -- 1
-- fromMaybe :: a -> Maybe a -> a
-- -- Try writing it in terms of the maybe catamorphism
-- 4. Converting between List and Maybe. -- >>> listToMaybe [1, 2, 3]
-- -- Just 1
-- -- >>> listToMaybe []
-- -- Nothing
-- listToMaybe :: [a] -> Maybe a
-- -- >>> maybeToList (Just 1)
-- -- [1]
-- -- >>> maybeToList Nothing
-- -- []
-- maybeToList :: Maybe a -> [a]
-- 5. For when we just want to drop the Nothing values from our list. -- >>> catMaybes [Just 1, Nothing, Just 2]
-- -- [1, 2]
-- -- >>> catMaybes [Nothing, Nothing, Nothing]
-- -- []
-- catMaybes :: [Maybe a] -> [a]
-- 6. You’ll see this called “sequence” later.
-- -- >>> flipMaybe [Just 1, Just 2, Just 3]
-- -- Just [1, 2, 3]
-- -- >>> flipMaybe [Just 1, Nothing, Just 3]
-- -- Nothing
-- flipMaybe :: [Maybe a] -> Maybe [a]
-- Small library for Either
-- Write each of the following functions. If more than one possible unique function exists for the type, use common sense to determine what it should do.
-- 1. Trytoeventuallyarriveatasolutionthatusesfoldr,evenifearlier versions don’t use foldr.
-- lefts' :: [Either a b] -> [a]
-- 2. Same as the last one. Use foldr eventually.
-- rights' :: [Either a b] -> [b]
-- 3. partitionEithers' :: [Either a b] -> ([a], [b])
-- 4. eitherMaybe' :: (b -> c) -> Either a b -> Maybe c
-- 5. This is a general catamorphism for Either values. either' :: (a -> c) -> (b -> c) -> Either a b -> c
-- 6. Same as before, but use the either' function you just wrote. eitherMaybe'' :: (b -> c) -> Either a b -> Maybe c
-- Most of the functions you just saw are in the Prelude, Data.Maybe, or Data.Either but you should strive to write them yourself without looking at existing implementations. You will deprive yourself if you cheat.
-- Unfolds
-- While the idea of catamorphisms is still relatively fresh in our minds, let’s turn our attention to their dual: anamorphisms. If folds, or cata- morphisms, let us break data structures down then unfolds let us build them up. There are, just as with folds, a few different ways to unfold a data structure. We can use them to create finite and infinite data structures alike.
-- -- iterate is like a very limited
-- -- unfold that never ends
-- Prelude> :t iterate
-- iterate :: (a -> a) -> a -> [a]
-- -- because it never ends, we must use
-- -- take to get a finite list
-- Prelude> take 10 $ iterate (+1) 0
-- [0,1,2,3,4,5,6,7,8,9]
-- -- unfoldr is the full monty
-- Prelude> :t unfoldr
-- unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
-- -- Using unfoldr to do the same as thing as iterate
-- Prelude> take 10 $ unfoldr (\b -> Just (b, b+1)) 0
-- [0,1,2,3,4,5,6,7,8,9]
-- Why bother?
-- We bother with this for the same reason we abstracted direct recursion
-- into folds, such as with sum, product, and concat. import Data.List
-- mehSum :: Num a => [a] -> a mehSum xs = go 0 xs
-- where go :: Num a => a -> [a] -> a go n [] = n
-- go n (x:xs) = (go (n+x) xs) niceSum :: Num a => [a] -> a
-- niceSum = foldl' (+) 0
-- mehProduct :: Num a => [a] -> a mehProduct xs = go 1 xs
-- where go :: Num a => a -> [a] -> a go n [] = n
-- go n (x:xs) = (go (n*x) xs) niceProduct :: Num a => [a] -> a
-- niceProduct = foldl' (*) 1
-- Remember the redundant structure when we looked at folds?
-- mehConcat :: [[a]] -> [a] mehConcat xs = go [] xs
-- where go :: [a] -> [[a]] -> [a] go xs' [] = xs'
-- go xs' (x:xs) = (go (xs' ++ x) xs) niceConcat :: [[a]] -> [a]
-- niceConcat = foldr (++) []
-- Your eyes may be spouting gouts of blood, but you may also see that this same principle of abstracting out common patterns and giving them names applies as well to unfolds as it does to folds.
-- Write your own iterate and unfoldr
-- 1. Write the function myIterate using direct recursion. Compare the behavior with the built-in iterate to gauge correctness. Do not look at the source or any examples of iterate so that you are forced to do this yourself.
-- myIterate :: (a -> a) -> a -> [a] myIterate = undefined
-- 2. Write the function myUnfoldr using direct recursion. Compare with the built-in unfoldr to check your implementation. Again, don’t look at implementations of unfoldr so that you figure it out yourself.
-- myUnfoldr :: (b -> Maybe (a, b)) -> b -> [a] myUnfoldr = undefined
-- 3. Rewrite myIterate into betterIterate using myUnfoldr. A hint – we used unfoldr to produce the same results as iterate earlier. Do this with different functions and see if you can abstract the structure out.
-- -- It helps to have the types in front of you
-- -- myUnfoldr :: (b -> Maybe (a, b)) -> b -> [a]
-- betterIterate :: (a -> a) -> a -> [a]
-- betterIterate f x = myUnfoldr ...?
-- Remember, your betterIterate should have the same results as iterate.
-- Prelude> take 10 $ iterate (+1) 0
-- [0,1,2,3,4,5,6,7,8,9]
-- Prelude> take 10 $ betterIterate (+1) 0
-- [0,1,2,3,4,5,6,7,8,9]
-- Finally something other than a list!
-- Given the BinaryTree from last chapter, complete the following exer- cises. Here’s that datatype again:
-- data BinaryTree a = Leaf
-- | Node (BinaryTree a) a (BinaryTree a) deriving (Eq, Ord, Show)
-- 1. Write unfold for BinaryTree.
-- unfold :: (a -> Maybe (a,b,a)) -> a -> BinaryTree b unfold = undefined
-- 2. Make a tree builder.
-- Using the unfold function you’ve just made for BinaryTree, write the following function:
-- treeBuild :: Integer -> BinaryTree Integer
-- treeBuild n = undefined
-- You should be producing results that look like the following:
-- Prelude> treeBuild 0
-- Leaf
-- Prelude> treeBuild 1
-- Node Leaf 0 Leaf
-- Prelude> treeBuild 2
-- Node (Node Leaf 1 Leaf)
-- 0
-- (Node Leaf 1 Leaf)
-- Prelude> treeBuild 3
-- Node (Node (Node Leaf 2 Leaf)
-- 1
-- (Node Leaf 2 Leaf))
-- 0
-- (Node (Node Leaf 2 Leaf)
-- 1
-- (Node Leaf 2 Leaf))
-- Or in a slightly different representation:
-- 0
-- 0 /\ 11
-- 0 /\
-- 11 /\ /\ 22 22
-- Good work.
--
| diminishedprime/.org | reading-list/haskell_programming_from_first_principles/12_05.hs | mit | 9,864 | 0 | 14 | 2,133 | 323 | 260 | 63 | 12 | 2 |
module LetWhere where
----------------------
-- LET BINDINGS -----
-- are bottom up -----
-- -------------------
-- let bindings as like variable assignments but they are more permanent and they scope things nicely.
-- this fancySeven doesn't do much but shows how we can assign values
fancySeven :: Integer
fancySeven =
let a = 3 -- let keyword start the binding
in 2 * a + 1
-- our function only return us a 7 cause there were no inputs from us they were already given.
-- *LetWhere> fancySeven
-- 7
fancy9 =
let x = 4
y = 5
in x + y
-- *LetWhere> fancy9
-- 9
removeOdd [] = []
removeOdd (x:xs)
| mod x 2 == 0 = x : (removeOdd xs)
| otherwise = removeOdd xs
numEven :: Integral a => [a] -> Int
numEven nums =
let evenNums = removeOdd nums
in length evenNums
-- *LetWhere> numEven [1..33]
-- 16
--
------------------------------------------------------------------
-- where bindings must be associated with a function definition --
-- top down
-- ---------------------------------------------------------------
fancyNine = x + y
where x = 4
y = 5
-- *LetWhere> fancyNine
-- 9
-- fancy10 = 2 * (a + 1 where a = 4)
-- parse error on input `where'
fancyTen = 2 * (let a = 4 in a + 1)
-- *LetWhere> fancyTen
-- 10
cylinder :: Floating a => a -> a -> a
cylinder r h =
let sideArea = 2 * pi * r * h
topArea = pi * r ^ 2
in sideArea + 2 * topArea
| HaskellForCats/HaskellForCats | MenaBeginning/Ch008/2014-0214letWhere.hs | mit | 1,434 | 0 | 11 | 355 | 313 | 170 | 143 | 26 | 1 |
module ToyRobot.Point where
import Data.Number.CReal
data Point = Point CReal CReal
le :: Point -> Point -> Bool
le (Point x1 y1) (Point x2 y2) = (x1 <= x2) && (y1 <= y2)
ge :: Point -> Point -> Bool
ge (Point x1 y1) (Point x2 y2) = (x1 >= x2) && (y1 >= y2)
plus :: Point -> Point -> Point
plus (Point x1 y1) (Point x2 y2) = Point (x1 + x2) (y1 + y2)
instance Show Point where
show (Point x y) = show x ++ "," ++ show y
instance Eq Point where
(Point x y) == (Point xx yy) = x == xx && y == yy
| lokulin/toy-robot-haskell | src/lib/ToyRobot/Point.hs | mit | 505 | 0 | 8 | 123 | 280 | 145 | 135 | 13 | 1 |
module Diagonal where
import qualified Data.MemoCombinators as Memo
import Math.NumberTheory.Powers
getCode :: Integer -> Integer -> Integer
getCode i = getNthCode . nFromCoord i
nFromCoord :: Integer -> Integer -> Integer
nFromCoord = Memo.memo2 Memo.integral Memo.integral nFromCoord'
where nFromCoord' 1 j = (j * (j+1)) `div` 2
nFromCoord' i j = (j + (i-2)) + nFromCoord (i-1) j
getNthCode :: Integer -> Integer
getNthCode n = 20151125 * powerMod 252533 (n-1) 33554393 `mod` 33554393
| corajr/adventofcode2015 | 25/src/Diagonal.hs | mit | 501 | 0 | 11 | 88 | 190 | 104 | 86 | 11 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.Supervisor
import Control.Exception
job1 :: IO ()
job1 = do
threadDelay 5000000
fail "Dead"
job2 :: ThreadId -> IO ()
job2 tid = do
threadDelay 3000000
killThread tid
job3 :: IO ()
job3 = do
threadDelay 5000000
error "Oh boy, I'm good as dead"
job4 :: IO ()
job4 = threadDelay 7000000
job5 :: IO ()
job5 = threadDelay 100 >> error "dead"
main :: IO ()
main = bracketOnError (do
sup1 <- newSupervisor OneForOne
sup2 <- newSupervisor OneForOne
sup2ThreadId <- monitorWith fibonacciRetryPolicy sup1 sup2
putStrLn $ "Supervisor 2 has ThreadId: " ++ show sup2ThreadId
_ <- forkSupervised sup2 fibonacciRetryPolicy job3
j1 <- forkSupervised sup1 fibonacciRetryPolicy job1
_ <- forkSupervised sup1 fibonacciRetryPolicy (job2 j1)
_ <- forkSupervised sup1 fibonacciRetryPolicy job4
_ <- forkSupervised sup1 fibonacciRetryPolicy job5
_ <- forkIO (go (eventStream sup1))
-- We kill sup2
throwTo sup2ThreadId (AssertionFailed "sup2, die please.")
return sup1) shutdownSupervisor (\_ -> threadDelay 10000000000)
where
go eS = do
newE <- atomically $ readQueue eS
print newE
go eS
| adinapoli/threads-supervisor | examples/Main.hs | mit | 1,273 | 0 | 14 | 245 | 397 | 184 | 213 | 40 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.