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 OverloadedStrings #-} module Gittins.Config ( Config(..) , RuntimeConfig(..) , GroupId , Repository(..) , loadConfig , saveConfig , mkRepoName , modifyRepository , addToGroups ) where import Control.Applicative ((<|>), (<$>)) import Data.Foldable (foldMap) import Data.HashMap.Strict (HashMap, empty, foldrWithKey, fromList) import Data.Ini (Ini(..), readIniFile, writeIniFile) import Data.List (nub) import Data.Maybe (catMaybes, fromMaybe) import Data.Text (Text, pack, unpack) import System.Directory (doesFileExist, getHomeDirectory) import System.FilePath ((</>), takeFileName) import qualified Data.HashMap.Strict as HM import qualified Data.Text as T type Workers = Int data RuntimeConfig = RuntimeConfig Workers loadConfig :: IO Config loadConfig = fmap fromIni loadIni saveConfig :: Config -> IO () saveConfig config = do iniPath <- configFile writeIniFile iniPath (toIni config) data Config = Config { repositories :: [Repository] } deriving (Eq, Ord, Show) type GroupId = String data Repository = Repository { repoName :: String , repoPath :: FilePath , repoGroups :: [GroupId] } deriving (Eq, Ord, Show) configFile :: IO FilePath configFile = do homeDir <- getHomeDirectory return (homeDir </> ".gittins") mkRepoName :: FilePath -> String mkRepoName = takeFileName loadIni :: IO Ini loadIni = do iniPath <- configFile fileExists <- doesFileExist iniPath ini <- if fileExists then readIniFile iniPath else return $ Right (Ini empty) case ini of Right i -> return i Left _ -> error $ "Failed to parse INI format [" ++ iniPath ++ "]" fromIni :: Ini -> Config fromIni (Ini repos) = Config $ foldrWithKey (\n ps -> (repository n ps :)) [] repos where repository :: Text -> HashMap Text Text -> Repository repository path props = Repository (fromMaybe (mkRepoName $ unpack path) $ unpack <$> HM.lookup "name" props) (unpack path) (foldMap parseGroups $ HM.lookup "group" props) parseGroups :: Text -> [GroupId] parseGroups = map unpack . nub . T.words toIni :: Config -> Ini toIni (Config repos) = Ini $ fromList (map fromRepository repos) where fromRepository :: Repository -> (Text, HashMap Text Text) fromRepository repo@(Repository _ p _) = (pack p, settings repo) settings :: Repository -> HashMap Text Text settings (Repository name _ gs) = let group = if null gs then Nothing else Just ("group", T.pack $ unwords (nub gs)) in fromList (("name", pack name) : catMaybes [group]) -- | Given a function from 'Repository' to 'Maybe' 'Repository', returns the -- first 'Just' result obtained by applying the function to each 'Repository', -- or 'Nothing' otherwise. modifyRepository :: (Repository -> Maybe Repository) -> Config -> Maybe Config modifyRepository f (Config repos) = fmap Config (go repos) where go (r:rs) = fmap (:rs) (f r) <|> fmap (r:) (go rs) go [] = Nothing addToGroups :: [GroupId] -> FilePath -> Config -> Maybe Config addToGroups groupIds path = modifyRepository $ \(Repository n p gs) -> if p == path then Just $ Repository n p (nub $ groupIds ++ gs) else Nothing
bmjames/gittins
src/Gittins/Config.hs
bsd-3-clause
3,366
0
17
820
1,082
586
496
76
3
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ATI.VertexArrayObject -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ATI.VertexArrayObject ( -- * Extension Support glGetATIVertexArrayObject, gl_ATI_vertex_array_object, -- * Enums pattern GL_ARRAY_OBJECT_BUFFER_ATI, pattern GL_ARRAY_OBJECT_OFFSET_ATI, pattern GL_DISCARD_ATI, pattern GL_DYNAMIC_ATI, pattern GL_OBJECT_BUFFER_SIZE_ATI, pattern GL_OBJECT_BUFFER_USAGE_ATI, pattern GL_PRESERVE_ATI, pattern GL_STATIC_ATI, -- * Functions glArrayObjectATI, glFreeObjectBufferATI, glGetArrayObjectfvATI, glGetArrayObjectivATI, glGetObjectBufferfvATI, glGetObjectBufferivATI, glGetVariantArrayObjectfvATI, glGetVariantArrayObjectivATI, glIsObjectBufferATI, glNewObjectBufferATI, glUpdateObjectBufferATI, glVariantArrayObjectATI ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/ATI/VertexArrayObject.hs
bsd-3-clause
1,249
0
5
162
125
86
39
27
0
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} module Hamath.Map where import Data.Aeson import Linear.Affine ( Point(..) ) type Rect = ( Float, Float, Float, Float ) data Obstacle = Obstacle !Float !Float !Float !Float deriving ( Show, Eq ) class Collisionable a where toRect :: a -> Rect intersect :: Collisionable b => a -> b -> Bool intersect a b = not $ ( x1 > x2 + w2 ) || ( x1 + w1 < x2 ) || ( y1 > y2 + h2 ) || ( y1 + h1 < y2 ) where ( x1, y1, w1, h1 ) = toRect a ( x2, y2, w2, h2 ) = toRect b instance Collisionable Obstacle where toRect ( Obstacle x y w h ) = ( x, y, w, h ) data Map = Map { obstacles :: ![ Obstacle ] } deriving ( Show, Eq ) mapCollise :: Collisionable a => Map -> a -> Bool mapCollise Map{..} obj = any ( intersect obj ) obstacles data Tileset = Tileset { columns :: Int , firstgid :: Int , imagePath :: FilePath , name :: String } deriving ( Show, Eq ) data Layer = Layer { layerName :: String , datum :: [ Int ] } deriving ( Show, Eq ) data Chunk = Chunk { nextobjectid :: Int , tilesets :: [ Tileset ] , layers :: [ Layer ] } deriving ( Show, Eq ) instance FromJSON Tileset where parseJSON ( Object v ) = Tileset <$> v .: "columns" <*> v .: "firstgid" <*> v .: "image" <*> v .: "name" instance FromJSON Layer where parseJSON ( Object v ) = Layer <$> v .: "name" <*> v .: "data" instance FromJSON Chunk where parseJSON ( Object v ) = Chunk <$> v .: "nextobjectid" <*> v .: "tilesets" <*> v .: "layers"
triplepointfive/hamath
src/Hamath/Map.hs
bsd-3-clause
1,604
0
13
461
605
331
274
66
1
{-# LANGUAGE Rank2Types #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric.AD.Types -- Copyright : (c) Edward Kmett 2010-12 -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC only -- ----------------------------------------------------------------------------- module Numeric.AD.Types ( -- * AD modes Mode(..) -- * AD variables , AD(..) -- * Jets , Jet(..) , headJet , tailJet , jet -- * Apply functions that use 'lift' , lowerUU, lowerUF, lowerFU, lowerFF ) where import Numeric.AD.Internal.Identity import Numeric.AD.Internal.Types import Numeric.AD.Internal.Jet import Numeric.AD.Internal.Classes -- | Evaluate a scalar-to-scalar function in the trivial identity AD mode. lowerUU :: (forall s. Mode s => AD s a -> AD s a) -> a -> a lowerUU f = unprobe . f . probe {-# INLINE lowerUU #-} -- | Evaluate a scalar-to-nonscalar function in the trivial identity AD mode. lowerUF :: (forall s. Mode s => AD s a -> f (AD s a)) -> a -> f a lowerUF f = unprobed . f . probe {-# INLINE lowerUF #-} -- | Evaluate a nonscalar-to-scalar function in the trivial identity AD mode. lowerFU :: (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> a lowerFU f = unprobe . f . probed {-# INLINE lowerFU #-} -- | Evaluate a nonscalar-to-nonscalar function in the trivial identity AD mode. lowerFF :: (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g a lowerFF f = unprobed . f . probed {-# INLINE lowerFF #-}
yairchu/ad
src/Numeric/AD/Types.hs
bsd-3-clause
1,584
0
12
339
370
210
160
26
1
{- mkindex :: Making index.html for the current directory. -} import Control.Applicative import Data.Time import Data.Time.Clock.POSIX import Locale import System.Directory import System.Posix.Files import Text.Printf import Data.Bits indexFile :: String indexFile = "index.html" main :: IO () main = do contents <- mkContents writeFile indexFile $ header ++ contents ++ tailer setFileMode indexFile mode where mode = ownerReadMode .|. ownerWriteMode .|. groupReadMode .|. otherReadMode mkContents :: IO String mkContents = do fileNames <- filter dotAndIndex <$> getDirectoryContents "." stats <- mapM getFileStatus fileNames let fmsls = map pp $ zip fileNames stats maxLen = maximum $ map (\(_,_,_,x) -> x) fmsls contents = concatMap (content maxLen) fmsls return contents where dotAndIndex x = head x /= '.' && x /= indexFile pp :: (String,FileStatus) -> (String,String,String,Int) pp (f,st) = (file,mtime,size,flen) where file = ppFile f st flen = length file mtime = ppMtime st size = ppSize st ppFile :: String -> FileStatus -> String ppFile f st | isDirectory st = f ++ "/" | otherwise = f ppMtime :: FileStatus -> String ppMtime st = dateFormat . epochTimeToUTCTime $ st where epochTimeToUTCTime = posixSecondsToUTCTime . realToFrac . modificationTime dateFormat = formatTime defaultTimeLocale "%d-%b-%Y %H:%M" ppSize :: FileStatus -> String ppSize st | isDirectory st = " - " | otherwise = sizeFormat . fromIntegral . fileSize $ st where sizeFormat siz = unit siz [' ','K','M','G','T'] unit _ [] = undefined unit s [u] = format s u unit s (u:us) | s >= 1024 = unit (s `div` 1024) us | otherwise = format s u format :: Integer -> Char -> String format = printf "%3d%c" header :: String header = "\ \<html>\n\ \<head>\n\ \<style type=\"text/css\">\n\ \<!--\n\ \body { padding-left: 10%; }\n\ \h1 { font-size: x-large; }\n\ \pre { font-size: large; }\n\ \hr { text-align: left; margin-left: 0px; width: 80% }\n\ \--!>\n\ \</style>\n\ \</head>\n\ \<title>Directory contents</title>\n\ \<body>\n\ \<h1>Directory contents</h1>\n\ \<hr>\n\ \<pre>\n" content :: Int -> (String,String,String,Int) -> String content lim (f,m,s,len) = "<a href=\"" ++ f ++ "\">" ++ f ++ "</a> " ++ replicate (lim - len) ' ' ++ m ++ " " ++ s ++ "\n" tailer :: String tailer = "\ \</pre>\n\ \<hr>\n\ \</body>\n\ \</html>\n"
mwotton/sofadb
mkindex.hs
bsd-3-clause
2,458
0
14
518
746
389
357
57
3
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} -- ------------------------------------------------------------ {- | Module : Yuuko.Control.Arrow.ArrowState Copyright : Copyright (C) 2005 Uwe Schmidt License : MIT Maintainer : Uwe Schmidt (uwe\@fh-wedel.de) Stability : experimental Portability: multy parameter classes and functional depenedencies required Arrows for managing an explicit state State arrows work similar to state monads. A state value is threaded through the application of arrows. -} -- ------------------------------------------------------------ module Yuuko.Control.Arrow.ArrowState ( ArrowState(..) ) where import Control.Arrow -- | The interface for accessing and changing the state component. -- -- Multi parameter classes and functional dependencies are required. class Arrow a => ArrowState s a | a -> s where -- | change the state of a state arrow by applying a function -- for computing a new state from the old and the arrow input. -- Result is the arrow input changeState :: (s -> b -> s) -> a b b -- | access the state with a function using the arrow input -- as data for selecting state components. accessState :: (s -> b -> c) -> a b c -- | read the complete state, ignore arrow input -- -- definition: @ getState = accessState (\\ s x -> s) @ getState :: a b s getState = accessState (\ s _x -> s) -- | overwrite the old state -- -- definition: @ setState = changeState (\\ s x -> x) @ setState :: a s s setState = changeState (\ _s x -> x) -- changeState (const id) -- | change state (and ignore input) and return new state -- -- convenience function, -- usefull for generating e.g. unique identifiers: -- -- example with SLA state list arrows -- -- > newId :: SLA Int b String -- > newId = nextState (+1) -- > >>> -- > arr (('#':) . show) -- > -- > runSLA 0 (newId <+> newId <+> newId) undefined -- > = ["#1", "#2", "#3"] nextState :: (s -> s) -> a b s nextState sf = changeState (\s -> const (sf s)) >>> getState -- ------------------------------------------------------------
nfjinjing/yuuko
src/Yuuko/Control/Arrow/ArrowState.hs
bsd-3-clause
2,264
25
10
577
250
153
97
15
0
-- -- @file -- -- @brief Regex generation for enums -- -- @copyright BSD License (see LICENSE.md or https://www.libelektra.org) -- {-# LANGUAGE TupleSections #-} module Elektra.EnumDispatcher (enumDispatch) where import Elektra.Key import Elektra.KeySet import Elektra.Dispatch import Elektra.Range import Elektra.Parsers import Data.List (intercalate, permutations) import Control.Monad (mapM) import Data.Maybe (catMaybes) enumDispatch :: Dispatcher enumDispatch ks = ksList ks >>= fmap catMaybes . mapM dispatch where dispatch k = do es <- filterMeta "check/enum/#" k if null es then return Nothing else keyGetMeta k "check/enum/multi" >>= ifKey (singleEnum es) (multiEnum es) >>= return . Just . (k, "check/validation", ) multiEnum es s = do s <- keyString s let group = ('(' :) . (++ ")") . intercalate s let genUniqueCombinations = intercalate "|" . map group . permutations fmap genUniqueCombinations . mapM keyString $ es singleEnum = fmap (intercalate "|") . mapM keyString
e1528532/libelektra
src/plugins/regexdispatcher/Elektra/EnumDispatcher.hs
bsd-3-clause
1,101
0
16
259
300
156
144
24
2
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Program.Db -- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009 -- -- Maintainer : [email protected] -- Portability : portable -- -- This provides a 'ProgramDb' type which holds configured and not-yet -- configured programs. It is the parameter to lots of actions elsewhere in -- Cabal that need to look up and run programs. If we had a Cabal monad, -- the 'ProgramDb' would probably be a reader or state component of it. -- -- One nice thing about using it is that any program that is -- registered with Cabal will get some \"configure\" and \".cabal\" -- helpers like --with-foo-args --foo-path= and extra-foo-args. -- -- There's also a hook for adding programs in a Setup.lhs script. See -- hookedPrograms in 'Distribution.Simple.UserHooks'. This gives a -- hook user the ability to get the above flags and such so that they -- don't have to write all the PATH logic inside Setup.lhs. module Distribution.Simple.Program.Db ( -- * The collection of configured programs we can run ProgramDb, emptyProgramDb, defaultProgramDb, restoreProgramDb, -- ** Query and manipulate the program db addKnownProgram, addKnownPrograms, lookupKnownProgram, knownPrograms, getProgramSearchPath, setProgramSearchPath, modifyProgramSearchPath, userSpecifyPath, userSpecifyPaths, userMaybeSpecifyPath, userSpecifyArgs, userSpecifyArgss, userSpecifiedArgs, lookupProgram, updateProgram, configuredPrograms, -- ** Query and manipulate the program db configureProgram, configureAllKnownPrograms, lookupProgramVersion, reconfigurePrograms, requireProgram, requireProgramVersion, ) where import Distribution.Simple.Program.Types ( Program(..), ProgArg, ConfiguredProgram(..), ProgramLocation(..) ) import Distribution.Simple.Program.Find ( ProgramSearchPath, defaultProgramSearchPath , findProgramOnSearchPath, programSearchPathAsPATHVar ) import Distribution.Simple.Program.Builtin ( builtinPrograms ) import Distribution.Simple.Utils ( die, doesExecutableExist ) import Distribution.Version ( Version, VersionRange, isAnyVersion, withinRange ) import Distribution.Text ( display ) import Distribution.Verbosity ( Verbosity ) import Distribution.Compat.Binary (Binary(..)) import Data.List ( foldl' ) import Data.Maybe ( catMaybes ) import qualified Data.Map as Map import Control.Monad ( join, foldM ) -- ------------------------------------------------------------ -- * Programs database -- ------------------------------------------------------------ -- | The configuration is a collection of information about programs. It -- contains information both about configured programs and also about programs -- that we are yet to configure. -- -- The idea is that we start from a collection of unconfigured programs and one -- by one we try to configure them at which point we move them into the -- configured collection. For unconfigured programs we record not just the -- 'Program' but also any user-provided arguments and location for the program. data ProgramDb = ProgramDb { unconfiguredProgs :: UnconfiguredProgs, progSearchPath :: ProgramSearchPath, configuredProgs :: ConfiguredProgs } type UnconfiguredProgram = (Program, Maybe FilePath, [ProgArg]) type UnconfiguredProgs = Map.Map String UnconfiguredProgram type ConfiguredProgs = Map.Map String ConfiguredProgram emptyProgramDb :: ProgramDb emptyProgramDb = ProgramDb Map.empty defaultProgramSearchPath Map.empty defaultProgramDb :: ProgramDb defaultProgramDb = restoreProgramDb builtinPrograms emptyProgramDb -- internal helpers: updateUnconfiguredProgs :: (UnconfiguredProgs -> UnconfiguredProgs) -> ProgramDb -> ProgramDb updateUnconfiguredProgs update conf = conf { unconfiguredProgs = update (unconfiguredProgs conf) } updateConfiguredProgs :: (ConfiguredProgs -> ConfiguredProgs) -> ProgramDb -> ProgramDb updateConfiguredProgs update conf = conf { configuredProgs = update (configuredProgs conf) } -- Read & Show instances are based on listToFM -- Note that we only serialise the configured part of the database, this is -- because we don't need the unconfigured part after the configure stage, and -- additionally because we cannot read/show 'Program' as it contains functions. instance Show ProgramDb where show = show . Map.toAscList . configuredProgs instance Read ProgramDb where readsPrec p s = [ (emptyProgramDb { configuredProgs = Map.fromList s' }, r) | (s', r) <- readsPrec p s ] instance Binary ProgramDb where put = put . configuredProgs get = do progs <- get return $! emptyProgramDb { configuredProgs = progs } -- | The Read\/Show instance does not preserve all the unconfigured 'Programs' -- because 'Program' is not in Read\/Show because it contains functions. So to -- fully restore a deserialised 'ProgramDb' use this function to add -- back all the known 'Program's. -- -- * It does not add the default programs, but you probably want them, use -- 'builtinPrograms' in addition to any extra you might need. -- restoreProgramDb :: [Program] -> ProgramDb -> ProgramDb restoreProgramDb = addKnownPrograms -- ------------------------------- -- Managing unconfigured programs -- | Add a known program that we may configure later -- addKnownProgram :: Program -> ProgramDb -> ProgramDb addKnownProgram prog = updateUnconfiguredProgs $ Map.insertWith combine (programName prog) (prog, Nothing, []) where combine _ (_, path, args) = (prog, path, args) addKnownPrograms :: [Program] -> ProgramDb -> ProgramDb addKnownPrograms progs conf = foldl' (flip addKnownProgram) conf progs lookupKnownProgram :: String -> ProgramDb -> Maybe Program lookupKnownProgram name = fmap (\(p,_,_)->p) . Map.lookup name . unconfiguredProgs knownPrograms :: ProgramDb -> [(Program, Maybe ConfiguredProgram)] knownPrograms conf = [ (p,p') | (p,_,_) <- Map.elems (unconfiguredProgs conf) , let p' = Map.lookup (programName p) (configuredProgs conf) ] -- | Get the current 'ProgramSearchPath' used by the 'ProgramDb'. -- This is the default list of locations where programs are looked for when -- configuring them. This can be overridden for specific programs (with -- 'userSpecifyPath'), and specific known programs can modify or ignore this -- search path in their own configuration code. -- getProgramSearchPath :: ProgramDb -> ProgramSearchPath getProgramSearchPath = progSearchPath -- | Change the current 'ProgramSearchPath' used by the 'ProgramDb'. -- This will affect programs that are configured from here on, so you -- should usually set it before configuring any programs. -- setProgramSearchPath :: ProgramSearchPath -> ProgramDb -> ProgramDb setProgramSearchPath searchpath db = db { progSearchPath = searchpath } -- | Modify the current 'ProgramSearchPath' used by the 'ProgramDb'. -- This will affect programs that are configured from here on, so you -- should usually modify it before configuring any programs. -- modifyProgramSearchPath :: (ProgramSearchPath -> ProgramSearchPath) -> ProgramDb -> ProgramDb modifyProgramSearchPath f db = setProgramSearchPath (f $ getProgramSearchPath db) db -- |User-specify this path. Basically override any path information -- for this program in the configuration. If it's not a known -- program ignore it. -- userSpecifyPath :: String -- ^Program name -> FilePath -- ^user-specified path to the program -> ProgramDb -> ProgramDb userSpecifyPath name path = updateUnconfiguredProgs $ flip Map.update name $ \(prog, _, args) -> Just (prog, Just path, args) userMaybeSpecifyPath :: String -> Maybe FilePath -> ProgramDb -> ProgramDb userMaybeSpecifyPath _ Nothing conf = conf userMaybeSpecifyPath name (Just path) conf = userSpecifyPath name path conf -- |User-specify the arguments for this program. Basically override -- any args information for this program in the configuration. If it's -- not a known program, ignore it.. userSpecifyArgs :: String -- ^Program name -> [ProgArg] -- ^user-specified args -> ProgramDb -> ProgramDb userSpecifyArgs name args' = updateUnconfiguredProgs (flip Map.update name $ \(prog, path, args) -> Just (prog, path, args ++ args')) . updateConfiguredProgs (flip Map.update name $ \prog -> Just prog { programOverrideArgs = programOverrideArgs prog ++ args' }) -- | Like 'userSpecifyPath' but for a list of progs and their paths. -- userSpecifyPaths :: [(String, FilePath)] -> ProgramDb -> ProgramDb userSpecifyPaths paths conf = foldl' (\conf' (prog, path) -> userSpecifyPath prog path conf') conf paths -- | Like 'userSpecifyPath' but for a list of progs and their args. -- userSpecifyArgss :: [(String, [ProgArg])] -> ProgramDb -> ProgramDb userSpecifyArgss argss conf = foldl' (\conf' (prog, args) -> userSpecifyArgs prog args conf') conf argss -- | Get the path that has been previously specified for a program, if any. -- userSpecifiedPath :: Program -> ProgramDb -> Maybe FilePath userSpecifiedPath prog = join . fmap (\(_,p,_)->p) . Map.lookup (programName prog) . unconfiguredProgs -- | Get any extra args that have been previously specified for a program. -- userSpecifiedArgs :: Program -> ProgramDb -> [ProgArg] userSpecifiedArgs prog = maybe [] (\(_,_,as)->as) . Map.lookup (programName prog) . unconfiguredProgs -- ----------------------------- -- Managing configured programs -- | Try to find a configured program lookupProgram :: Program -> ProgramDb -> Maybe ConfiguredProgram lookupProgram prog = Map.lookup (programName prog) . configuredProgs -- | Update a configured program in the database. updateProgram :: ConfiguredProgram -> ProgramDb -> ProgramDb updateProgram prog = updateConfiguredProgs $ Map.insert (programId prog) prog -- | List all configured programs. configuredPrograms :: ProgramDb -> [ConfiguredProgram] configuredPrograms = Map.elems . configuredProgs -- --------------------------- -- Configuring known programs -- | Try to configure a specific program. If the program is already included in -- the collection of unconfigured programs then we use any user-supplied -- location and arguments. If the program gets configured successfully it gets -- added to the configured collection. -- -- Note that it is not a failure if the program cannot be configured. It's only -- a failure if the user supplied a location and the program could not be found -- at that location. -- -- The reason for it not being a failure at this stage is that we don't know up -- front all the programs we will need, so we try to configure them all. -- To verify that a program was actually successfully configured use -- 'requireProgram'. -- configureProgram :: Verbosity -> Program -> ProgramDb -> IO ProgramDb configureProgram verbosity prog conf = do let name = programName prog maybeLocation <- case userSpecifiedPath prog conf of Nothing -> programFindLocation prog verbosity (progSearchPath conf) >>= return . fmap FoundOnSystem Just path -> do absolute <- doesExecutableExist path if absolute then return (Just (UserSpecified path)) else findProgramOnSearchPath verbosity (progSearchPath conf) path >>= maybe (die notFound) (return . Just . UserSpecified) where notFound = "Cannot find the program '" ++ name ++ "'. User-specified path '" ++ path ++ "' does not refer to an executable and " ++ "the program is not on the system path." case maybeLocation of Nothing -> return conf Just location -> do version <- programFindVersion prog verbosity (locationPath location) newPath <- programSearchPathAsPATHVar (progSearchPath conf) let configuredProg = ConfiguredProgram { programId = name, programVersion = version, programDefaultArgs = [], programOverrideArgs = userSpecifiedArgs prog conf, programOverrideEnv = [("PATH", Just newPath)], programProperties = Map.empty, programLocation = location } configuredProg' <- programPostConf prog verbosity configuredProg return (updateConfiguredProgs (Map.insert name configuredProg') conf) -- | Configure a bunch of programs using 'configureProgram'. Just a 'foldM'. -- configurePrograms :: Verbosity -> [Program] -> ProgramDb -> IO ProgramDb configurePrograms verbosity progs conf = foldM (flip (configureProgram verbosity)) conf progs -- | Try to configure all the known programs that have not yet been configured. -- configureAllKnownPrograms :: Verbosity -> ProgramDb -> IO ProgramDb configureAllKnownPrograms verbosity conf = configurePrograms verbosity [ prog | (prog,_,_) <- Map.elems notYetConfigured ] conf where notYetConfigured = unconfiguredProgs conf `Map.difference` configuredProgs conf -- | reconfigure a bunch of programs given new user-specified args. It takes -- the same inputs as 'userSpecifyPath' and 'userSpecifyArgs' and for all progs -- with a new path it calls 'configureProgram'. -- reconfigurePrograms :: Verbosity -> [(String, FilePath)] -> [(String, [ProgArg])] -> ProgramDb -> IO ProgramDb reconfigurePrograms verbosity paths argss conf = do configurePrograms verbosity progs . userSpecifyPaths paths . userSpecifyArgss argss $ conf where progs = catMaybes [ lookupKnownProgram name conf | (name,_) <- paths ] -- | Check that a program is configured and available to be run. -- -- It raises an exception if the program could not be configured, otherwise -- it returns the configured program. -- requireProgram :: Verbosity -> Program -> ProgramDb -> IO (ConfiguredProgram, ProgramDb) requireProgram verbosity prog conf = do -- If it's not already been configured, try to configure it now conf' <- case lookupProgram prog conf of Nothing -> configureProgram verbosity prog conf Just _ -> return conf case lookupProgram prog conf' of Nothing -> die notFound Just configuredProg -> return (configuredProg, conf') where notFound = "The program '" ++ programName prog ++ "' is required but it could not be found." -- | Check that a program is configured and available to be run. -- -- Additionally check that the program version number is suitable and return -- it. For example you could require 'AnyVersion' or @'orLaterVersion' -- ('Version' [1,0] [])@ -- -- It returns the configured program, its version number and a possibly updated -- 'ProgramDb'. If the program could not be configured or the version is -- unsuitable, it returns an error value. -- lookupProgramVersion :: Verbosity -> Program -> VersionRange -> ProgramDb -> IO (Either String (ConfiguredProgram, Version, ProgramDb)) lookupProgramVersion verbosity prog range programDb = do -- If it's not already been configured, try to configure it now programDb' <- case lookupProgram prog programDb of Nothing -> configureProgram verbosity prog programDb Just _ -> return programDb case lookupProgram prog programDb' of Nothing -> return $! Left notFound Just configuredProg@ConfiguredProgram { programLocation = location } -> case programVersion configuredProg of Just version | withinRange version range -> return $! Right (configuredProg, version ,programDb') | otherwise -> return $! Left (badVersion version location) Nothing -> return $! Left (noVersion location) where notFound = "The program '" ++ programName prog ++ "'" ++ versionRequirement ++ " is required but it could not be found." badVersion v l = "The program '" ++ programName prog ++ "'" ++ versionRequirement ++ " is required but the version found at " ++ locationPath l ++ " is version " ++ display v noVersion l = "The program '" ++ programName prog ++ "'" ++ versionRequirement ++ " is required but the version of " ++ locationPath l ++ " could not be determined." versionRequirement | isAnyVersion range = "" | otherwise = " version " ++ display range -- | Like 'lookupProgramVersion', but raises an exception in case of error -- instead of returning 'Left errMsg'. -- requireProgramVersion :: Verbosity -> Program -> VersionRange -> ProgramDb -> IO (ConfiguredProgram, Version, ProgramDb) requireProgramVersion verbosity prog range programDb = join $ either die return `fmap` lookupProgramVersion verbosity prog range programDb
trskop/cabal
Cabal/Distribution/Simple/Program/Db.hs
bsd-3-clause
17,709
0
19
4,146
2,921
1,606
1,315
257
4
{-# LANGUAGE CPP, BangPatterns, MagicHash, UnboxedTuples #-} {-# OPTIONS_GHC -O #-} -- We always optimise this, otherwise performance of a non-optimised -- compiler is severely affected -- -- (c) The University of Glasgow 2002-2006 -- -- Unboxed mutable Ints module ETA.Utils.FastMutInt( FastMutInt, newFastMutInt, readFastMutInt, writeFastMutInt, FastMutPtr, newFastMutPtr, readFastMutPtr, writeFastMutPtr ) where #define SIZEOF_HSINT 4 #define SIZEOF_VOID_P 4 import GHC.Base import GHC.Ptr newFastMutInt :: IO FastMutInt readFastMutInt :: FastMutInt -> IO Int writeFastMutInt :: FastMutInt -> Int -> IO () newFastMutPtr :: IO FastMutPtr readFastMutPtr :: FastMutPtr -> IO (Ptr a) writeFastMutPtr :: FastMutPtr -> Ptr a -> IO () data FastMutInt = FastMutInt (MutableByteArray# RealWorld) newFastMutInt = IO $ \s -> case newByteArray# size s of { (# s', arr #) -> (# s', FastMutInt arr #) } where !(I# size) = SIZEOF_HSINT readFastMutInt (FastMutInt arr) = IO $ \s -> case readIntArray# arr 0# s of { (# s', i #) -> (# s', I# i #) } writeFastMutInt (FastMutInt arr) (I# i) = IO $ \s -> case writeIntArray# arr 0# i s of { s' -> (# s', () #) } data FastMutPtr = FastMutPtr (MutableByteArray# RealWorld) newFastMutPtr = IO $ \s -> case newByteArray# size s of { (# s', arr #) -> (# s', FastMutPtr arr #) } where !(I# size) = SIZEOF_VOID_P readFastMutPtr (FastMutPtr arr) = IO $ \s -> case readAddrArray# arr 0# s of { (# s', i #) -> (# s', Ptr i #) } writeFastMutPtr (FastMutPtr arr) (Ptr i) = IO $ \s -> case writeAddrArray# arr 0# i s of { s' -> (# s', () #) }
pparkkin/eta
compiler/ETA/Utils/FastMutInt.hs
bsd-3-clause
1,641
0
11
348
514
278
236
37
1
{-# LANGUAGE DataKinds,EmptyDataDecls #-} module HLearn.Metrics.Mahalanobis.Lego where import Control.DeepSeq import Data.List import Data.Proxy import qualified Data.Semigroup as SG import qualified Data.Foldable as F import qualified Data.Vector.Generic as VG import Foreign.Storable import Numeric.LinearAlgebra hiding ((<>)) import qualified Numeric.LinearAlgebra as LA import HLearn.Algebra import HLearn.Metrics.Mahalanobis import HLearn.Models.Distributions.Multivariate.MultiNormalFast ------------------------------------------------------------------------------- -- data types type instance Scalar (AddUnit1 (Lego' reg eta) dp) = Scalar (Lego' reg eta dp) instance Field (Scalar dp) => MahalanobisMetric (AddUnit1 (Lego' reg eta) dp) where getMatrix (UnitLift1 m) = inv $ covar $ multinorm m type Lego reg (eta::Frac) dp = AddUnit1 (Lego' reg eta) dp data Lego' reg (eta::Frac) dp = Lego' { b :: !(Matrix (Scalar dp)) , c :: !(Matrix (Scalar dp)) , x :: Matrix (Scalar dp) , multinorm :: MultiNormal dp } deriving instance (Element (Scalar dp), Show (Scalar dp)) => Show (Lego' reg eta dp) instance NFData dp => NFData (Lego' reg eta dp) where rnf lego = deepseq b $ deepseq c $ rnf x --------------------------------------- data RegMatrix_ = Identity_ | InvCovar_ class RegMatrix m where regmatrix :: m -> RegMatrix_ data Identity instance RegMatrix Identity where regmatrix _ = Identity_ data InvCovar instance RegMatrix InvCovar where regmatrix _ = InvCovar_ --------------------------------------- mkLego :: forall reg eta dp. ( KnownFrac eta , MatrixField dp , RegMatrix reg ) => Matrix (Scalar dp) -> Matrix (Scalar dp) -> MultiNormal dp -> Lego' reg eta dp mkLego b c multinorm = Lego' { b = b , c = c , multinorm = multinorm , x = inv $ completeTheSquare (scale (-1) b') (scale (-eta) c) } where m = case (regmatrix (undefined::reg)) of Identity_ -> ident (rows b) InvCovar_ -> inv $ covar multinorm b' = scale (1/2) (m `add` scale eta b) eta = fromRational $ fracVal (Proxy :: Proxy eta) -- | given an equation Y^2 + BY + YB + C, solve for Y completeTheSquare :: ( Storable r , Element r , Container Vector r , LA.Product r , Field r , r ~ Double ) => Matrix r -> Matrix r -> Matrix r -- completeTheSquare b c = (sqrtm' ((b LA.<> b) `sub` c)) `sub` b completeTheSquare b c = (sqrtm' ((scale (1/4) $ b LA.<> b) `sub` c)) `sub` b where sqrtm' m = cmap realPart $ matFunc sqrt $ cmap (:+0) m ------------------------------------------------------------------------------- -- algebra instance (KnownFrac eta, RegMatrix reg, MatrixField dp) => SG.Semigroup (Lego' reg eta dp) where lego1 <> lego2 = mkLego b' c' mn' where b' = b lego1 `add` b lego2 c' = c lego1 `add` c lego2 mn' = multinorm lego1 <> multinorm lego2 type instance Scalar (Lego' reg eta dp) = Scalar dp type instance Scalar (Vector r) = r ------------------------------------------------------------------------------- -- training instance ( KnownFrac eta , RegMatrix reg , MatrixField (Vector r) , r ~ Scalar (dp r) , VG.Vector dp r ) => HomTrainer (Lego reg eta (dp r)) where type Datapoint (Lego reg eta (dp r)) = (r,dp r) train1dp (y,dp) = UnitLift1 $ mkLego (scale y zzT) (zzT LA.<> zzT) (train1dp dp) where zzT = asColumn dp' LA.<> asRow dp' dp' = fromList $ VG.toList dp ------------------------------------------------------------------------------- -- metric instance ( VG.Vector dp r , Scalar (dp r) ~ r , RegMatrix reg , LA.Product r ) => MkMahalanobis (Lego reg eta (dp r)) where type MetricDatapoint (Lego reg eta (dp r)) = dp r mkMahalanobis (UnitLift1 lego) dp = Mahalanobis { rawdp = dp , moddp = VG.fromList $ toList $ flatten $ (x lego) LA.<> asColumn v } where v = fromList $ VG.toList dp ------------------------------------------------------------------------------- -- test xs = [ [1,2] , [2,3] , [3,4] ] :: [[Double]] mb = (2><2)[-6.5,-10,-10,-14] :: Matrix Double mc = (2><2)[282,388,388,537] :: Matrix Double
iamkingmaker/HLearn
src/HLearn/Metrics/Mahalanobis/Lego.hs
bsd-3-clause
4,383
0
15
1,086
1,509
814
695
-1
-1
{-# LANGUAGE DeriveDataTypeable, DisambiguateRecordFields, TemplateHaskell #-} module Unify.Config where import Unify.Instance import Prolog.Data import Autolib.ToDoc import Autolib.Reader import Autolib.FiniteMap import Autolib.Set import qualified Autolib.TES.Binu as B import Data.Typeable -- | maps Identifier to its arity type Signature = FiniteMap Identifier Int data Config = Config { signature :: Signature , variables :: Set Identifier , term_size :: Int , wildcard :: Identifier , num_wildcards :: Int , num_candidates :: Int -- ^ will use best instance of these } deriving ( Typeable, Eq ) $(derives [makeReader, makeToDoc] [''Config]) example :: Config example = Config { signature = listToFM $ read "[ (f,2),(a,0) ]" , variables = mkSet $ read "[X,Y,Z]" , wildcard = read "undefined" , term_size = 5 , num_wildcards = 3 , num_candidates = 3000 }
Erdwolf/autotool-bonn
src/Unify/Config.hs
gpl-2.0
967
0
9
236
211
127
84
29
1
infixr 9 . infixr 5 ++ infixl 4 <$ infix 2 `foo` infixl 1 >>, >>= infixr 1 =<< infixr 0 $, $! infixl 4 <*>, <*, *>, <**>
itchyny/vim-haskell-indent
test/infix/infix.out.hs
mit
132
0
4
40
58
36
22
8
0
{-# LANGUAGE OverloadedStrings #-} module Stack.Options.LogLevelParser where import Control.Monad.Logger (LogLevel (..)) import Data.Monoid.Extra import qualified Data.Text as T import Options.Applicative import Stack.Options.Utils -- | Parser for a logging level. logLevelOptsParser :: Bool -> Maybe LogLevel -> Parser (Maybe LogLevel) logLevelOptsParser hide defLogLevel = fmap (Just . parse) (strOption (long "verbosity" <> metavar "VERBOSITY" <> help "Verbosity: silent, error, warn, info, debug" <> hideMods hide)) <|> flag' (Just verboseLevel) (short 'v' <> long "verbose" <> help ("Enable verbose mode: verbosity level \"" <> showLevel verboseLevel <> "\"") <> hideMods hide) <|> flag' (Just silentLevel) (long "silent" <> help ("Enable silent mode: verbosity level \"" <> showLevel silentLevel <> "\"") <> hideMods hide) <|> pure defLogLevel where verboseLevel = LevelDebug silentLevel = LevelOther "silent" showLevel l = case l of LevelDebug -> "debug" LevelInfo -> "info" LevelWarn -> "warn" LevelError -> "error" LevelOther x -> T.unpack x parse s = case s of "debug" -> LevelDebug "info" -> LevelInfo "warn" -> LevelWarn "error" -> LevelError _ -> LevelOther (T.pack s)
AndreasPK/stack
src/Stack/Options/LogLevelParser.hs
bsd-3-clause
1,546
0
16
532
359
182
177
39
9
yes = not (a == b)
bitemyapp/apply-refact
tests/examples/Default9.hs
bsd-3-clause
18
0
7
5
16
8
8
1
1
{-# LANGUAGE CPP, ScopedTypeVariables, BangPatterns #-} -- -- Must have rules off, otherwise the fusion rules will replace the rhs -- with the lhs, and we only end up testing lhs == lhs -- -- -- -fhpc interferes with rewrite rules firing. -- import Foreign.Storable import Foreign.ForeignPtr import Foreign.Marshal.Alloc import Foreign.Marshal.Array import GHC.Ptr import Test.QuickCheck import Control.Monad import Control.Concurrent import Control.Exception import System.Directory import Data.List import Data.Char import Data.Word import Data.Maybe import Data.Int (Int64) import Data.Monoid import Text.Printf import Data.String import System.Environment import System.IO import System.IO.Unsafe import Data.ByteString.Lazy (ByteString(..), pack , unpack) import qualified Data.ByteString.Lazy as L import Data.ByteString.Lazy.Internal (ByteString(..)) import qualified Data.ByteString as P import qualified Data.ByteString.Internal as P import qualified Data.ByteString.Unsafe as P import qualified Data.ByteString.Char8 as C import qualified Data.ByteString.Short as Short import qualified Data.ByteString.Lazy.Char8 as LC import qualified Data.ByteString.Lazy.Char8 as D import qualified Data.ByteString.Lazy.Internal as L import Prelude hiding (abs) import Rules import QuickCheckUtils #if defined(HAVE_TEST_FRAMEWORK) import Test.Framework import Test.Framework.Providers.QuickCheck2 #else import TestFramework #endif toInt64 :: Int -> Int64 toInt64 = fromIntegral -- -- ByteString.Lazy.Char8 <=> ByteString.Char8 -- prop_concatCC = D.concat `eq1` C.concat prop_nullCC = D.null `eq1` C.null prop_reverseCC = D.reverse `eq1` C.reverse prop_transposeCC = D.transpose `eq1` C.transpose prop_groupCC = D.group `eq1` C.group prop_groupByCC = D.groupBy `eq2` C.groupBy prop_initsCC = D.inits `eq1` C.inits prop_tailsCC = D.tails `eq1` C.tails prop_allCC = D.all `eq2` C.all prop_anyCC = D.any `eq2` C.any prop_appendCC = D.append `eq2` C.append prop_breakCC = D.break `eq2` C.break prop_concatMapCC = adjustSize (min 50) $ D.concatMap `eq2` C.concatMap prop_consCC = D.cons `eq2` C.cons prop_consCC' = D.cons' `eq2` C.cons prop_unconsCC = D.uncons `eq1` C.uncons prop_unsnocCC = D.unsnoc `eq1` C.unsnoc prop_countCC = D.count `eq2` ((toInt64 .) . C.count) prop_dropCC = (D.drop . toInt64) `eq2` C.drop prop_dropWhileCC = D.dropWhile `eq2` C.dropWhile prop_filterCC = D.filter `eq2` C.filter prop_findCC = D.find `eq2` C.find prop_findIndexCC = D.findIndex `eq2` ((fmap toInt64 .) . C.findIndex) prop_findIndicesCC = D.findIndices `eq2` ((fmap toInt64 .) . C.findIndices) prop_isPrefixOfCC = D.isPrefixOf `eq2` C.isPrefixOf prop_mapCC = D.map `eq2` C.map prop_replicateCC = forAll arbitrarySizedIntegral $ (D.replicate . toInt64) `eq2` C.replicate prop_snocCC = D.snoc `eq2` C.snoc prop_spanCC = D.span `eq2` C.span prop_splitCC = D.split `eq2` C.split prop_splitAtCC = (D.splitAt . toInt64) `eq2` C.splitAt prop_takeCC = (D.take . toInt64) `eq2` C.take prop_takeWhileCC = D.takeWhile `eq2` C.takeWhile prop_elemCC = D.elem `eq2` C.elem prop_notElemCC = D.notElem `eq2` C.notElem prop_elemIndexCC = D.elemIndex `eq2` ((fmap toInt64 .) . C.elemIndex) prop_elemIndicesCC = D.elemIndices `eq2` ((fmap toInt64 .) . C.elemIndices) prop_lengthCC = D.length `eq1` (toInt64 . C.length) prop_headCC = D.head `eqnotnull1` C.head prop_initCC = D.init `eqnotnull1` C.init prop_lastCC = D.last `eqnotnull1` C.last prop_maximumCC = D.maximum `eqnotnull1` C.maximum prop_minimumCC = D.minimum `eqnotnull1` C.minimum prop_tailCC = D.tail `eqnotnull1` C.tail prop_foldl1CC = D.foldl1 `eqnotnull2` C.foldl1 prop_foldl1CC' = D.foldl1' `eqnotnull2` C.foldl1' prop_foldr1CC = D.foldr1 `eqnotnull2` C.foldr1 prop_foldr1CC' = D.foldr1 `eqnotnull2` C.foldr1' prop_scanlCC = D.scanl `eqnotnull3` C.scanl prop_intersperseCC = D.intersperse `eq2` C.intersperse prop_foldlCC = eq3 (D.foldl :: (X -> Char -> X) -> X -> B -> X) (C.foldl :: (X -> Char -> X) -> X -> P -> X) prop_foldlCC' = eq3 (D.foldl' :: (X -> Char -> X) -> X -> B -> X) (C.foldl' :: (X -> Char -> X) -> X -> P -> X) prop_foldrCC = eq3 (D.foldr :: (Char -> X -> X) -> X -> B -> X) (C.foldr :: (Char -> X -> X) -> X -> P -> X) prop_foldrCC' = eq3 (D.foldr :: (Char -> X -> X) -> X -> B -> X) (C.foldr' :: (Char -> X -> X) -> X -> P -> X) prop_mapAccumLCC = eq3 (D.mapAccumL :: (X -> Char -> (X,Char)) -> X -> B -> (X, B)) (C.mapAccumL :: (X -> Char -> (X,Char)) -> X -> P -> (X, P)) --prop_mapIndexedCC = D.mapIndexed `eq2` C.mapIndexed --prop_mapIndexedPL = L.mapIndexed `eq2` P.mapIndexed --prop_mapAccumL_mapIndexedBP = -- P.mapIndexed `eq2` -- (\k p -> snd $ P.mapAccumL (\i w -> (i+1, k i w)) (0::Int) p) -- -- ByteString.Lazy <=> ByteString -- prop_concatBP = adjustSize (`div` 2) $ L.concat `eq1` P.concat prop_nullBP = L.null `eq1` P.null prop_reverseBP = L.reverse `eq1` P.reverse prop_transposeBP = L.transpose `eq1` P.transpose prop_groupBP = L.group `eq1` P.group prop_groupByBP = L.groupBy `eq2` P.groupBy prop_initsBP = L.inits `eq1` P.inits prop_tailsBP = L.tails `eq1` P.tails prop_allBP = L.all `eq2` P.all prop_anyBP = L.any `eq2` P.any prop_appendBP = L.append `eq2` P.append prop_breakBP = L.break `eq2` P.break prop_concatMapBP = adjustSize (`div` 4) $ L.concatMap `eq2` P.concatMap prop_consBP = L.cons `eq2` P.cons prop_consBP' = L.cons' `eq2` P.cons prop_unconsBP = L.uncons `eq1` P.uncons prop_unsnocBP = L.unsnoc `eq1` P.unsnoc prop_countBP = L.count `eq2` ((toInt64 .) . P.count) prop_dropBP = (L.drop. toInt64) `eq2` P.drop prop_dropWhileBP = L.dropWhile `eq2` P.dropWhile prop_filterBP = L.filter `eq2` P.filter prop_findBP = L.find `eq2` P.find prop_findIndexBP = L.findIndex `eq2` ((fmap toInt64 .) . P.findIndex) prop_findIndicesBP = L.findIndices `eq2` ((fmap toInt64 .) . P.findIndices) prop_isPrefixOfBP = L.isPrefixOf `eq2` P.isPrefixOf prop_mapBP = L.map `eq2` P.map prop_replicateBP = forAll arbitrarySizedIntegral $ (L.replicate. toInt64) `eq2` P.replicate prop_snocBP = L.snoc `eq2` P.snoc prop_spanBP = L.span `eq2` P.span prop_splitBP = L.split `eq2` P.split prop_splitAtBP = (L.splitAt. toInt64) `eq2` P.splitAt prop_takeBP = (L.take . toInt64) `eq2` P.take prop_takeWhileBP = L.takeWhile `eq2` P.takeWhile prop_elemBP = L.elem `eq2` P.elem prop_notElemBP = L.notElem `eq2` P.notElem prop_elemIndexBP = L.elemIndex `eq2` ((fmap toInt64 .) . P.elemIndex) prop_elemIndicesBP = L.elemIndices `eq2` ((fmap toInt64 .) . P.elemIndices) prop_intersperseBP = L.intersperse `eq2` P.intersperse prop_lengthBP = L.length `eq1` (toInt64 . P.length) prop_readIntBP = D.readInt `eq1` C.readInt prop_linesBP = D.lines `eq1` C.lines -- double check: -- Currently there's a bug in the lazy bytestring version of lines, this -- catches it: prop_linesNLBP = eq1 D.lines C.lines x where x = D.pack "one\ntwo\n\n\nfive\n\nseven\n" prop_headBP = L.head `eqnotnull1` P.head prop_initBP = L.init `eqnotnull1` P.init prop_lastBP = L.last `eqnotnull1` P.last prop_maximumBP = L.maximum `eqnotnull1` P.maximum prop_minimumBP = L.minimum `eqnotnull1` P.minimum prop_tailBP = L.tail `eqnotnull1` P.tail prop_foldl1BP = L.foldl1 `eqnotnull2` P.foldl1 prop_foldl1BP' = L.foldl1' `eqnotnull2` P.foldl1' prop_foldr1BP = L.foldr1 `eqnotnull2` P.foldr1 prop_foldr1BP' = L.foldr1 `eqnotnull2` P.foldr1' prop_scanlBP = L.scanl `eqnotnull3` P.scanl prop_eqBP = eq2 ((==) :: B -> B -> Bool) ((==) :: P -> P -> Bool) prop_compareBP = eq2 ((compare) :: B -> B -> Ordering) ((compare) :: P -> P -> Ordering) prop_foldlBP = eq3 (L.foldl :: (X -> W -> X) -> X -> B -> X) (P.foldl :: (X -> W -> X) -> X -> P -> X) prop_foldlBP' = eq3 (L.foldl' :: (X -> W -> X) -> X -> B -> X) (P.foldl' :: (X -> W -> X) -> X -> P -> X) prop_foldrBP = eq3 (L.foldr :: (W -> X -> X) -> X -> B -> X) (P.foldr :: (W -> X -> X) -> X -> P -> X) prop_foldrBP' = eq3 (L.foldr :: (W -> X -> X) -> X -> B -> X) (P.foldr' :: (W -> X -> X) -> X -> P -> X) prop_mapAccumLBP = eq3 (L.mapAccumL :: (X -> W -> (X,W)) -> X -> B -> (X, B)) (P.mapAccumL :: (X -> W -> (X,W)) -> X -> P -> (X, P)) prop_unfoldrBP = forAll arbitrarySizedIntegral $ eq3 ((\n f a -> L.take (fromIntegral n) $ L.unfoldr f a) :: Int -> (X -> Maybe (W,X)) -> X -> B) ((\n f a -> fst $ P.unfoldrN n f a) :: Int -> (X -> Maybe (W,X)) -> X -> P) prop_unfoldr2BP = forAll arbitrarySizedIntegral $ \n -> forAll arbitrarySizedIntegral $ \a -> eq2 ((\n a -> P.take (n*100) $ P.unfoldr (\x -> if x <= (n*100) then Just (fromIntegral x, x + 1) else Nothing) a) :: Int -> Int -> P) ((\n a -> fst $ P.unfoldrN (n*100) (\x -> if x <= (n*100) then Just (fromIntegral x, x + 1) else Nothing) a) :: Int -> Int -> P) n a prop_unfoldr2CP = forAll arbitrarySizedIntegral $ \n -> forAll arbitrarySizedIntegral $ \a -> eq2 ((\n a -> C.take (n*100) $ C.unfoldr (\x -> if x <= (n*100) then Just (chr (x `mod` 256), x + 1) else Nothing) a) :: Int -> Int -> P) ((\n a -> fst $ C.unfoldrN (n*100) (\x -> if x <= (n*100) then Just (chr (x `mod` 256), x + 1) else Nothing) a) :: Int -> Int -> P) n a prop_unfoldrLC = forAll arbitrarySizedIntegral $ eq3 ((\n f a -> LC.take (fromIntegral n) $ LC.unfoldr f a) :: Int -> (X -> Maybe (Char,X)) -> X -> B) ((\n f a -> fst $ C.unfoldrN n f a) :: Int -> (X -> Maybe (Char,X)) -> X -> P) prop_cycleLC a = not (LC.null a) ==> forAll arbitrarySizedIntegral $ eq1 ((\n -> LC.take (fromIntegral n) $ LC.cycle a ) :: Int -> B) ((\n -> LC.take (fromIntegral (n::Int)) . LC.concat $ unfoldr (\x -> Just (x,x) ) a ) :: Int -> B) prop_iterateLC = forAll arbitrarySizedIntegral $ eq3 ((\n f a -> LC.take (fromIntegral n) $ LC.iterate f a) :: Int -> (Char -> Char) -> Char -> B) ((\n f a -> fst $ C.unfoldrN n (\a -> Just (f a, f a)) a) :: Int -> (Char -> Char) -> Char -> P) prop_iterateLC_2 = forAll arbitrarySizedIntegral $ eq3 ((\n f a -> LC.take (fromIntegral n) $ LC.iterate f a) :: Int -> (Char -> Char) -> Char -> B) ((\n f a -> LC.take (fromIntegral n) $ LC.unfoldr (\a -> Just (f a, f a)) a) :: Int -> (Char -> Char) -> Char -> B) prop_iterateL = forAll arbitrarySizedIntegral $ eq3 ((\n f a -> L.take (fromIntegral n) $ L.iterate f a) :: Int -> (W -> W) -> W -> B) ((\n f a -> fst $ P.unfoldrN n (\a -> Just (f a, f a)) a) :: Int -> (W -> W) -> W -> P) prop_repeatLC = forAll arbitrarySizedIntegral $ eq2 ((\n a -> LC.take (fromIntegral n) $ LC.repeat a) :: Int -> Char -> B) ((\n a -> fst $ C.unfoldrN n (\a -> Just (a, a)) a) :: Int -> Char -> P) prop_repeatL = forAll arbitrarySizedIntegral $ eq2 ((\n a -> L.take (fromIntegral n) $ L.repeat a) :: Int -> W -> B) ((\n a -> fst $ P.unfoldrN n (\a -> Just (a, a)) a) :: Int -> W -> P) -- -- properties comparing ByteString.Lazy `eq1` List -- prop_concatBL = adjustSize (`div` 2) $ L.concat `eq1` (concat :: [[W]] -> [W]) prop_lengthBL = L.length `eq1` (toInt64 . length :: [W] -> Int64) prop_nullBL = L.null `eq1` (null :: [W] -> Bool) prop_reverseBL = L.reverse `eq1` (reverse :: [W] -> [W]) prop_transposeBL = L.transpose `eq1` (transpose :: [[W]] -> [[W]]) prop_groupBL = L.group `eq1` (group :: [W] -> [[W]]) prop_groupByBL = L.groupBy `eq2` (groupBy :: (W -> W -> Bool) -> [W] -> [[W]]) prop_initsBL = L.inits `eq1` (inits :: [W] -> [[W]]) prop_tailsBL = L.tails `eq1` (tails :: [W] -> [[W]]) prop_allBL = L.all `eq2` (all :: (W -> Bool) -> [W] -> Bool) prop_anyBL = L.any `eq2` (any :: (W -> Bool) -> [W] -> Bool) prop_appendBL = L.append `eq2` ((++) :: [W] -> [W] -> [W]) prop_breakBL = L.break `eq2` (break :: (W -> Bool) -> [W] -> ([W],[W])) prop_concatMapBL = adjustSize (`div` 2) $ L.concatMap `eq2` (concatMap :: (W -> [W]) -> [W] -> [W]) prop_consBL = L.cons `eq2` ((:) :: W -> [W] -> [W]) prop_dropBL = (L.drop . toInt64) `eq2` (drop :: Int -> [W] -> [W]) prop_dropWhileBL = L.dropWhile `eq2` (dropWhile :: (W -> Bool) -> [W] -> [W]) prop_filterBL = L.filter `eq2` (filter :: (W -> Bool ) -> [W] -> [W]) prop_findBL = L.find `eq2` (find :: (W -> Bool) -> [W] -> Maybe W) prop_findIndicesBL = L.findIndices `eq2` ((fmap toInt64 .) . findIndices:: (W -> Bool) -> [W] -> [Int64]) prop_findIndexBL = L.findIndex `eq2` ((fmap toInt64 .) . findIndex :: (W -> Bool) -> [W] -> Maybe Int64) prop_isPrefixOfBL = L.isPrefixOf `eq2` (isPrefixOf:: [W] -> [W] -> Bool) prop_mapBL = L.map `eq2` (map :: (W -> W) -> [W] -> [W]) prop_replicateBL = forAll arbitrarySizedIntegral $ (L.replicate . toInt64) `eq2` (replicate :: Int -> W -> [W]) prop_snocBL = L.snoc `eq2` ((\xs x -> xs ++ [x]) :: [W] -> W -> [W]) prop_spanBL = L.span `eq2` (span :: (W -> Bool) -> [W] -> ([W],[W])) prop_splitAtBL = (L.splitAt . toInt64) `eq2` (splitAt :: Int -> [W] -> ([W],[W])) prop_takeBL = (L.take . toInt64) `eq2` (take :: Int -> [W] -> [W]) prop_takeWhileBL = L.takeWhile `eq2` (takeWhile :: (W -> Bool) -> [W] -> [W]) prop_elemBL = L.elem `eq2` (elem :: W -> [W] -> Bool) prop_notElemBL = L.notElem `eq2` (notElem :: W -> [W] -> Bool) prop_elemIndexBL = L.elemIndex `eq2` ((fmap toInt64 .) . elemIndex :: W -> [W] -> Maybe Int64) prop_elemIndicesBL = L.elemIndices `eq2` ((fmap toInt64 .) . elemIndices :: W -> [W] -> [Int64]) prop_linesBL = D.lines `eq1` (lines :: String -> [String]) prop_foldl1BL = L.foldl1 `eqnotnull2` (foldl1 :: (W -> W -> W) -> [W] -> W) prop_foldl1BL' = L.foldl1' `eqnotnull2` (foldl1' :: (W -> W -> W) -> [W] -> W) prop_foldr1BL = L.foldr1 `eqnotnull2` (foldr1 :: (W -> W -> W) -> [W] -> W) prop_headBL = L.head `eqnotnull1` (head :: [W] -> W) prop_initBL = L.init `eqnotnull1` (init :: [W] -> [W]) prop_lastBL = L.last `eqnotnull1` (last :: [W] -> W) prop_maximumBL = L.maximum `eqnotnull1` (maximum :: [W] -> W) prop_minimumBL = L.minimum `eqnotnull1` (minimum :: [W] -> W) prop_tailBL = L.tail `eqnotnull1` (tail :: [W] -> [W]) prop_eqBL = eq2 ((==) :: B -> B -> Bool) ((==) :: [W] -> [W] -> Bool) prop_compareBL = eq2 ((compare) :: B -> B -> Ordering) ((compare) :: [W] -> [W] -> Ordering) prop_foldlBL = eq3 (L.foldl :: (X -> W -> X) -> X -> B -> X) ( foldl :: (X -> W -> X) -> X -> [W] -> X) prop_foldlBL' = eq3 (L.foldl' :: (X -> W -> X) -> X -> B -> X) ( foldl' :: (X -> W -> X) -> X -> [W] -> X) prop_foldrBL = eq3 (L.foldr :: (W -> X -> X) -> X -> B -> X) ( foldr :: (W -> X -> X) -> X -> [W] -> X) prop_mapAccumLBL = eq3 (L.mapAccumL :: (X -> W -> (X,W)) -> X -> B -> (X, B)) ( mapAccumL :: (X -> W -> (X,W)) -> X -> [W] -> (X, [W])) prop_mapAccumRBL = eq3 (L.mapAccumR :: (X -> W -> (X,W)) -> X -> B -> (X, B)) ( mapAccumR :: (X -> W -> (X,W)) -> X -> [W] -> (X, [W])) prop_mapAccumRDL = eq3 (D.mapAccumR :: (X -> Char -> (X,Char)) -> X -> B -> (X, B)) ( mapAccumR :: (X -> Char -> (X,Char)) -> X -> [Char] -> (X, [Char])) prop_mapAccumRCC = eq3 (C.mapAccumR :: (X -> Char -> (X,Char)) -> X -> P -> (X, P)) ( mapAccumR :: (X -> Char -> (X,Char)) -> X -> [Char] -> (X, [Char])) prop_unfoldrBL = forAll arbitrarySizedIntegral $ eq3 ((\n f a -> L.take (fromIntegral n) $ L.unfoldr f a) :: Int -> (X -> Maybe (W,X)) -> X -> B) ((\n f a -> take n $ unfoldr f a) :: Int -> (X -> Maybe (W,X)) -> X -> [W]) -- -- And finally, check correspondance between Data.ByteString and List -- prop_lengthPL = (fromIntegral.P.length :: P -> Int) `eq1` (length :: [W] -> Int) prop_nullPL = P.null `eq1` (null :: [W] -> Bool) prop_reversePL = P.reverse `eq1` (reverse :: [W] -> [W]) prop_transposePL = P.transpose `eq1` (transpose :: [[W]] -> [[W]]) prop_groupPL = P.group `eq1` (group :: [W] -> [[W]]) prop_groupByPL = P.groupBy `eq2` (groupBy :: (W -> W -> Bool) -> [W] -> [[W]]) prop_initsPL = P.inits `eq1` (inits :: [W] -> [[W]]) prop_tailsPL = P.tails `eq1` (tails :: [W] -> [[W]]) prop_concatPL = adjustSize (`div` 2) $ P.concat `eq1` (concat :: [[W]] -> [W]) prop_allPL = P.all `eq2` (all :: (W -> Bool) -> [W] -> Bool) prop_anyPL = P.any `eq2` (any :: (W -> Bool) -> [W] -> Bool) prop_appendPL = P.append `eq2` ((++) :: [W] -> [W] -> [W]) prop_breakPL = P.break `eq2` (break :: (W -> Bool) -> [W] -> ([W],[W])) prop_concatMapPL = adjustSize (`div` 2) $ P.concatMap `eq2` (concatMap :: (W -> [W]) -> [W] -> [W]) prop_consPL = P.cons `eq2` ((:) :: W -> [W] -> [W]) prop_dropPL = P.drop `eq2` (drop :: Int -> [W] -> [W]) prop_dropWhilePL = P.dropWhile `eq2` (dropWhile :: (W -> Bool) -> [W] -> [W]) prop_filterPL = P.filter `eq2` (filter :: (W -> Bool ) -> [W] -> [W]) prop_filterPL_rule= (\x -> P.filter ((==) x)) `eq2` -- test rules ((\x -> filter ((==) x)) :: W -> [W] -> [W]) -- under lambda doesn't fire? prop_filterLC_rule= (f) `eq2` -- test rules ((\x -> filter ((==) x)) :: Char -> [Char] -> [Char]) where f x s = LC.filter ((==) x) s prop_partitionPL = P.partition `eq2` (partition :: (W -> Bool ) -> [W] -> ([W],[W])) prop_partitionLL = L.partition `eq2` (partition :: (W -> Bool ) -> [W] -> ([W],[W])) prop_findPL = P.find `eq2` (find :: (W -> Bool) -> [W] -> Maybe W) prop_findIndexPL = P.findIndex `eq2` (findIndex :: (W -> Bool) -> [W] -> Maybe Int) prop_isPrefixOfPL = P.isPrefixOf`eq2` (isPrefixOf:: [W] -> [W] -> Bool) prop_isInfixOfPL = P.isInfixOf `eq2` (isInfixOf:: [W] -> [W] -> Bool) prop_mapPL = P.map `eq2` (map :: (W -> W) -> [W] -> [W]) prop_replicatePL = forAll arbitrarySizedIntegral $ P.replicate `eq2` (replicate :: Int -> W -> [W]) prop_snocPL = P.snoc `eq2` ((\xs x -> xs ++ [x]) :: [W] -> W -> [W]) prop_spanPL = P.span `eq2` (span :: (W -> Bool) -> [W] -> ([W],[W])) prop_splitAtPL = P.splitAt `eq2` (splitAt :: Int -> [W] -> ([W],[W])) prop_takePL = P.take `eq2` (take :: Int -> [W] -> [W]) prop_takeWhilePL = P.takeWhile `eq2` (takeWhile :: (W -> Bool) -> [W] -> [W]) prop_elemPL = P.elem `eq2` (elem :: W -> [W] -> Bool) prop_notElemPL = P.notElem `eq2` (notElem :: W -> [W] -> Bool) prop_elemIndexPL = P.elemIndex `eq2` (elemIndex :: W -> [W] -> Maybe Int) prop_linesPL = C.lines `eq1` (lines :: String -> [String]) prop_findIndicesPL= P.findIndices`eq2` (findIndices:: (W -> Bool) -> [W] -> [Int]) prop_elemIndicesPL= P.elemIndices`eq2` (elemIndices:: W -> [W] -> [Int]) prop_zipPL = P.zip `eq2` (zip :: [W] -> [W] -> [(W,W)]) prop_zipCL = C.zip `eq2` (zip :: [Char] -> [Char] -> [(Char,Char)]) prop_zipLL = L.zip `eq2` (zip :: [W] -> [W] -> [(W,W)]) prop_unzipPL = P.unzip `eq1` (unzip :: [(W,W)] -> ([W],[W])) prop_unzipLL = L.unzip `eq1` (unzip :: [(W,W)] -> ([W],[W])) prop_unzipCL = C.unzip `eq1` (unzip :: [(Char,Char)] -> ([Char],[Char])) prop_foldl1PL = P.foldl1 `eqnotnull2` (foldl1 :: (W -> W -> W) -> [W] -> W) prop_foldl1PL' = P.foldl1' `eqnotnull2` (foldl1' :: (W -> W -> W) -> [W] -> W) prop_foldr1PL = P.foldr1 `eqnotnull2` (foldr1 :: (W -> W -> W) -> [W] -> W) prop_scanlPL = P.scanl `eqnotnull3` (scanl :: (W -> W -> W) -> W -> [W] -> [W]) prop_scanl1PL = P.scanl1 `eqnotnull2` (scanl1 :: (W -> W -> W) -> [W] -> [W]) prop_scanrPL = P.scanr `eqnotnull3` (scanr :: (W -> W -> W) -> W -> [W] -> [W]) prop_scanr1PL = P.scanr1 `eqnotnull2` (scanr1 :: (W -> W -> W) -> [W] -> [W]) prop_headPL = P.head `eqnotnull1` (head :: [W] -> W) prop_initPL = P.init `eqnotnull1` (init :: [W] -> [W]) prop_lastPL = P.last `eqnotnull1` (last :: [W] -> W) prop_maximumPL = P.maximum `eqnotnull1` (maximum :: [W] -> W) prop_minimumPL = P.minimum `eqnotnull1` (minimum :: [W] -> W) prop_tailPL = P.tail `eqnotnull1` (tail :: [W] -> [W]) prop_scanl1CL = C.scanl1 `eqnotnull2` (scanl1 :: (Char -> Char -> Char) -> [Char] -> [Char]) prop_scanrCL = C.scanr `eqnotnull3` (scanr :: (Char -> Char -> Char) -> Char -> [Char] -> [Char]) prop_scanr1CL = C.scanr1 `eqnotnull2` (scanr1 :: (Char -> Char -> Char) -> [Char] -> [Char]) -- prop_zipWithPL' = P.zipWith' `eq3` (zipWith :: (W -> W -> W) -> [W] -> [W] -> [W]) prop_zipWithPL = (P.zipWith :: (W -> W -> X) -> P -> P -> [X]) `eq3` (zipWith :: (W -> W -> X) -> [W] -> [W] -> [X]) prop_zipWithPL_rules = (P.zipWith :: (W -> W -> W) -> P -> P -> [W]) `eq3` (zipWith :: (W -> W -> W) -> [W] -> [W] -> [W]) prop_eqPL = eq2 ((==) :: P -> P -> Bool) ((==) :: [W] -> [W] -> Bool) prop_comparePL = eq2 ((compare) :: P -> P -> Ordering) ((compare) :: [W] -> [W] -> Ordering) prop_foldlPL = eq3 (P.foldl :: (X -> W -> X) -> X -> P -> X) ( foldl :: (X -> W -> X) -> X -> [W] -> X) prop_foldlPL' = eq3 (P.foldl' :: (X -> W -> X) -> X -> P -> X) ( foldl' :: (X -> W -> X) -> X -> [W] -> X) prop_foldrPL = eq3 (P.foldr :: (W -> X -> X) -> X -> P -> X) ( foldr :: (W -> X -> X) -> X -> [W] -> X) prop_mapAccumLPL= eq3 (P.mapAccumL :: (X -> W -> (X,W)) -> X -> P -> (X, P)) ( mapAccumL :: (X -> W -> (X,W)) -> X -> [W] -> (X, [W])) prop_mapAccumRPL= eq3 (P.mapAccumR :: (X -> W -> (X,W)) -> X -> P -> (X, P)) ( mapAccumR :: (X -> W -> (X,W)) -> X -> [W] -> (X, [W])) prop_unfoldrPL = forAll arbitrarySizedIntegral $ eq3 ((\n f a -> fst $ P.unfoldrN n f a) :: Int -> (X -> Maybe (W,X)) -> X -> P) ((\n f a -> take n $ unfoldr f a) :: Int -> (X -> Maybe (W,X)) -> X -> [W]) ------------------------------------------------------------------------ -- -- These are miscellaneous tests left over. Or else they test some -- property internal to a type (i.e. head . sort == minimum), without -- reference to a model type. -- invariant :: L.ByteString -> Bool invariant Empty = True invariant (Chunk c cs) = not (P.null c) && invariant cs prop_invariant = invariant prop_eq_refl x = x == (x :: ByteString) prop_eq_symm x y = (x == y) == (y == (x :: ByteString)) prop_eq1 xs = xs == (unpack . pack $ xs) prop_eq2 xs = xs == (xs :: ByteString) prop_eq3 xs ys = (xs == ys) == (unpack xs == unpack ys) prop_compare1 xs = (pack xs `compare` pack xs) == EQ prop_compare2 xs c = (pack (xs++[c]) `compare` pack xs) == GT prop_compare3 xs c = (pack xs `compare` pack (xs++[c])) == LT prop_compare4 xs = (not (null xs)) ==> (pack xs `compare` L.empty) == GT prop_compare5 xs = (not (null xs)) ==> (L.empty `compare` pack xs) == LT prop_compare6 xs ys = (not (null ys)) ==> (pack (xs++ys) `compare` pack xs) == GT prop_compare7 x y = x `compare` y == (L.singleton x `compare` L.singleton y) prop_compare8 xs ys = xs `compare` ys == (L.pack xs `compare` L.pack ys) prop_compare7LL x y = x `compare` y == (LC.singleton x `compare` LC.singleton y) prop_empty1 = L.length L.empty == 0 prop_empty2 = L.unpack L.empty == [] prop_packunpack s = (L.unpack . L.pack) s == id s prop_unpackpack s = (L.pack . L.unpack) s == id s prop_null xs = null (L.unpack xs) == L.null xs prop_length1 xs = fromIntegral (length xs) == L.length (L.pack xs) prop_length2 xs = L.length xs == length1 xs where length1 ys | L.null ys = 0 | otherwise = 1 + length1 (L.tail ys) prop_cons1 c xs = unpack (L.cons c (pack xs)) == (c:xs) prop_cons2 c = L.singleton c == (c `L.cons` L.empty) prop_cons3 c = unpack (L.singleton c) == (c:[]) prop_cons4 c = (c `L.cons` L.empty) == pack (c:[]) prop_snoc1 xs c = xs ++ [c] == unpack ((pack xs) `L.snoc` c) prop_head xs = (not (null xs)) ==> head xs == (L.head . pack) xs prop_head1 xs = not (L.null xs) ==> L.head xs == head (L.unpack xs) prop_tail xs = not (L.null xs) ==> L.tail xs == pack (tail (unpack xs)) prop_tail1 xs = (not (null xs)) ==> tail xs == (unpack . L.tail . pack) xs prop_last xs = (not (null xs)) ==> last xs == (L.last . pack) xs prop_init xs = (not (null xs)) ==> init xs == (unpack . L.init . pack) xs prop_append1 xs = (xs ++ xs) == (unpack $ pack xs `L.append` pack xs) prop_append2 xs ys = (xs ++ ys) == (unpack $ pack xs `L.append` pack ys) prop_append3 xs ys = L.append xs ys == pack (unpack xs ++ unpack ys) prop_map1 f xs = L.map f (pack xs) == pack (map f xs) prop_map2 f g xs = L.map f (L.map g xs) == L.map (f . g) xs prop_map3 f xs = map f xs == (unpack . L.map f . pack) xs prop_filter1 c xs = (filter (/=c) xs) == (unpack $ L.filter (/=c) (pack xs)) prop_filter2 p xs = (filter p xs) == (unpack $ L.filter p (pack xs)) prop_reverse xs = reverse xs == (unpack . L.reverse . pack) xs prop_reverse1 xs = L.reverse (pack xs) == pack (reverse xs) prop_reverse2 xs = reverse (unpack xs) == (unpack . L.reverse) xs prop_transpose xs = (transpose xs) == ((map unpack) . L.transpose . (map pack)) xs prop_foldl f c xs = L.foldl f c (pack xs) == foldl f c xs where _ = c :: Char prop_foldr f c xs = L.foldl f c (pack xs) == foldl f c xs where _ = c :: Char prop_foldl_1 xs = L.foldl (\xs c -> c `L.cons` xs) L.empty xs == L.reverse xs prop_foldr_1 xs = L.foldr (\c xs -> c `L.cons` xs) L.empty xs == id xs prop_foldl1_1 xs = (not . L.null) xs ==> L.foldl1 (\x c -> if c > x then c else x) xs == L.foldl (\x c -> if c > x then c else x) 0 xs prop_foldl1_2 xs = (not . L.null) xs ==> L.foldl1 const xs == L.head xs prop_foldl1_3 xs = (not . L.null) xs ==> L.foldl1 (flip const) xs == L.last xs prop_foldr1_1 xs = (not . L.null) xs ==> L.foldr1 (\c x -> if c > x then c else x) xs == L.foldr (\c x -> if c > x then c else x) 0 xs prop_foldr1_2 xs = (not . L.null) xs ==> L.foldr1 (flip const) xs == L.last xs prop_foldr1_3 xs = (not . L.null) xs ==> L.foldr1 const xs == L.head xs prop_concat1 xs = (concat [xs,xs]) == (unpack $ L.concat [pack xs, pack xs]) prop_concat2 xs = (concat [xs,[]]) == (unpack $ L.concat [pack xs, pack []]) prop_concat3 xss = adjustSize (`div` 2) $ L.concat (map pack xss) == pack (concat xss) prop_concatMap xs = L.concatMap L.singleton xs == (pack . concatMap (:[]) . unpack) xs prop_any xs a = (any (== a) xs) == (L.any (== a) (pack xs)) prop_all xs a = (all (== a) xs) == (L.all (== a) (pack xs)) prop_maximum xs = (not (null xs)) ==> (maximum xs) == (L.maximum ( pack xs )) prop_minimum xs = (not (null xs)) ==> (minimum xs) == (L.minimum ( pack xs )) prop_replicate1 c = forAll arbitrarySizedIntegral $ \(Positive n) -> unpack (L.replicate (fromIntegral n) c) == replicate n c prop_replicate2 c = unpack (L.replicate 0 c) == replicate 0 c prop_take1 i xs = L.take (fromIntegral i) (pack xs) == pack (take i xs) prop_drop1 i xs = L.drop (fromIntegral i) (pack xs) == pack (drop i xs) prop_splitAt i xs = --collect (i >= 0 && i < length xs) $ L.splitAt (fromIntegral i) (pack xs) == let (a,b) = splitAt i xs in (pack a, pack b) prop_takeWhile f xs = L.takeWhile f (pack xs) == pack (takeWhile f xs) prop_dropWhile f xs = L.dropWhile f (pack xs) == pack (dropWhile f xs) prop_break f xs = L.break f (pack xs) == let (a,b) = break f xs in (pack a, pack b) prop_breakspan xs c = L.break (==c) xs == L.span (/=c) xs prop_span xs a = (span (/=a) xs) == (let (x,y) = L.span (/=a) (pack xs) in (unpack x, unpack y)) -- prop_breakByte xs c = L.break (== c) xs == L.breakByte c xs -- prop_spanByte c xs = (L.span (==c) xs) == L.spanByte c xs prop_split c xs = (map L.unpack . map checkInvariant . L.split c $ xs) == (map P.unpack . P.split c . P.pack . L.unpack $ xs) prop_splitWith f xs = (l1 == l2 || l1 == l2+1) && sum (map L.length splits) == L.length xs - l2 where splits = L.splitWith f xs l1 = fromIntegral (length splits) l2 = L.length (L.filter f xs) prop_splitWith_D f xs = (l1 == l2 || l1 == l2+1) && sum (map D.length splits) == D.length xs - l2 where splits = D.splitWith f xs l1 = fromIntegral (length splits) l2 = D.length (D.filter f xs) prop_splitWith_C f xs = (l1 == l2 || l1 == l2+1) && sum (map C.length splits) == C.length xs - l2 where splits = C.splitWith f xs l1 = fromIntegral (length splits) l2 = C.length (C.filter f xs) prop_joinsplit c xs = L.intercalate (pack [c]) (L.split c xs) == id xs prop_group xs = group xs == (map unpack . L.group . pack) xs prop_groupBy f xs = groupBy f xs == (map unpack . L.groupBy f . pack) xs prop_groupBy_LC f xs = groupBy f xs == (map LC.unpack . LC.groupBy f . LC.pack) xs -- prop_joinjoinByte xs ys c = L.joinWithByte c xs ys == L.join (L.singleton c) [xs,ys] prop_index xs = not (null xs) ==> forAll indices $ \i -> (xs !! i) == L.pack xs `L.index` (fromIntegral i) where indices = choose (0, length xs -1) prop_index_D xs = not (null xs) ==> forAll indices $ \i -> (xs !! i) == D.pack xs `D.index` (fromIntegral i) where indices = choose (0, length xs -1) prop_index_C xs = not (null xs) ==> forAll indices $ \i -> (xs !! i) == C.pack xs `C.index` (fromIntegral i) where indices = choose (0, length xs -1) prop_elemIndex xs c = (elemIndex c xs) == fmap fromIntegral (L.elemIndex c (pack xs)) prop_elemIndexCL xs c = (elemIndex c xs) == (C.elemIndex c (C.pack xs)) prop_elemIndices xs c = elemIndices c xs == map fromIntegral (L.elemIndices c (pack xs)) prop_count c xs = length (L.elemIndices c xs) == fromIntegral (L.count c xs) prop_findIndex xs f = (findIndex f xs) == fmap fromIntegral (L.findIndex f (pack xs)) prop_findIndicies xs f = (findIndices f xs) == map fromIntegral (L.findIndices f (pack xs)) prop_elem xs c = (c `elem` xs) == (c `L.elem` (pack xs)) prop_notElem xs c = (c `notElem` xs) == (L.notElem c (pack xs)) prop_elem_notelem xs c = c `L.elem` xs == not (c `L.notElem` xs) -- prop_filterByte xs c = L.filterByte c xs == L.filter (==c) xs -- prop_filterByte2 xs c = unpack (L.filterByte c xs) == filter (==c) (unpack xs) -- prop_filterNotByte xs c = L.filterNotByte c xs == L.filter (/=c) xs -- prop_filterNotByte2 xs c = unpack (L.filterNotByte c xs) == filter (/=c) (unpack xs) prop_find p xs = find p xs == L.find p (pack xs) prop_find_findIndex p xs = L.find p xs == case L.findIndex p xs of Just n -> Just (xs `L.index` n) _ -> Nothing prop_isPrefixOf xs ys = isPrefixOf xs ys == (pack xs `L.isPrefixOf` pack ys) {- prop_sort1 xs = sort xs == (unpack . L.sort . pack) xs prop_sort2 xs = (not (null xs)) ==> (L.head . L.sort . pack $ xs) == minimum xs prop_sort3 xs = (not (null xs)) ==> (L.last . L.sort . pack $ xs) == maximum xs prop_sort4 xs ys = (not (null xs)) ==> (not (null ys)) ==> (L.head . L.sort) (L.append (pack xs) (pack ys)) == min (minimum xs) (minimum ys) prop_sort5 xs ys = (not (null xs)) ==> (not (null ys)) ==> (L.last . L.sort) (L.append (pack xs) (pack ys)) == max (maximum xs) (maximum ys) -} ------------------------------------------------------------------------ -- Misc ByteString properties prop_nil1BB = P.length P.empty == 0 prop_nil2BB = P.unpack P.empty == [] prop_nil1BB_monoid = P.length mempty == 0 prop_nil2BB_monoid = P.unpack mempty == [] prop_nil1LL_monoid = L.length mempty == 0 prop_nil2LL_monoid = L.unpack mempty == [] prop_tailSBB xs = not (P.null xs) ==> P.tail xs == P.pack (tail (P.unpack xs)) prop_nullBB xs = null (P.unpack xs) == P.null xs prop_lengthBB xs = P.length xs == length1 xs where length1 ys | P.null ys = 0 | otherwise = 1 + length1 (P.tail ys) prop_lengthSBB xs = length xs == P.length (P.pack xs) prop_indexBB xs = not (null xs) ==> forAll indices $ \i -> (xs !! i) == P.pack xs `P.index` i where indices = choose (0, length xs -1) prop_unsafeIndexBB xs = not (null xs) ==> forAll indices $ \i -> (xs !! i) == P.pack xs `P.unsafeIndex` i where indices = choose (0, length xs -1) prop_mapfusionBB f g xs = P.map f (P.map g xs) == P.map (f . g) xs prop_filterBB f xs = P.filter f (P.pack xs) == P.pack (filter f xs) prop_filterfusionBB f g xs = P.filter f (P.filter g xs) == P.filter (\c -> f c && g c) xs prop_elemSBB x xs = P.elem x (P.pack xs) == elem x xs prop_takeSBB i xs = P.take i (P.pack xs) == P.pack (take i xs) prop_dropSBB i xs = P.drop i (P.pack xs) == P.pack (drop i xs) prop_splitAtSBB i xs = -- collect (i >= 0 && i < length xs) $ P.splitAt i (P.pack xs) == let (a,b) = splitAt i xs in (P.pack a, P.pack b) prop_foldlBB f c xs = P.foldl f c (P.pack xs) == foldl f c xs where _ = c :: Char prop_scanlfoldlBB f z xs = not (P.null xs) ==> P.last (P.scanl f z xs) == P.foldl f z xs prop_foldrBB f c xs = P.foldl f c (P.pack xs) == foldl f c xs where _ = c :: Char prop_takeWhileSBB f xs = P.takeWhile f (P.pack xs) == P.pack (takeWhile f xs) prop_dropWhileSBB f xs = P.dropWhile f (P.pack xs) == P.pack (dropWhile f xs) prop_spanSBB f xs = P.span f (P.pack xs) == let (a,b) = span f xs in (P.pack a, P.pack b) prop_breakSBB f xs = P.break f (P.pack xs) == let (a,b) = break f xs in (P.pack a, P.pack b) prop_breakspan_1BB xs c = P.break (== c) xs == P.span (/= c) xs prop_linesSBB xs = C.lines (C.pack xs) == map C.pack (lines xs) prop_unlinesSBB xss = C.unlines (map C.pack xss) == C.pack (unlines xss) prop_wordsSBB xs = C.words (C.pack xs) == map C.pack (words xs) prop_wordsLC xs = LC.words (LC.pack xs) == map LC.pack (words xs) prop_unwordsSBB xss = C.unwords (map C.pack xss) == C.pack (unwords xss) prop_unwordsSLC xss = LC.unwords (map LC.pack xss) == LC.pack (unwords xss) prop_splitWithBB f xs = (l1 == l2 || l1 == l2+1) && sum (map P.length splits) == P.length xs - l2 where splits = P.splitWith f xs l1 = length splits l2 = P.length (P.filter f xs) prop_joinsplitBB c xs = P.intercalate (P.pack [c]) (P.split c xs) == xs prop_intercalatePL c x y = P.intercalate (P.singleton c) (x : y : []) == -- intercalate (singleton c) (s1 : s2 : []) P.pack (intercalate [c] [P.unpack x,P.unpack y]) -- prop_linessplitBB xs = -- (not . C.null) xs ==> -- C.lines' xs == C.split '\n' xs -- false: {- prop_linessplit2BB xs = (not . C.null) xs ==> C.lines xs == C.split '\n' xs ++ (if C.last xs == '\n' then [C.empty] else []) -} prop_splitsplitWithBB c xs = P.split c xs == P.splitWith (== c) xs prop_bijectionBB c = (P.w2c . P.c2w) c == id c prop_bijectionBB' w = (P.c2w . P.w2c) w == id w prop_packunpackBB s = (P.unpack . P.pack) s == id s prop_packunpackBB' s = (P.pack . P.unpack) s == id s prop_eq1BB xs = xs == (P.unpack . P.pack $ xs) prop_eq2BB xs = xs == (xs :: P.ByteString) prop_eq3BB xs ys = (xs == ys) == (P.unpack xs == P.unpack ys) prop_compare1BB xs = (P.pack xs `compare` P.pack xs) == EQ prop_compare2BB xs c = (P.pack (xs++[c]) `compare` P.pack xs) == GT prop_compare3BB xs c = (P.pack xs `compare` P.pack (xs++[c])) == LT prop_compare4BB xs = (not (null xs)) ==> (P.pack xs `compare` P.empty) == GT prop_compare5BB xs = (not (null xs)) ==> (P.empty `compare` P.pack xs) == LT prop_compare6BB xs ys= (not (null ys)) ==> (P.pack (xs++ys) `compare` P.pack xs) == GT prop_compare7BB x y = x `compare` y == (C.singleton x `compare` C.singleton y) prop_compare8BB xs ys = xs `compare` ys == (P.pack xs `compare` P.pack ys) prop_consBB c xs = P.unpack (P.cons c (P.pack xs)) == (c:xs) prop_cons1BB xs = 'X' : xs == C.unpack ('X' `C.cons` (C.pack xs)) prop_cons2BB xs c = c : xs == P.unpack (c `P.cons` (P.pack xs)) prop_cons3BB c = C.unpack (C.singleton c) == (c:[]) prop_cons4BB c = (c `P.cons` P.empty) == P.pack (c:[]) prop_snoc1BB xs c = xs ++ [c] == P.unpack ((P.pack xs) `P.snoc` c) prop_head1BB xs = (not (null xs)) ==> head xs == (P.head . P.pack) xs prop_head2BB xs = (not (null xs)) ==> head xs == (P.unsafeHead . P.pack) xs prop_head3BB xs = not (P.null xs) ==> P.head xs == head (P.unpack xs) prop_tailBB xs = (not (null xs)) ==> tail xs == (P.unpack . P.tail . P.pack) xs prop_tail1BB xs = (not (null xs)) ==> tail xs == (P.unpack . P.unsafeTail. P.pack) xs prop_lastBB xs = (not (null xs)) ==> last xs == (P.last . P.pack) xs prop_last1BB xs = (not (null xs)) ==> last xs == (P.unsafeLast . P.pack) xs prop_initBB xs = (not (null xs)) ==> init xs == (P.unpack . P.init . P.pack) xs prop_init1BB xs = (not (null xs)) ==> init xs == (P.unpack . P.unsafeInit . P.pack) xs -- prop_null xs = (null xs) ==> null xs == (nullPS (pack xs)) prop_append1BB xs = (xs ++ xs) == (P.unpack $ P.pack xs `P.append` P.pack xs) prop_append2BB xs ys = (xs ++ ys) == (P.unpack $ P.pack xs `P.append` P.pack ys) prop_append3BB xs ys = P.append xs ys == P.pack (P.unpack xs ++ P.unpack ys) prop_append1BB_monoid xs = (xs ++ xs) == (P.unpack $ P.pack xs `mappend` P.pack xs) prop_append2BB_monoid xs ys = (xs ++ ys) == (P.unpack $ P.pack xs `mappend` P.pack ys) prop_append3BB_monoid xs ys = mappend xs ys == P.pack (P.unpack xs ++ P.unpack ys) prop_append1LL_monoid xs = (xs ++ xs) == (L.unpack $ L.pack xs `mappend` L.pack xs) prop_append2LL_monoid xs ys = (xs ++ ys) == (L.unpack $ L.pack xs `mappend` L.pack ys) prop_append3LL_monoid xs ys = mappend xs ys == L.pack (L.unpack xs ++ L.unpack ys) prop_map1BB f xs = P.map f (P.pack xs) == P.pack (map f xs) prop_map2BB f g xs = P.map f (P.map g xs) == P.map (f . g) xs prop_map3BB f xs = map f xs == (P.unpack . P.map f . P.pack) xs -- prop_mapBB' f xs = P.map' f (P.pack xs) == P.pack (map f xs) prop_filter1BB xs = (filter (=='X') xs) == (C.unpack $ C.filter (=='X') (C.pack xs)) prop_filter2BB p xs = (filter p xs) == (P.unpack $ P.filter p (P.pack xs)) prop_findBB p xs = find p xs == P.find p (P.pack xs) prop_find_findIndexBB p xs = P.find p xs == case P.findIndex p xs of Just n -> Just (xs `P.unsafeIndex` n) _ -> Nothing prop_foldl1BB xs a = ((foldl (\x c -> if c == a then x else c:x) [] xs)) == (P.unpack $ P.foldl (\x c -> if c == a then x else c `P.cons` x) P.empty (P.pack xs)) prop_foldl2BB xs = P.foldl (\xs c -> c `P.cons` xs) P.empty (P.pack xs) == P.reverse (P.pack xs) prop_foldr1BB xs a = ((foldr (\c x -> if c == a then x else c:x) [] xs)) == (P.unpack $ P.foldr (\c x -> if c == a then x else c `P.cons` x) P.empty (P.pack xs)) prop_foldr2BB xs = P.foldr (\c xs -> c `P.cons` xs) P.empty (P.pack xs) == (P.pack xs) prop_foldl1_1BB xs = (not . P.null) xs ==> P.foldl1 (\x c -> if c > x then c else x) xs == P.foldl (\x c -> if c > x then c else x) 0 xs prop_foldl1_2BB xs = (not . P.null) xs ==> P.foldl1 const xs == P.head xs prop_foldl1_3BB xs = (not . P.null) xs ==> P.foldl1 (flip const) xs == P.last xs prop_foldr1_1BB xs = (not . P.null) xs ==> P.foldr1 (\c x -> if c > x then c else x) xs == P.foldr (\c x -> if c > x then c else x) 0 xs prop_foldr1_2BB xs = (not . P.null) xs ==> P.foldr1 (flip const) xs == P.last xs prop_foldr1_3BB xs = (not . P.null) xs ==> P.foldr1 const xs == P.head xs prop_takeWhileBB xs a = (takeWhile (/= a) xs) == (P.unpack . (P.takeWhile (/= a)) . P.pack) xs prop_dropWhileBB xs a = (dropWhile (/= a) xs) == (P.unpack . (P.dropWhile (/= a)) . P.pack) xs prop_dropWhileCC_isSpace xs = (dropWhile isSpace xs) == (C.unpack . (C.dropWhile isSpace) . C.pack) xs prop_takeBB xs = (take 10 xs) == (P.unpack . (P.take 10) . P.pack) xs prop_dropBB xs = (drop 10 xs) == (P.unpack . (P.drop 10) . P.pack) xs prop_splitAtBB i xs = -- collect (i >= 0 && i < length xs) $ splitAt i xs == let (x,y) = P.splitAt i (P.pack xs) in (P.unpack x, P.unpack y) prop_spanBB xs a = (span (/=a) xs) == (let (x,y) = P.span (/=a) (P.pack xs) in (P.unpack x, P.unpack y)) prop_breakBB xs a = (break (/=a) xs) == (let (x,y) = P.break (/=a) (P.pack xs) in (P.unpack x, P.unpack y)) prop_reverse1BB xs = (reverse xs) == (P.unpack . P.reverse . P.pack) xs prop_reverse2BB xs = P.reverse (P.pack xs) == P.pack (reverse xs) prop_reverse3BB xs = reverse (P.unpack xs) == (P.unpack . P.reverse) xs prop_elemBB xs a = (a `elem` xs) == (a `P.elem` (P.pack xs)) prop_notElemBB c xs = P.notElem c (P.pack xs) == notElem c xs -- should try to stress it prop_concat1BB xs = (concat [xs,xs]) == (P.unpack $ P.concat [P.pack xs, P.pack xs]) prop_concat2BB xs = (concat [xs,[]]) == (P.unpack $ P.concat [P.pack xs, P.pack []]) prop_concatBB xss = P.concat (map P.pack xss) == P.pack (concat xss) prop_concat1BB_monoid xs = (concat [xs,xs]) == (P.unpack $ mconcat [P.pack xs, P.pack xs]) prop_concat2BB_monoid xs = (concat [xs,[]]) == (P.unpack $ mconcat [P.pack xs, P.pack []]) prop_concatBB_monoid xss = mconcat (map P.pack xss) == P.pack (concat xss) prop_concat1LL_monoid xs = (concat [xs,xs]) == (L.unpack $ mconcat [L.pack xs, L.pack xs]) prop_concat2LL_monoid xs = (concat [xs,[]]) == (L.unpack $ mconcat [L.pack xs, L.pack []]) prop_concatLL_monoid xss = mconcat (map L.pack xss) == L.pack (concat xss) prop_concatMapBB xs = C.concatMap C.singleton xs == (C.pack . concatMap (:[]) . C.unpack) xs prop_anyBB xs a = (any (== a) xs) == (P.any (== a) (P.pack xs)) prop_allBB xs a = (all (== a) xs) == (P.all (== a) (P.pack xs)) prop_linesBB xs = (lines xs) == ((map C.unpack) . C.lines . C.pack) xs prop_unlinesBB xs = (unlines.lines) xs == (C.unpack. C.unlines . C.lines .C.pack) xs prop_unlinesLC xs = (unlines.lines) xs == (LC.unpack. LC.unlines . LC.lines .LC.pack) xs prop_wordsBB xs = (words xs) == ((map C.unpack) . C.words . C.pack) xs -- prop_wordstokensBB xs = C.words xs == C.tokens isSpace xs prop_unwordsBB xs = (C.pack.unwords.words) xs == (C.unwords . C.words .C.pack) xs prop_groupBB xs = group xs == (map P.unpack . P.group . P.pack) xs prop_groupByBB xs = groupBy (==) xs == (map P.unpack . P.groupBy (==) . P.pack) xs prop_groupBy1CC xs = groupBy (==) xs == (map C.unpack . C.groupBy (==) . C.pack) xs prop_groupBy1BB xs = groupBy (/=) xs == (map P.unpack . P.groupBy (/=) . P.pack) xs prop_groupBy2CC xs = groupBy (/=) xs == (map C.unpack . C.groupBy (/=) . C.pack) xs prop_joinBB xs ys = (concat . (intersperse ys) . lines) xs == (C.unpack $ C.intercalate (C.pack ys) (C.lines (C.pack xs))) prop_elemIndex1BB xs = (elemIndex 'X' xs) == (C.elemIndex 'X' (C.pack xs)) prop_elemIndex2BB xs c = (elemIndex c xs) == (C.elemIndex c (C.pack xs)) -- prop_lineIndices1BB xs = C.elemIndices '\n' xs == C.lineIndices xs prop_countBB c xs = length (P.elemIndices c xs) == P.count c xs prop_elemIndexEnd1BB c xs = (P.elemIndexEnd c (P.pack xs)) == (case P.elemIndex c (P.pack (reverse xs)) of Nothing -> Nothing Just i -> Just (length xs -1 -i)) prop_elemIndexEnd1CC c xs = (C.elemIndexEnd c (C.pack xs)) == (case C.elemIndex c (C.pack (reverse xs)) of Nothing -> Nothing Just i -> Just (length xs -1 -i)) prop_elemIndexEnd2BB c xs = (P.elemIndexEnd c (P.pack xs)) == ((-) (length xs - 1) `fmap` P.elemIndex c (P.pack $ reverse xs)) prop_elemIndicesBB xs c = elemIndices c xs == P.elemIndices c (P.pack xs) prop_findIndexBB xs a = (findIndex (==a) xs) == (P.findIndex (==a) (P.pack xs)) prop_findIndiciesBB xs c = (findIndices (==c) xs) == (P.findIndices (==c) (P.pack xs)) -- example properties from QuickCheck.Batch prop_sort1BB xs = sort xs == (P.unpack . P.sort . P.pack) xs prop_sort2BB xs = (not (null xs)) ==> (P.head . P.sort . P.pack $ xs) == minimum xs prop_sort3BB xs = (not (null xs)) ==> (P.last . P.sort . P.pack $ xs) == maximum xs prop_sort4BB xs ys = (not (null xs)) ==> (not (null ys)) ==> (P.head . P.sort) (P.append (P.pack xs) (P.pack ys)) == min (minimum xs) (minimum ys) prop_sort5BB xs ys = (not (null xs)) ==> (not (null ys)) ==> (P.last . P.sort) (P.append (P.pack xs) (P.pack ys)) == max (maximum xs) (maximum ys) prop_intersperseBB c xs = (intersperse c xs) == (P.unpack $ P.intersperse c (P.pack xs)) -- prop_transposeBB xs = (transpose xs) == ((map P.unpack) . P.transpose . (map P.pack)) xs prop_maximumBB xs = (not (null xs)) ==> (maximum xs) == (P.maximum ( P.pack xs )) prop_minimumBB xs = (not (null xs)) ==> (minimum xs) == (P.minimum ( P.pack xs )) -- prop_dropSpaceBB xs = dropWhile isSpace xs == C.unpack (C.dropSpace (C.pack xs)) -- prop_dropSpaceEndBB xs = (C.reverse . (C.dropWhile isSpace) . C.reverse) (C.pack xs) == -- (C.dropSpaceEnd (C.pack xs)) -- prop_breakSpaceBB xs = -- (let (x,y) = C.breakSpace (C.pack xs) -- in (C.unpack x, C.unpack y)) == (break isSpace xs) prop_spanEndBB xs = (C.spanEnd (not . isSpace) (C.pack xs)) == (let (x,y) = C.span (not.isSpace) (C.reverse (C.pack xs)) in (C.reverse y,C.reverse x)) prop_breakEndBB p xs = P.breakEnd (not.p) xs == P.spanEnd p xs prop_breakEndCC p xs = C.breakEnd (not.p) xs == C.spanEnd p xs {- prop_breakCharBB c xs = (break (==c) xs) == (let (x,y) = C.breakChar c (C.pack xs) in (C.unpack x, C.unpack y)) prop_spanCharBB c xs = (break (/=c) xs) == (let (x,y) = C.spanChar c (C.pack xs) in (C.unpack x, C.unpack y)) prop_spanChar_1BB c xs = (C.span (==c) xs) == C.spanChar c xs prop_wordsBB' xs = (C.unpack . C.unwords . C.words' . C.pack) xs == (map (\c -> if isSpace c then ' ' else c) xs) -- prop_linesBB' xs = (C.unpack . C.unlines' . C.lines' . C.pack) xs == (xs) -} prop_unfoldrBB c = forAll arbitrarySizedIntegral $ \n -> (fst $ C.unfoldrN n fn c) == (C.pack $ take n $ unfoldr fn c) where fn x = Just (x, chr (ord x + 1)) prop_prefixBB xs ys = isPrefixOf xs ys == (P.pack xs `P.isPrefixOf` P.pack ys) prop_suffixBB xs ys = isSuffixOf xs ys == (P.pack xs `P.isSuffixOf` P.pack ys) prop_suffixLL xs ys = isSuffixOf xs ys == (L.pack xs `L.isSuffixOf` L.pack ys) prop_copyBB xs = let p = P.pack xs in P.copy p == p prop_copyLL xs = let p = L.pack xs in L.copy p == p prop_initsBB xs = inits xs == map P.unpack (P.inits (P.pack xs)) prop_tailsBB xs = tails xs == map P.unpack (P.tails (P.pack xs)) prop_findSubstringsBB s x l = C.findSubstrings (C.pack p) (C.pack s) == naive_findSubstrings p s where _ = l :: Int _ = x :: Int -- we look for some random substring of the test string p = take (model l) $ drop (model x) s -- naive reference implementation naive_findSubstrings :: String -> String -> [Int] naive_findSubstrings p s = [x | x <- [0..length s], p `isPrefixOf` drop x s] prop_findSubstringBB s x l = C.findSubstring (C.pack p) (C.pack s) == naive_findSubstring p s where _ = l :: Int _ = x :: Int -- we look for some random substring of the test string p = take (model l) $ drop (model x) s -- naive reference implementation naive_findSubstring :: String -> String -> Maybe Int naive_findSubstring p s = listToMaybe [x | x <- [0..length s], p `isPrefixOf` drop x s] -- correspondance between break and breakSubstring prop_breakSubstringBB c l = P.break (== c) l == P.breakSubstring (P.singleton c) l prop_breakSubstring_isInfixOf s l = P.isInfixOf s l == if P.null s then True else case P.breakSubstring s l of (x,y) | P.null y -> False | otherwise -> True prop_breakSubstring_findSubstring s l = P.findSubstring s l == if P.null s then Just 0 else case P.breakSubstring s l of (x,y) | P.null y -> Nothing | otherwise -> Just (P.length x) prop_replicate1BB c = forAll arbitrarySizedIntegral $ \n -> P.unpack (P.replicate n c) == replicate n c prop_replicate2BB c = forAll arbitrarySizedIntegral $ \n -> P.replicate n c == fst (P.unfoldrN n (\u -> Just (u,u)) c) prop_replicate3BB c = P.unpack (P.replicate 0 c) == replicate 0 c prop_readintBB n = (fst . fromJust . C.readInt . C.pack . show) n == (n :: Int) prop_readintLL n = (fst . fromJust . D.readInt . D.pack . show) n == (n :: Int) prop_readBB x = (read . show) x == (x :: P.ByteString) prop_readLL x = (read . show) x == (x :: L.ByteString) prop_readint2BB s = let s' = filter (\c -> c `notElem` ['0'..'9']) s in C.readInt (C.pack s') == Nothing prop_readintegerBB n = (fst . fromJust . C.readInteger . C.pack . show) n == (n :: Integer) prop_readintegerLL n = (fst . fromJust . D.readInteger . D.pack . show) n == (n :: Integer) prop_readinteger2BB s = let s' = filter (\c -> c `notElem` ['0'..'9']) s in C.readInteger (C.pack s') == Nothing -- prop_filterChar1BB c xs = (filter (==c) xs) == ((C.unpack . C.filterChar c . C.pack) xs) -- prop_filterChar2BB c xs = (C.filter (==c) (C.pack xs)) == (C.filterChar c (C.pack xs)) -- prop_filterChar3BB c xs = C.filterChar c xs == C.replicate (C.count c xs) c -- prop_filterNotChar1BB c xs = (filter (/=c) xs) == ((C.unpack . C.filterNotChar c . C.pack) xs) -- prop_filterNotChar2BB c xs = (C.filter (/=c) (C.pack xs)) == (C.filterNotChar c (C.pack xs)) -- prop_joinjoinpathBB xs ys c = C.joinWithChar c xs ys == C.join (C.singleton c) [xs,ys] prop_zipBB xs ys = zip xs ys == P.zip (P.pack xs) (P.pack ys) prop_zipLC xs ys = zip xs ys == LC.zip (LC.pack xs) (LC.pack ys) prop_zip1BB xs ys = P.zip xs ys == zip (P.unpack xs) (P.unpack ys) prop_zipWithBB xs ys = P.zipWith (,) xs ys == P.zip xs ys prop_zipWithCC xs ys = C.zipWith (,) xs ys == C.zip xs ys prop_zipWithLC xs ys = LC.zipWith (,) xs ys == LC.zip xs ys -- prop_zipWith'BB xs ys = P.pack (P.zipWith (+) xs ys) == P.zipWith' (+) xs ys prop_unzipBB x = let (xs,ys) = unzip x in (P.pack xs, P.pack ys) == P.unzip x ------------------------------------------------------------------------ -- -- And check fusion RULES. -- {- prop_lazylooploop em1 em2 start1 start2 arr = loopL em2 start2 (loopArr (loopL em1 start1 arr)) == loopSndAcc (loopL (em1 `fuseEFL` em2) (start1 :*: start2) arr) where _ = start1 :: Int _ = start2 :: Int prop_looploop em1 em2 start1 start2 arr = loopU em2 start2 (loopArr (loopU em1 start1 arr)) == loopSndAcc (loopU (em1 `fuseEFL` em2) (start1 :*: start2) arr) where _ = start1 :: Int _ = start2 :: Int ------------------------------------------------------------------------ -- check associativity of sequence loops prop_sequenceloops_assoc n m o x y z a1 a2 a3 xs = k ((f * g) * h) == k (f * (g * h)) -- associativity where (*) = sequenceLoops f = (sel n) x a1 g = (sel m) y a2 h = (sel o) z a3 _ = a1 :: Int; _ = a2 :: Int; _ = a3 :: Int k g = loopArr (loopWrapper g xs) -- check wrapper elimination prop_loop_loop_wrapper_elimination n m x y a1 a2 xs = loopWrapper g (loopArr (loopWrapper f xs)) == loopSndAcc (loopWrapper (sequenceLoops f g) xs) where f = (sel n) x a1 g = (sel m) y a2 _ = a1 :: Int; _ = a2 :: Int sel :: Bool -> (acc -> Word8 -> PairS acc (MaybeS Word8)) -> acc -> Ptr Word8 -> Ptr Word8 -> Int -> IO (PairS (PairS acc Int) Int) sel False = doDownLoop sel True = doUpLoop ------------------------------------------------------------------------ -- -- Test fusion forms -- prop_up_up_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doUpLoop f1 acc1) (doUpLoop f2 acc2)) == k (doUpLoop (f1 `fuseAccAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int; k g = loopWrapper g xs prop_down_down_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doDownLoop f1 acc1) (doDownLoop f2 acc2)) == k (doDownLoop (f1 `fuseAccAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int ; _ = acc2 :: Int ; k g = loopWrapper g xs prop_noAcc_noAcc_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doNoAccLoop f1 acc1) (doNoAccLoop f2 acc2)) == k (doNoAccLoop (f1 `fuseNoAccNoAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int ; _ = acc2 :: Int ; k g = loopWrapper g xs prop_noAcc_up_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doNoAccLoop f1 acc1) (doUpLoop f2 acc2)) == k (doUpLoop (f1 `fuseNoAccAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int; k g = loopWrapper g xs prop_up_noAcc_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doUpLoop f1 acc1) (doNoAccLoop f2 acc2)) == k (doUpLoop (f1 `fuseAccNoAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int; k g = loopWrapper g xs prop_noAcc_down_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doNoAccLoop f1 acc1) (doDownLoop f2 acc2)) == k (doDownLoop (f1 `fuseNoAccAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_down_noAcc_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doDownLoop f1 acc1) (doNoAccLoop f2 acc2)) == k (doDownLoop (f1 `fuseAccNoAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int; k g = loopWrapper g xs prop_map_map_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doMapLoop f1 acc1) (doMapLoop f2 acc2)) == k (doMapLoop (f1 `fuseMapMapEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_filter_filter_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doFilterLoop f1 acc1) (doFilterLoop f2 acc2)) == k (doFilterLoop (f1 `fuseFilterFilterEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_map_filter_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doMapLoop f1 acc1) (doFilterLoop f2 acc2)) == k (doNoAccLoop (f1 `fuseMapFilterEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_filter_map_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doFilterLoop f1 acc1) (doMapLoop f2 acc2)) == k (doNoAccLoop (f1 `fuseFilterMapEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_map_noAcc_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doMapLoop f1 acc1) (doNoAccLoop f2 acc2)) == k (doNoAccLoop (f1 `fuseMapNoAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_noAcc_map_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doNoAccLoop f1 acc1) (doMapLoop f2 acc2)) == k (doNoAccLoop (f1 `fuseNoAccMapEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_map_up_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doMapLoop f1 acc1) (doUpLoop f2 acc2)) == k (doUpLoop (f1 `fuseMapAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_up_map_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doUpLoop f1 acc1) (doMapLoop f2 acc2)) == k (doUpLoop (f1 `fuseAccMapEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_map_down_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doMapLoop f1 acc1) (doDownLoop f2 acc2)) == k (doDownLoop (f1 `fuseMapAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_down_map_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doDownLoop f1 acc1) (doMapLoop f2 acc2)) == k (doDownLoop (f1 `fuseAccMapEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_filter_noAcc_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doFilterLoop f1 acc1) (doNoAccLoop f2 acc2)) == k (doNoAccLoop (f1 `fuseFilterNoAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_noAcc_filter_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doNoAccLoop f1 acc1) (doFilterLoop f2 acc2)) == k (doNoAccLoop (f1 `fuseNoAccFilterEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_filter_up_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doFilterLoop f1 acc1) (doUpLoop f2 acc2)) == k (doUpLoop (f1 `fuseFilterAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_up_filter_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doUpLoop f1 acc1) (doFilterLoop f2 acc2)) == k (doUpLoop (f1 `fuseAccFilterEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_filter_down_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doFilterLoop f1 acc1) (doDownLoop f2 acc2)) == k (doDownLoop (f1 `fuseFilterAccEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs prop_down_filter_loop_fusion f1 f2 acc1 acc2 xs = k (sequenceLoops (doDownLoop f1 acc1) (doFilterLoop f2 acc2)) == k (doDownLoop (f1 `fuseAccFilterEFL` f2) (acc1 :*: acc2)) where _ = acc1 :: Int; _ = acc2 :: Int ; k g = loopWrapper g xs ------------------------------------------------------------------------ {- prop_length_loop_fusion_1 f1 acc1 xs = P.length (loopArr (loopWrapper (doUpLoop f1 acc1) xs)) == P.lengthU (loopArr (loopWrapper (doUpLoop f1 acc1) xs)) where _ = acc1 :: Int prop_length_loop_fusion_2 f1 acc1 xs = P.length (loopArr (loopWrapper (doDownLoop f1 acc1) xs)) == P.lengthU (loopArr (loopWrapper (doDownLoop f1 acc1) xs)) where _ = acc1 :: Int prop_length_loop_fusion_3 f1 acc1 xs = P.length (loopArr (loopWrapper (doMapLoop f1 acc1) xs)) == P.lengthU (loopArr (loopWrapper (doMapLoop f1 acc1) xs)) where _ = acc1 :: Int prop_length_loop_fusion_4 f1 acc1 xs = P.length (loopArr (loopWrapper (doFilterLoop f1 acc1) xs)) == P.lengthU (loopArr (loopWrapper (doFilterLoop f1 acc1) xs)) where _ = acc1 :: Int -} -} -- prop_zipwith_spec f p q = -- P.pack (P.zipWith f p q) == P.zipWith' f p q -- where _ = f :: Word8 -> Word8 -> Word8 -- prop_join_spec c s1 s2 = -- P.join (P.singleton c) (s1 : s2 : []) == P.joinWithByte c s1 s2 -- prop_break_spec x s = -- P.break ((==) x) s == P.breakByte x s -- prop_span_spec x s = -- P.span ((==) x) s == P.spanByte x s ------------------------------------------------------------------------ -- Test IsString, Show, Read, pack, unpack prop_isstring x = C.unpack (fromString x :: C.ByteString) == x prop_isstring_lc x = LC.unpack (fromString x :: LC.ByteString) == x prop_showP1 x = show x == show (C.unpack x) prop_showL1 x = show x == show (LC.unpack x) prop_readP1 x = read (show x) == (x :: P.ByteString) prop_readP2 x = read (show x) == C.pack (x :: String) prop_readL1 x = read (show x) == (x :: L.ByteString) prop_readL2 x = read (show x) == LC.pack (x :: String) prop_packunpack_s x = (P.unpack . P.pack) x == x prop_unpackpack_s x = (P.pack . P.unpack) x == x prop_packunpack_c x = (C.unpack . C.pack) x == x prop_unpackpack_c x = (C.pack . C.unpack) x == x prop_packunpack_l x = (L.unpack . L.pack) x == x prop_unpackpack_l x = (L.pack . L.unpack) x == x prop_packunpack_lc x = (LC.unpack . LC.pack) x == x prop_unpackpack_lc x = (LC.pack . LC.unpack) x == x prop_toFromChunks x = (L.fromChunks . L.toChunks) x == x prop_fromToChunks x = (L.toChunks . L.fromChunks) x == filter (not . P.null) x prop_toFromStrict x = (L.fromStrict . L.toStrict) x == x prop_fromToStrict x = (L.toStrict . L.fromStrict) x == x prop_packUptoLenBytes cs = forAll (choose (0, length cs + 1)) $ \n -> let (bs, cs') = P.packUptoLenBytes n cs in P.length bs == min n (length cs) && take n cs == P.unpack bs && P.pack (take n cs) == bs && drop n cs == cs' prop_packUptoLenChars cs = forAll (choose (0, length cs + 1)) $ \n -> let (bs, cs') = P.packUptoLenChars n cs in P.length bs == min n (length cs) && take n cs == C.unpack bs && C.pack (take n cs) == bs && drop n cs == cs' prop_unpack_s cs = forAll (choose (0, length cs)) $ \n -> P.unpack (P.drop n $ P.pack cs) == drop n cs prop_unpack_c cs = forAll (choose (0, length cs)) $ \n -> C.unpack (C.drop n $ C.pack cs) == drop n cs prop_unpack_l cs = forAll (choose (0, length cs)) $ \n -> L.unpack (L.drop (fromIntegral n) $ L.pack cs) == drop n cs prop_unpack_lc cs = forAll (choose (0, length cs)) $ \n -> LC.unpack (L.drop (fromIntegral n) $ LC.pack cs) == drop n cs prop_unpackBytes cs = forAll (choose (0, length cs)) $ \n -> P.unpackBytes (P.drop n $ P.pack cs) == drop n cs prop_unpackChars cs = forAll (choose (0, length cs)) $ \n -> P.unpackChars (P.drop n $ C.pack cs) == drop n cs prop_unpackBytes_l = forAll (sized $ \n -> resize (n * 10) arbitrary) $ \cs -> forAll (choose (0, length cs)) $ \n -> L.unpackBytes (L.drop (fromIntegral n) $ L.pack cs) == drop n cs prop_unpackChars_l = forAll (sized $ \n -> resize (n * 10) arbitrary) $ \cs -> forAll (choose (0, length cs)) $ \n -> L.unpackChars (L.drop (fromIntegral n) $ LC.pack cs) == drop n cs prop_unpackAppendBytesLazy cs' = forAll (sized $ \n -> resize (n * 10) arbitrary) $ \cs -> forAll (choose (0, 2)) $ \n -> P.unpackAppendBytesLazy (P.drop n $ P.pack cs) cs' == drop n cs ++ cs' prop_unpackAppendCharsLazy cs' = forAll (sized $ \n -> resize (n * 10) arbitrary) $ \cs -> forAll (choose (0, 2)) $ \n -> P.unpackAppendCharsLazy (P.drop n $ C.pack cs) cs' == drop n cs ++ cs' prop_unpackAppendBytesStrict cs cs' = forAll (choose (0, length cs)) $ \n -> P.unpackAppendBytesStrict (P.drop n $ P.pack cs) cs' == drop n cs ++ cs' prop_unpackAppendCharsStrict cs cs' = forAll (choose (0, length cs)) $ \n -> P.unpackAppendCharsStrict (P.drop n $ C.pack cs) cs' == drop n cs ++ cs' ------------------------------------------------------------------------ -- Unsafe functions -- Test unsafePackAddress prop_unsafePackAddress (CByteString x) = unsafePerformIO $ do let (p,_,_) = P.toForeignPtr (x `P.snoc` 0) y <- withForeignPtr p $ \(Ptr addr) -> P.unsafePackAddress addr return (y == x) -- Test unsafePackAddressLen prop_unsafePackAddressLen x = unsafePerformIO $ do let i = P.length x (p,_,_) = P.toForeignPtr (x `P.snoc` 0) y <- withForeignPtr p $ \(Ptr addr) -> P.unsafePackAddressLen i addr return (y == x) prop_unsafeUseAsCString x = unsafePerformIO $ do let n = P.length x y <- P.unsafeUseAsCString x $ \cstr -> sequence [ do a <- peekElemOff cstr i let b = x `P.index` i return (a == fromIntegral b) | i <- [0.. n-1] ] return (and y) prop_unsafeUseAsCStringLen x = unsafePerformIO $ do let n = P.length x y <- P.unsafeUseAsCStringLen x $ \(cstr,_) -> sequence [ do a <- peekElemOff cstr i let b = x `P.index` i return (a == fromIntegral b) | i <- [0.. n-1] ] return (and y) prop_internal_invariant x = L.invariant x prop_useAsCString x = unsafePerformIO $ do let n = P.length x y <- P.useAsCString x $ \cstr -> sequence [ do a <- peekElemOff cstr i let b = x `P.index` i return (a == fromIntegral b) | i <- [0.. n-1] ] return (and y) prop_packCString (CByteString x) = unsafePerformIO $ do y <- P.useAsCString x $ P.unsafePackCString return (y == x) prop_packCString_safe (CByteString x) = unsafePerformIO $ do y <- P.useAsCString x $ P.packCString return (y == x) prop_packCStringLen x = unsafePerformIO $ do y <- P.useAsCStringLen x $ P.unsafePackCStringLen return (y == x && P.length y == P.length x) prop_packCStringLen_safe x = unsafePerformIO $ do y <- P.useAsCStringLen x $ P.packCStringLen return (y == x && P.length y == P.length x) prop_packMallocCString (CByteString x) = unsafePerformIO $ do let (fp,_,_) = P.toForeignPtr x ptr <- mallocArray0 (P.length x) :: IO (Ptr Word8) forM_ [0 .. P.length x] $ \n -> pokeElemOff ptr n 0 withForeignPtr fp $ \qtr -> copyArray ptr qtr (P.length x) y <- P.unsafePackMallocCString (castPtr ptr) let !z = y == x free ptr `seq` return z prop_unsafeFinalize x = P.length x > 0 ==> unsafePerformIO $ do x <- P.unsafeFinalize x return (x == ()) prop_packCStringFinaliser x = unsafePerformIO $ do y <- P.useAsCString x $ \cstr -> P.unsafePackCStringFinalizer (castPtr cstr) (P.length x) (return ()) return (y == x) prop_fromForeignPtr x = (let (a,b,c) = (P.toForeignPtr x) in P.fromForeignPtr a b c) == x ------------------------------------------------------------------------ -- IO prop_read_write_file_P x = unsafePerformIO $ do tid <- myThreadId let f = "qc-test-"++show tid bracket (do P.writeFile f x) (const $ do removeFile f) (const $ do y <- P.readFile f return (x==y)) prop_read_write_file_C x = unsafePerformIO $ do tid <- myThreadId let f = "qc-test-"++show tid bracket (do C.writeFile f x) (const $ do removeFile f) (const $ do y <- C.readFile f return (x==y)) prop_read_write_file_L x = unsafePerformIO $ do tid <- myThreadId let f = "qc-test-"++show tid bracket (do L.writeFile f x) (const $ do removeFile f) (const $ do y <- L.readFile f return (x==y)) prop_read_write_file_D x = unsafePerformIO $ do tid <- myThreadId let f = "qc-test-"++show tid bracket (do D.writeFile f x) (const $ do removeFile f) (const $ do y <- D.readFile f return (x==y)) ------------------------------------------------------------------------ prop_append_file_P x y = unsafePerformIO $ do tid <- myThreadId let f = "qc-test-"++show tid bracket (do P.writeFile f x P.appendFile f y) (const $ do removeFile f) (const $ do z <- P.readFile f return (z==(x `P.append` y))) prop_append_file_C x y = unsafePerformIO $ do tid <- myThreadId let f = "qc-test-"++show tid bracket (do C.writeFile f x C.appendFile f y) (const $ do removeFile f) (const $ do z <- C.readFile f return (z==(x `C.append` y))) prop_append_file_L x y = unsafePerformIO $ do tid <- myThreadId let f = "qc-test-"++show tid bracket (do L.writeFile f x L.appendFile f y) (const $ do removeFile f) (const $ do z <- L.readFile f return (z==(x `L.append` y))) prop_append_file_D x y = unsafePerformIO $ do tid <- myThreadId let f = "qc-test-"++show tid bracket (do D.writeFile f x D.appendFile f y) (const $ do removeFile f) (const $ do z <- D.readFile f return (z==(x `D.append` y))) prop_packAddress = C.pack "this is a test" == C.pack "this is a test" prop_isSpaceWord8 (w :: Word8) = isSpace c == P.isSpaceChar8 c where c = chr (fromIntegral w) ------------------------------------------------------------------------ -- ByteString.Short -- prop_short_pack_unpack xs = (Short.unpack . Short.pack) xs == xs prop_short_toShort_fromShort bs = (Short.fromShort . Short.toShort) bs == bs prop_short_toShort_unpack bs = (Short.unpack . Short.toShort) bs == P.unpack bs prop_short_pack_fromShort xs = (Short.fromShort . Short.pack) xs == P.pack xs prop_short_empty = Short.empty == Short.toShort P.empty && Short.empty == Short.pack [] && Short.null (Short.toShort P.empty) && Short.null (Short.pack []) && Short.null Short.empty prop_short_null_toShort bs = P.null bs == Short.null (Short.toShort bs) prop_short_null_pack xs = null xs == Short.null (Short.pack xs) prop_short_length_toShort bs = P.length bs == Short.length (Short.toShort bs) prop_short_length_pack xs = length xs == Short.length (Short.pack xs) prop_short_index_pack xs = all (\i -> Short.pack xs `Short.index` i == xs !! i) [0 .. length xs - 1] prop_short_index_toShort bs = all (\i -> Short.toShort bs `Short.index` i == bs `P.index` i) [0 .. P.length bs - 1] prop_short_eq xs ys = (xs == ys) == (Short.pack xs == Short.pack ys) prop_short_ord xs ys = (xs `compare` ys) == (Short.pack xs `compare` Short.pack ys) prop_short_mappend_empty_empty = Short.empty `mappend` Short.empty == Short.empty prop_short_mappend_empty xs = Short.empty `mappend` Short.pack xs == Short.pack xs && Short.pack xs `mappend` Short.empty == Short.pack xs prop_short_mappend xs ys = (xs `mappend` ys) == Short.unpack (Short.pack xs `mappend` Short.pack ys) prop_short_mconcat xss = mconcat xss == Short.unpack (mconcat (map Short.pack xss)) prop_short_fromString s = fromString s == Short.fromShort (fromString s) prop_short_show xs = show (Short.pack xs) == show (map P.w2c xs) prop_short_show' xs = show (Short.pack xs) == show (P.pack xs) prop_short_read xs = read (show (Short.pack xs)) == Short.pack xs short_tests = [ testProperty "pack/unpack" prop_short_pack_unpack , testProperty "toShort/fromShort" prop_short_toShort_fromShort , testProperty "toShort/unpack" prop_short_toShort_unpack , testProperty "pack/fromShort" prop_short_pack_fromShort , testProperty "empty" prop_short_empty , testProperty "null/toShort" prop_short_null_toShort , testProperty "null/pack" prop_short_null_pack , testProperty "length/toShort" prop_short_length_toShort , testProperty "length/pack" prop_short_length_pack , testProperty "index/pack" prop_short_index_pack , testProperty "index/toShort" prop_short_index_toShort , testProperty "Eq" prop_short_eq , testProperty "Ord" prop_short_ord , testProperty "mappend/empty/empty" prop_short_mappend_empty_empty , testProperty "mappend/empty" prop_short_mappend_empty , testProperty "mappend" prop_short_mappend , testProperty "mconcat" prop_short_mconcat , testProperty "fromString" prop_short_fromString , testProperty "show" prop_short_show , testProperty "show'" prop_short_show' , testProperty "read" prop_short_read ] ------------------------------------------------------------------------ -- The entry point main :: IO () main = defaultMain tests -- -- And now a list of all the properties to test. -- tests = misc_tests ++ bl_tests ++ cc_tests ++ bp_tests ++ pl_tests ++ bb_tests ++ ll_tests ++ io_tests ++ short_tests ++ rules -- -- 'morally sound' IO -- io_tests = [ testProperty "readFile.writeFile" prop_read_write_file_P , testProperty "readFile.writeFile" prop_read_write_file_C , testProperty "readFile.writeFile" prop_read_write_file_L , testProperty "readFile.writeFile" prop_read_write_file_D , testProperty "appendFile " prop_append_file_P , testProperty "appendFile " prop_append_file_C , testProperty "appendFile " prop_append_file_L , testProperty "appendFile " prop_append_file_D , testProperty "packAddress " prop_packAddress ] misc_tests = [ testProperty "packunpack" prop_packunpack_s , testProperty "unpackpack" prop_unpackpack_s , testProperty "packunpack" prop_packunpack_c , testProperty "unpackpack" prop_unpackpack_c , testProperty "packunpack" prop_packunpack_l , testProperty "unpackpack" prop_unpackpack_l , testProperty "packunpack" prop_packunpack_lc , testProperty "unpackpack" prop_unpackpack_lc , testProperty "unpack" prop_unpack_s , testProperty "unpack" prop_unpack_c , testProperty "unpack" prop_unpack_l , testProperty "unpack" prop_unpack_lc , testProperty "packUptoLenBytes" prop_packUptoLenBytes , testProperty "packUptoLenChars" prop_packUptoLenChars , testProperty "unpackBytes" prop_unpackBytes , testProperty "unpackChars" prop_unpackChars , testProperty "unpackBytes" prop_unpackBytes_l , testProperty "unpackChars" prop_unpackChars_l , testProperty "unpackAppendBytesLazy" prop_unpackAppendBytesLazy , testProperty "unpackAppendCharsLazy" prop_unpackAppendCharsLazy , testProperty "unpackAppendBytesStrict"prop_unpackAppendBytesStrict , testProperty "unpackAppendCharsStrict"prop_unpackAppendCharsStrict , testProperty "toFromChunks" prop_toFromChunks , testProperty "fromToChunks" prop_fromToChunks , testProperty "toFromStrict" prop_toFromStrict , testProperty "fromToStrict" prop_fromToStrict , testProperty "invariant" prop_invariant , testProperty "unsafe pack address" prop_unsafePackAddress , testProperty "unsafe pack address len"prop_unsafePackAddressLen , testProperty "unsafeUseAsCString" prop_unsafeUseAsCString , testProperty "unsafeUseAsCStringLen" prop_unsafeUseAsCStringLen , testProperty "useAsCString" prop_useAsCString , testProperty "packCString" prop_packCString , testProperty "packCString safe" prop_packCString_safe , testProperty "packCStringLen" prop_packCStringLen , testProperty "packCStringLen safe" prop_packCStringLen_safe , testProperty "packCStringFinaliser" prop_packCStringFinaliser , testProperty "packMallocString" prop_packMallocCString , testProperty "unsafeFinalise" prop_unsafeFinalize , testProperty "invariant" prop_internal_invariant , testProperty "show 1" prop_showP1 , testProperty "show 2" prop_showL1 , testProperty "read 1" prop_readP1 , testProperty "read 2" prop_readP2 , testProperty "read 3" prop_readL1 , testProperty "read 4" prop_readL2 , testProperty "fromForeignPtr" prop_fromForeignPtr ] ------------------------------------------------------------------------ -- ByteString.Lazy <=> List bl_tests = [ testProperty "all" prop_allBL , testProperty "any" prop_anyBL , testProperty "append" prop_appendBL , testProperty "compare" prop_compareBL , testProperty "concat" prop_concatBL , testProperty "cons" prop_consBL , testProperty "eq" prop_eqBL , testProperty "filter" prop_filterBL , testProperty "find" prop_findBL , testProperty "findIndex" prop_findIndexBL , testProperty "findIndices" prop_findIndicesBL , testProperty "foldl" prop_foldlBL , testProperty "foldl'" prop_foldlBL' , testProperty "foldl1" prop_foldl1BL , testProperty "foldl1'" prop_foldl1BL' , testProperty "foldr" prop_foldrBL , testProperty "foldr1" prop_foldr1BL , testProperty "mapAccumL" prop_mapAccumLBL , testProperty "mapAccumR" prop_mapAccumRBL , testProperty "mapAccumR" prop_mapAccumRDL , testProperty "mapAccumR" prop_mapAccumRCC , testProperty "unfoldr" prop_unfoldrBL , testProperty "unfoldr" prop_unfoldrLC , testProperty "unfoldr" prop_cycleLC , testProperty "iterate" prop_iterateLC , testProperty "iterate" prop_iterateLC_2 , testProperty "iterate" prop_iterateL , testProperty "repeat" prop_repeatLC , testProperty "repeat" prop_repeatL , testProperty "head" prop_headBL , testProperty "init" prop_initBL , testProperty "isPrefixOf" prop_isPrefixOfBL , testProperty "last" prop_lastBL , testProperty "length" prop_lengthBL , testProperty "map" prop_mapBL , testProperty "maximum" prop_maximumBL , testProperty "minimum" prop_minimumBL , testProperty "null" prop_nullBL , testProperty "reverse" prop_reverseBL , testProperty "snoc" prop_snocBL , testProperty "tail" prop_tailBL , testProperty "transpose" prop_transposeBL , testProperty "replicate" prop_replicateBL , testProperty "take" prop_takeBL , testProperty "drop" prop_dropBL , testProperty "splitAt" prop_splitAtBL , testProperty "takeWhile" prop_takeWhileBL , testProperty "dropWhile" prop_dropWhileBL , testProperty "break" prop_breakBL , testProperty "span" prop_spanBL , testProperty "group" prop_groupBL , testProperty "groupBy" prop_groupByBL , testProperty "inits" prop_initsBL , testProperty "tails" prop_tailsBL , testProperty "elem" prop_elemBL , testProperty "notElem" prop_notElemBL , testProperty "lines" prop_linesBL , testProperty "elemIndex" prop_elemIndexBL , testProperty "elemIndices" prop_elemIndicesBL , testProperty "concatMap" prop_concatMapBL ] ------------------------------------------------------------------------ -- ByteString.Lazy <=> ByteString cc_tests = [ testProperty "prop_concatCC" prop_concatCC , testProperty "prop_nullCC" prop_nullCC , testProperty "prop_reverseCC" prop_reverseCC , testProperty "prop_transposeCC" prop_transposeCC , testProperty "prop_groupCC" prop_groupCC , testProperty "prop_groupByCC" prop_groupByCC , testProperty "prop_initsCC" prop_initsCC , testProperty "prop_tailsCC" prop_tailsCC , testProperty "prop_allCC" prop_allCC , testProperty "prop_anyCC" prop_anyCC , testProperty "prop_appendCC" prop_appendCC , testProperty "prop_breakCC" prop_breakCC , testProperty "prop_concatMapCC" prop_concatMapCC , testProperty "prop_consCC" prop_consCC , testProperty "prop_consCC'" prop_consCC' , testProperty "prop_unconsCC" prop_unconsCC , testProperty "prop_unsnocCC" prop_unsnocCC , testProperty "prop_countCC" prop_countCC , testProperty "prop_dropCC" prop_dropCC , testProperty "prop_dropWhileCC" prop_dropWhileCC , testProperty "prop_filterCC" prop_filterCC , testProperty "prop_findCC" prop_findCC , testProperty "prop_findIndexCC" prop_findIndexCC , testProperty "prop_findIndicesCC" prop_findIndicesCC , testProperty "prop_isPrefixOfCC" prop_isPrefixOfCC , testProperty "prop_mapCC" prop_mapCC , testProperty "prop_replicateCC" prop_replicateCC , testProperty "prop_snocCC" prop_snocCC , testProperty "prop_spanCC" prop_spanCC , testProperty "prop_splitCC" prop_splitCC , testProperty "prop_splitAtCC" prop_splitAtCC , testProperty "prop_takeCC" prop_takeCC , testProperty "prop_takeWhileCC" prop_takeWhileCC , testProperty "prop_elemCC" prop_elemCC , testProperty "prop_notElemCC" prop_notElemCC , testProperty "prop_elemIndexCC" prop_elemIndexCC , testProperty "prop_elemIndicesCC" prop_elemIndicesCC , testProperty "prop_lengthCC" prop_lengthCC , testProperty "prop_headCC" prop_headCC , testProperty "prop_initCC" prop_initCC , testProperty "prop_lastCC" prop_lastCC , testProperty "prop_maximumCC" prop_maximumCC , testProperty "prop_minimumCC" prop_minimumCC , testProperty "prop_tailCC" prop_tailCC , testProperty "prop_foldl1CC" prop_foldl1CC , testProperty "prop_foldl1CC'" prop_foldl1CC' , testProperty "prop_foldr1CC" prop_foldr1CC , testProperty "prop_foldr1CC'" prop_foldr1CC' , testProperty "prop_scanlCC" prop_scanlCC , testProperty "prop_intersperseCC" prop_intersperseCC , testProperty "prop_foldlCC" prop_foldlCC , testProperty "prop_foldlCC'" prop_foldlCC' , testProperty "prop_foldrCC" prop_foldrCC , testProperty "prop_foldrCC'" prop_foldrCC' , testProperty "prop_mapAccumLCC" prop_mapAccumLCC -- , testProperty "prop_mapIndexedCC" prop_mapIndexedCC -- , testProperty "prop_mapIndexedPL" prop_mapIndexedPL ] bp_tests = [ testProperty "all" prop_allBP , testProperty "any" prop_anyBP , testProperty "append" prop_appendBP , testProperty "compare" prop_compareBP , testProperty "concat" prop_concatBP , testProperty "cons" prop_consBP , testProperty "cons'" prop_consBP' , testProperty "uncons" prop_unconsBP , testProperty "unsnoc" prop_unsnocBP , testProperty "eq" prop_eqBP , testProperty "filter" prop_filterBP , testProperty "find" prop_findBP , testProperty "findIndex" prop_findIndexBP , testProperty "findIndices" prop_findIndicesBP , testProperty "foldl" prop_foldlBP , testProperty "foldl'" prop_foldlBP' , testProperty "foldl1" prop_foldl1BP , testProperty "foldl1'" prop_foldl1BP' , testProperty "foldr" prop_foldrBP , testProperty "foldr'" prop_foldrBP' , testProperty "foldr1" prop_foldr1BP , testProperty "foldr1'" prop_foldr1BP' , testProperty "mapAccumL" prop_mapAccumLBP -- , testProperty "mapAccumL" prop_mapAccumL_mapIndexedBP , testProperty "unfoldr" prop_unfoldrBP , testProperty "unfoldr 2" prop_unfoldr2BP , testProperty "unfoldr 2" prop_unfoldr2CP , testProperty "head" prop_headBP , testProperty "init" prop_initBP , testProperty "isPrefixOf" prop_isPrefixOfBP , testProperty "last" prop_lastBP , testProperty "length" prop_lengthBP , testProperty "readInt" prop_readIntBP , testProperty "lines" prop_linesBP , testProperty "lines \\n" prop_linesNLBP , testProperty "map" prop_mapBP , testProperty "maximum " prop_maximumBP , testProperty "minimum" prop_minimumBP , testProperty "null" prop_nullBP , testProperty "reverse" prop_reverseBP , testProperty "snoc" prop_snocBP , testProperty "tail" prop_tailBP , testProperty "scanl" prop_scanlBP , testProperty "transpose" prop_transposeBP , testProperty "replicate" prop_replicateBP , testProperty "take" prop_takeBP , testProperty "drop" prop_dropBP , testProperty "splitAt" prop_splitAtBP , testProperty "takeWhile" prop_takeWhileBP , testProperty "dropWhile" prop_dropWhileBP , testProperty "break" prop_breakBP , testProperty "span" prop_spanBP , testProperty "split" prop_splitBP , testProperty "count" prop_countBP , testProperty "group" prop_groupBP , testProperty "groupBy" prop_groupByBP , testProperty "inits" prop_initsBP , testProperty "tails" prop_tailsBP , testProperty "elem" prop_elemBP , testProperty "notElem" prop_notElemBP , testProperty "elemIndex" prop_elemIndexBP , testProperty "elemIndices" prop_elemIndicesBP , testProperty "intersperse" prop_intersperseBP , testProperty "concatMap" prop_concatMapBP ] ------------------------------------------------------------------------ -- ByteString <=> List pl_tests = [ testProperty "all" prop_allPL , testProperty "any" prop_anyPL , testProperty "append" prop_appendPL , testProperty "compare" prop_comparePL , testProperty "concat" prop_concatPL , testProperty "cons" prop_consPL , testProperty "eq" prop_eqPL , testProperty "filter" prop_filterPL , testProperty "filter rules"prop_filterPL_rule , testProperty "filter rules"prop_filterLC_rule , testProperty "partition" prop_partitionPL , testProperty "partition" prop_partitionLL , testProperty "find" prop_findPL , testProperty "findIndex" prop_findIndexPL , testProperty "findIndices" prop_findIndicesPL , testProperty "foldl" prop_foldlPL , testProperty "foldl'" prop_foldlPL' , testProperty "foldl1" prop_foldl1PL , testProperty "foldl1'" prop_foldl1PL' , testProperty "foldr1" prop_foldr1PL , testProperty "foldr" prop_foldrPL , testProperty "mapAccumL" prop_mapAccumLPL , testProperty "mapAccumR" prop_mapAccumRPL , testProperty "unfoldr" prop_unfoldrPL , testProperty "scanl" prop_scanlPL , testProperty "scanl1" prop_scanl1PL , testProperty "scanl1" prop_scanl1CL , testProperty "scanr" prop_scanrCL , testProperty "scanr" prop_scanrPL , testProperty "scanr1" prop_scanr1PL , testProperty "scanr1" prop_scanr1CL , testProperty "head" prop_headPL , testProperty "init" prop_initPL , testProperty "last" prop_lastPL , testProperty "maximum" prop_maximumPL , testProperty "minimum" prop_minimumPL , testProperty "tail" prop_tailPL , testProperty "zip" prop_zipPL , testProperty "zip" prop_zipLL , testProperty "zip" prop_zipCL , testProperty "unzip" prop_unzipPL , testProperty "unzip" prop_unzipLL , testProperty "unzip" prop_unzipCL , testProperty "zipWith" prop_zipWithPL -- , testProperty "zipWith" prop_zipWithCL , testProperty "zipWith rules" prop_zipWithPL_rules -- , testProperty "zipWith/zipWith'" prop_zipWithPL' , testProperty "isPrefixOf" prop_isPrefixOfPL , testProperty "isInfixOf" prop_isInfixOfPL , testProperty "length" prop_lengthPL , testProperty "map" prop_mapPL , testProperty "null" prop_nullPL , testProperty "reverse" prop_reversePL , testProperty "snoc" prop_snocPL , testProperty "transpose" prop_transposePL , testProperty "replicate" prop_replicatePL , testProperty "take" prop_takePL , testProperty "drop" prop_dropPL , testProperty "splitAt" prop_splitAtPL , testProperty "takeWhile" prop_takeWhilePL , testProperty "dropWhile" prop_dropWhilePL , testProperty "break" prop_breakPL , testProperty "span" prop_spanPL , testProperty "group" prop_groupPL , testProperty "groupBy" prop_groupByPL , testProperty "inits" prop_initsPL , testProperty "tails" prop_tailsPL , testProperty "elem" prop_elemPL , testProperty "notElem" prop_notElemPL , testProperty "lines" prop_linesPL , testProperty "elemIndex" prop_elemIndexPL , testProperty "elemIndex" prop_elemIndexCL , testProperty "elemIndices" prop_elemIndicesPL , testProperty "concatMap" prop_concatMapPL , testProperty "IsString" prop_isstring , testProperty "IsString LC" prop_isstring_lc ] ------------------------------------------------------------------------ -- extra ByteString properties bb_tests = [ testProperty "bijection" prop_bijectionBB , testProperty "bijection'" prop_bijectionBB' , testProperty "pack/unpack" prop_packunpackBB , testProperty "unpack/pack" prop_packunpackBB' , testProperty "eq 1" prop_eq1BB , testProperty "eq 2" prop_eq2BB , testProperty "eq 3" prop_eq3BB , testProperty "compare 1" prop_compare1BB , testProperty "compare 2" prop_compare2BB , testProperty "compare 3" prop_compare3BB , testProperty "compare 4" prop_compare4BB , testProperty "compare 5" prop_compare5BB , testProperty "compare 6" prop_compare6BB , testProperty "compare 7" prop_compare7BB , testProperty "compare 7" prop_compare7LL , testProperty "compare 8" prop_compare8BB , testProperty "empty 1" prop_nil1BB , testProperty "empty 2" prop_nil2BB , testProperty "empty 1 monoid" prop_nil1LL_monoid , testProperty "empty 2 monoid" prop_nil2LL_monoid , testProperty "empty 1 monoid" prop_nil1BB_monoid , testProperty "empty 2 monoid" prop_nil2BB_monoid , testProperty "null" prop_nullBB , testProperty "length 1" prop_lengthBB , testProperty "length 2" prop_lengthSBB , testProperty "cons 1" prop_consBB , testProperty "cons 2" prop_cons1BB , testProperty "cons 3" prop_cons2BB , testProperty "cons 4" prop_cons3BB , testProperty "cons 5" prop_cons4BB , testProperty "snoc" prop_snoc1BB , testProperty "head 1" prop_head1BB , testProperty "head 2" prop_head2BB , testProperty "head 3" prop_head3BB , testProperty "tail" prop_tailBB , testProperty "tail 1" prop_tail1BB , testProperty "last" prop_lastBB , testProperty "last 1" prop_last1BB , testProperty "init" prop_initBB , testProperty "init 1" prop_init1BB , testProperty "append 1" prop_append1BB , testProperty "append 2" prop_append2BB , testProperty "append 3" prop_append3BB , testProperty "mappend 1" prop_append1BB_monoid , testProperty "mappend 2" prop_append2BB_monoid , testProperty "mappend 3" prop_append3BB_monoid , testProperty "map 1" prop_map1BB , testProperty "map 2" prop_map2BB , testProperty "map 3" prop_map3BB , testProperty "filter1" prop_filter1BB , testProperty "filter2" prop_filter2BB , testProperty "map fusion" prop_mapfusionBB , testProperty "filter fusion" prop_filterfusionBB , testProperty "reverse 1" prop_reverse1BB , testProperty "reverse 2" prop_reverse2BB , testProperty "reverse 3" prop_reverse3BB , testProperty "foldl 1" prop_foldl1BB , testProperty "foldl 2" prop_foldl2BB , testProperty "foldr 1" prop_foldr1BB , testProperty "foldr 2" prop_foldr2BB , testProperty "foldl1 1" prop_foldl1_1BB , testProperty "foldl1 2" prop_foldl1_2BB , testProperty "foldl1 3" prop_foldl1_3BB , testProperty "foldr1 1" prop_foldr1_1BB , testProperty "foldr1 2" prop_foldr1_2BB , testProperty "foldr1 3" prop_foldr1_3BB , testProperty "scanl/foldl" prop_scanlfoldlBB , testProperty "all" prop_allBB , testProperty "any" prop_anyBB , testProperty "take" prop_takeBB , testProperty "drop" prop_dropBB , testProperty "takeWhile" prop_takeWhileBB , testProperty "dropWhile" prop_dropWhileBB , testProperty "dropWhile" prop_dropWhileCC_isSpace , testProperty "splitAt" prop_splitAtBB , testProperty "span" prop_spanBB , testProperty "break" prop_breakBB , testProperty "elem" prop_elemBB , testProperty "notElem" prop_notElemBB , testProperty "concat 1" prop_concat1BB , testProperty "concat 2" prop_concat2BB , testProperty "concat 3" prop_concatBB , testProperty "mconcat 1" prop_concat1BB_monoid , testProperty "mconcat 2" prop_concat2BB_monoid , testProperty "mconcat 3" prop_concatBB_monoid , testProperty "mconcat 1" prop_concat1LL_monoid , testProperty "mconcat 2" prop_concat2LL_monoid , testProperty "mconcat 3" prop_concatLL_monoid , testProperty "lines" prop_linesBB , testProperty "unlines" prop_unlinesBB , testProperty "unlines" prop_unlinesLC , testProperty "words" prop_wordsBB , testProperty "words" prop_wordsLC , testProperty "unwords" prop_unwordsBB , testProperty "group" prop_groupBB , testProperty "groupBy 0" prop_groupByBB , testProperty "groupBy 1" prop_groupBy1CC , testProperty "groupBy 2" prop_groupBy1BB , testProperty "groupBy 3" prop_groupBy2CC , testProperty "join" prop_joinBB , testProperty "elemIndex 1" prop_elemIndex1BB , testProperty "elemIndex 2" prop_elemIndex2BB , testProperty "findIndex" prop_findIndexBB , testProperty "findIndicies" prop_findIndiciesBB , testProperty "elemIndices" prop_elemIndicesBB , testProperty "find" prop_findBB , testProperty "find/findIndex" prop_find_findIndexBB , testProperty "sort 1" prop_sort1BB , testProperty "sort 2" prop_sort2BB , testProperty "sort 3" prop_sort3BB , testProperty "sort 4" prop_sort4BB , testProperty "sort 5" prop_sort5BB , testProperty "intersperse" prop_intersperseBB , testProperty "maximum" prop_maximumBB , testProperty "minimum" prop_minimumBB -- , testProperty "breakChar" prop_breakCharBB -- , testProperty "spanChar 1" prop_spanCharBB -- , testProperty "spanChar 2" prop_spanChar_1BB -- , testProperty "breakSpace" prop_breakSpaceBB -- , testProperty "dropSpace" prop_dropSpaceBB , testProperty "spanEnd" prop_spanEndBB , testProperty "breakEnd" prop_breakEndBB , testProperty "breakEnd" prop_breakEndCC , testProperty "elemIndexEnd 1" prop_elemIndexEnd1BB , testProperty "elemIndexEnd 1" prop_elemIndexEnd1CC , testProperty "elemIndexEnd 2" prop_elemIndexEnd2BB -- , testProperty "words'" prop_wordsBB' -- , testProperty "lines'" prop_linesBB' -- , testProperty "dropSpaceEnd" prop_dropSpaceEndBB , testProperty "unfoldr" prop_unfoldrBB , testProperty "prefix" prop_prefixBB , testProperty "suffix" prop_suffixBB , testProperty "suffix" prop_suffixLL , testProperty "copy" prop_copyBB , testProperty "copy" prop_copyLL , testProperty "inits" prop_initsBB , testProperty "tails" prop_tailsBB , testProperty "findSubstrings "prop_findSubstringsBB , testProperty "findSubstring "prop_findSubstringBB , testProperty "breakSubstring 1"prop_breakSubstringBB , testProperty "breakSubstring 2"prop_breakSubstring_findSubstring , testProperty "breakSubstring 3"prop_breakSubstring_isInfixOf , testProperty "replicate1" prop_replicate1BB , testProperty "replicate2" prop_replicate2BB , testProperty "replicate3" prop_replicate3BB , testProperty "readInt" prop_readintBB , testProperty "readInt 2" prop_readint2BB , testProperty "readInteger" prop_readintegerBB , testProperty "readInteger 2" prop_readinteger2BB , testProperty "read" prop_readLL , testProperty "read" prop_readBB , testProperty "Lazy.readInt" prop_readintLL , testProperty "Lazy.readInt" prop_readintLL , testProperty "Lazy.readInteger" prop_readintegerLL , testProperty "mconcat 1" prop_append1LL_monoid , testProperty "mconcat 2" prop_append2LL_monoid , testProperty "mconcat 3" prop_append3LL_monoid -- , testProperty "filterChar1" prop_filterChar1BB -- , testProperty "filterChar2" prop_filterChar2BB -- , testProperty "filterChar3" prop_filterChar3BB -- , testProperty "filterNotChar1" prop_filterNotChar1BB -- , testProperty "filterNotChar2" prop_filterNotChar2BB , testProperty "tail" prop_tailSBB , testProperty "index" prop_indexBB , testProperty "unsafeIndex" prop_unsafeIndexBB -- , testProperty "map'" prop_mapBB' , testProperty "filter" prop_filterBB , testProperty "elem" prop_elemSBB , testProperty "take" prop_takeSBB , testProperty "drop" prop_dropSBB , testProperty "splitAt" prop_splitAtSBB , testProperty "foldl" prop_foldlBB , testProperty "foldr" prop_foldrBB , testProperty "takeWhile " prop_takeWhileSBB , testProperty "dropWhile " prop_dropWhileSBB , testProperty "span " prop_spanSBB , testProperty "break " prop_breakSBB , testProperty "breakspan" prop_breakspan_1BB , testProperty "lines " prop_linesSBB , testProperty "unlines " prop_unlinesSBB , testProperty "words " prop_wordsSBB , testProperty "unwords " prop_unwordsSBB , testProperty "unwords " prop_unwordsSLC -- , testProperty "wordstokens" prop_wordstokensBB , testProperty "splitWith" prop_splitWithBB , testProperty "joinsplit" prop_joinsplitBB , testProperty "intercalate" prop_intercalatePL -- , testProperty "lineIndices" prop_lineIndices1BB , testProperty "count" prop_countBB -- , testProperty "linessplit" prop_linessplit2BB , testProperty "splitsplitWith" prop_splitsplitWithBB -- , testProperty "joinjoinpath" prop_joinjoinpathBB , testProperty "zip" prop_zipBB , testProperty "zip" prop_zipLC , testProperty "zip1" prop_zip1BB , testProperty "zipWith" prop_zipWithBB , testProperty "zipWith" prop_zipWithCC , testProperty "zipWith" prop_zipWithLC -- , testProperty "zipWith'" prop_zipWith'BB , testProperty "unzip" prop_unzipBB , testProperty "concatMap" prop_concatMapBB -- , testProperty "join/joinByte" prop_join_spec -- , testProperty "span/spanByte" prop_span_spec -- , testProperty "break/breakByte"prop_break_spec ] ------------------------------------------------------------------------ -- Fusion rules {- fusion_tests = -- v1 fusion [ ("lazy loop/loop fusion" prop_lazylooploop , ("loop/loop fusion" prop_looploop -- v2 fusion , testProperty "loop/loop wrapper elim" prop_loop_loop_wrapper_elimination , testProperty "sequence association" prop_sequenceloops_assoc , testProperty "up/up loop fusion" prop_up_up_loop_fusion , testProperty "down/down loop fusion" prop_down_down_loop_fusion , testProperty "noAcc/noAcc loop fusion" prop_noAcc_noAcc_loop_fusion , testProperty "noAcc/up loop fusion" prop_noAcc_up_loop_fusion , testProperty "up/noAcc loop fusion" prop_up_noAcc_loop_fusion , testProperty "noAcc/down loop fusion" prop_noAcc_down_loop_fusion , testProperty "down/noAcc loop fusion" prop_down_noAcc_loop_fusion , testProperty "map/map loop fusion" prop_map_map_loop_fusion , testProperty "filter/filter loop fusion" prop_filter_filter_loop_fusion , testProperty "map/filter loop fusion" prop_map_filter_loop_fusion , testProperty "filter/map loop fusion" prop_filter_map_loop_fusion , testProperty "map/noAcc loop fusion" prop_map_noAcc_loop_fusion , testProperty "noAcc/map loop fusion" prop_noAcc_map_loop_fusion , testProperty "map/up loop fusion" prop_map_up_loop_fusion , testProperty "up/map loop fusion" prop_up_map_loop_fusion , testProperty "map/down loop fusion" prop_map_down_fusion , testProperty "down/map loop fusion" prop_down_map_loop_fusion , testProperty "filter/noAcc loop fusion" prop_filter_noAcc_loop_fusion , testProperty "noAcc/filter loop fusion" prop_noAcc_filter_loop_fusion , testProperty "filter/up loop fusion" prop_filter_up_loop_fusion , testProperty "up/filter loop fusion" prop_up_filter_loop_fusion , testProperty "filter/down loop fusion" prop_filter_down_fusion , testProperty "down/filter loop fusion" prop_down_filter_loop_fusion {- , testProperty "length/loop fusion" prop_length_loop_fusion_1 , testProperty "length/loop fusion" prop_length_loop_fusion_2 , testProperty "length/loop fusion" prop_length_loop_fusion_3 , testProperty "length/loop fusion" prop_length_loop_fusion_4 -} -- , testProperty "zipwith/spec" prop_zipwith_spec ] -} ------------------------------------------------------------------------ -- Extra lazy properties ll_tests = [ testProperty "eq 1" prop_eq1 , testProperty "eq 2" prop_eq2 , testProperty "eq 3" prop_eq3 , testProperty "eq refl" prop_eq_refl , testProperty "eq symm" prop_eq_symm , testProperty "compare 1" prop_compare1 , testProperty "compare 2" prop_compare2 , testProperty "compare 3" prop_compare3 , testProperty "compare 4" prop_compare4 , testProperty "compare 5" prop_compare5 , testProperty "compare 6" prop_compare6 , testProperty "compare 7" prop_compare7 , testProperty "compare 8" prop_compare8 , testProperty "empty 1" prop_empty1 , testProperty "empty 2" prop_empty2 , testProperty "pack/unpack" prop_packunpack , testProperty "unpack/pack" prop_unpackpack , testProperty "null" prop_null , testProperty "length 1" prop_length1 , testProperty "length 2" prop_length2 , testProperty "cons 1" prop_cons1 , testProperty "cons 2" prop_cons2 , testProperty "cons 3" prop_cons3 , testProperty "cons 4" prop_cons4 , testProperty "snoc" prop_snoc1 , testProperty "head/pack" prop_head , testProperty "head/unpack" prop_head1 , testProperty "tail/pack" prop_tail , testProperty "tail/unpack" prop_tail1 , testProperty "last" prop_last , testProperty "init" prop_init , testProperty "append 1" prop_append1 , testProperty "append 2" prop_append2 , testProperty "append 3" prop_append3 , testProperty "map 1" prop_map1 , testProperty "map 2" prop_map2 , testProperty "map 3" prop_map3 , testProperty "filter 1" prop_filter1 , testProperty "filter 2" prop_filter2 , testProperty "reverse" prop_reverse , testProperty "reverse1" prop_reverse1 , testProperty "reverse2" prop_reverse2 , testProperty "transpose" prop_transpose , testProperty "foldl" prop_foldl , testProperty "foldl/reverse" prop_foldl_1 , testProperty "foldr" prop_foldr , testProperty "foldr/id" prop_foldr_1 , testProperty "foldl1/foldl" prop_foldl1_1 , testProperty "foldl1/head" prop_foldl1_2 , testProperty "foldl1/tail" prop_foldl1_3 , testProperty "foldr1/foldr" prop_foldr1_1 , testProperty "foldr1/last" prop_foldr1_2 , testProperty "foldr1/head" prop_foldr1_3 , testProperty "concat 1" prop_concat1 , testProperty "concat 2" prop_concat2 , testProperty "concat/pack" prop_concat3 , testProperty "any" prop_any , testProperty "all" prop_all , testProperty "maximum" prop_maximum , testProperty "minimum" prop_minimum , testProperty "replicate 1" prop_replicate1 , testProperty "replicate 2" prop_replicate2 , testProperty "take" prop_take1 , testProperty "drop" prop_drop1 , testProperty "splitAt" prop_drop1 , testProperty "takeWhile" prop_takeWhile , testProperty "dropWhile" prop_dropWhile , testProperty "break" prop_break , testProperty "span" prop_span , testProperty "splitAt" prop_splitAt , testProperty "break/span" prop_breakspan -- , testProperty "break/breakByte" prop_breakByte -- , testProperty "span/spanByte" prop_spanByte , testProperty "split" prop_split , testProperty "splitWith" prop_splitWith , testProperty "splitWith" prop_splitWith_D , testProperty "splitWith" prop_splitWith_C , testProperty "join.split/id" prop_joinsplit -- , testProperty "join/joinByte" prop_joinjoinByte , testProperty "group" prop_group , testProperty "groupBy" prop_groupBy , testProperty "groupBy" prop_groupBy_LC , testProperty "index" prop_index , testProperty "index" prop_index_D , testProperty "index" prop_index_C , testProperty "elemIndex" prop_elemIndex , testProperty "elemIndices" prop_elemIndices , testProperty "count/elemIndices" prop_count , testProperty "findIndex" prop_findIndex , testProperty "findIndices" prop_findIndicies , testProperty "find" prop_find , testProperty "find/findIndex" prop_find_findIndex , testProperty "elem" prop_elem , testProperty "notElem" prop_notElem , testProperty "elem/notElem" prop_elem_notelem -- , testProperty "filterByte 1" prop_filterByte -- , testProperty "filterByte 2" prop_filterByte2 -- , testProperty "filterNotByte 1" prop_filterNotByte -- , testProperty "filterNotByte 2" prop_filterNotByte2 , testProperty "isPrefixOf" prop_isPrefixOf , testProperty "concatMap" prop_concatMap , testProperty "isSpace" prop_isSpaceWord8 ]
markflorisson/hpack
testrepo/bytestring-0.10.4.1/tests/Properties.hs
bsd-3-clause
111,015
4
22
30,767
33,390
17,559
15,831
1,764
3
{-# LANGUAGE CPP #-} #ifdef __GLASGOW_HASKELL__ {-# LANGUAGE Safe #-} #endif ----------------------------------------------------------------------------- -- | -- Module : System.Posix -- Copyright : (c) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (requires POSIX) -- -- POSIX support -- ----------------------------------------------------------------------------- module System.Posix ( module System.Posix.Types, module System.Posix.Signals, module System.Posix.Directory, module System.Posix.Files, module System.Posix.Unistd, module System.Posix.IO, module System.Posix.Env, module System.Posix.Process, module System.Posix.Temp, module System.Posix.Terminal, module System.Posix.Time, module System.Posix.User, module System.Posix.Resource, module System.Posix.Semaphore, module System.Posix.SharedMem, module System.Posix.DynamicLinker, -- XXX 'Module' type clashes with GHC -- module System.Posix.DynamicLinker.Module ) where import System.Posix.Types import System.Posix.Signals import System.Posix.Directory import System.Posix.Files import System.Posix.Unistd import System.Posix.Process import System.Posix.IO import System.Posix.Env import System.Posix.Temp import System.Posix.Terminal import System.Posix.Time import System.Posix.User import System.Posix.Resource import System.Posix.Semaphore import System.Posix.SharedMem -- XXX: bad planning, we have two constructors called "Default" import System.Posix.DynamicLinker hiding (Default) --import System.Posix.DynamicLinker.Module {- TODO Here we detail our support for the IEEE Std 1003.1-2001 standard. For each header file defined by the standard, we categorise its functionality as - "supported" Full equivalent functionality is provided by the specified Haskell module. - "unsupported" (functionality not provided by a Haskell module) The functionality is not currently provided. - "to be supported" Currently unsupported, but support is planned for the future. Exceptions are listed where appropriate. Interfaces supported -------------------- unix package: dirent.h System.Posix.Directory dlfcn.h System.Posix.DynamicLinker errno.h Foreign.C.Error fcntl.h System.Posix.IO signal.h System.Posix.Signals sys/stat.h System.Posix.Files sys/times.h System.Posix.Process sys/types.h System.Posix.Types (with exceptions...) sys/utsname.h System.Posix.Unistd sys/wait.h System.Posix.Process termios.h System.Posix.Terminal (check exceptions) unistd.h System.Posix.* utime.h System.Posix.Files pwd.h System.Posix.User grp.h System.Posix.User stdlib.h: System.Posix.Env (getenv()/setenv()/unsetenv()) System.Posix.Temp (mkstemp()) sys/resource.h: System.Posix.Resource (get/setrlimit() only) regex-posix package: regex.h Text.Regex.Posix network package: arpa/inet.h net/if.h netinet/in.h netinet/tcp.h sys/socket.h sys/un.h To be supported --------------- limits.h (pathconf()/fpathconf() already done) poll.h sys/resource.h (getrusage(): use instead of times() for getProcessTimes?) sys/select.h sys/statvfs.h (?) sys/time.h (but maybe not the itimer?) time.h (System.Posix.Time) stdio.h (popen only: System.Posix.IO) sys/mman.h Unsupported interfaces ---------------------- aio.h assert.h complex.h cpio.h ctype.h fenv.h float.h fmtmsg.h fnmatch.h ftw.h glob.h iconv.h inttypes.h iso646.h langinfo.h libgen.h locale.h (see System.Locale) math.h monetary.h mqueue.h ndbm.h netdb.h nl_types.h pthread.h sched.h search.h semaphore.h setjmp.h spawn.h stdarg.h stdbool.h stddef.h stdint.h stdio.h except: popen() stdlib.h except: exit(): System.Posix.Process free()/malloc(): Foreign.Marshal.Alloc getenv()/setenv(): ?? System.Environment rand() etc.: System.Random string.h strings.h stropts.h sys/ipc.h sys/msg.h sys/sem.h sys/shm.h sys/timeb.h sys/uio.h syslog.h tar.h tgmath.h trace.h ucontext.h ulimit.h utmpx.h wchar.h wctype.h wordexp.h -}
DavidAlphaFox/ghc
libraries/unix/System/Posix.hs
bsd-3-clause
4,079
0
5
512
245
176
69
34
0
<?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>Passive Scan Rules | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Søg</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/pscanrules/src/main/javahelp/org/zaproxy/zap/extension/pscanrules/resources/help_da_DK/helpset_da_DK.hs
apache-2.0
977
78
66
160
418
211
207
-1
-1
{-# LANGUAGE FlexibleInstances, GeneralizedNewtypeDeriving #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main (main) where import Data.Hashable (Hashable(hashWithSalt)) import Test.ChasingBottoms.IsBottom import Test.Framework (Test, defaultMain, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck (Arbitrary(arbitrary)) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM -- Key type that generates more hash collisions. newtype Key = K { unK :: Int } deriving (Arbitrary, Eq, Ord, Show) instance Hashable Key where hashWithSalt salt k = hashWithSalt salt (unK k) `mod` 20 instance (Arbitrary k, Arbitrary v, Eq k, Hashable k) => Arbitrary (HashMap k v) where arbitrary = HM.fromList `fmap` arbitrary instance Show (Int -> Int) where show _ = "<function>" instance Show (Int -> Int -> Int) where show _ = "<function>" ------------------------------------------------------------------------ -- * Properties ------------------------------------------------------------------------ -- ** Strict module pSingletonKeyStrict :: Int -> Bool pSingletonKeyStrict v = isBottom $ HM.singleton (bottom :: Key) v pSingletonValueStrict :: Key -> Bool pSingletonValueStrict k = isBottom $ (HM.singleton k (bottom :: Int)) pLookupDefaultKeyStrict :: Int -> HashMap Key Int -> Bool pLookupDefaultKeyStrict def m = isBottom $ HM.lookupDefault def bottom m pAdjustKeyStrict :: (Int -> Int) -> HashMap Key Int -> Bool pAdjustKeyStrict f m = isBottom $ HM.adjust f bottom m pAdjustValueStrict :: Key -> HashMap Key Int -> Bool pAdjustValueStrict k m | k `HM.member` m = isBottom $ HM.adjust (const bottom) k m | otherwise = case HM.keys m of [] -> True (k':_) -> isBottom $ HM.adjust (const bottom) k' m pInsertKeyStrict :: Int -> HashMap Key Int -> Bool pInsertKeyStrict v m = isBottom $ HM.insert bottom v m pInsertValueStrict :: Key -> HashMap Key Int -> Bool pInsertValueStrict k m = isBottom $ HM.insert k bottom m pInsertWithKeyStrict :: (Int -> Int -> Int) -> Int -> HashMap Key Int -> Bool pInsertWithKeyStrict f v m = isBottom $ HM.insertWith f bottom v m pInsertWithValueStrict :: (Int -> Int -> Int) -> Key -> Int -> HashMap Key Int -> Bool pInsertWithValueStrict f k v m | HM.member k m = isBottom $ HM.insertWith (const2 bottom) k v m | otherwise = isBottom $ HM.insertWith f k bottom m pFromListKeyStrict :: Bool pFromListKeyStrict = isBottom $ HM.fromList [(undefined :: Key, 1 :: Int)] pFromListValueStrict :: Bool pFromListValueStrict = isBottom $ HM.fromList [(K 1, undefined)] pFromListWithKeyStrict :: (Int -> Int -> Int) -> Bool pFromListWithKeyStrict f = isBottom $ HM.fromListWith f [(undefined :: Key, 1 :: Int)] pFromListWithValueStrict :: [(Key, Int)] -> Bool pFromListWithValueStrict xs = case xs of [] -> True (x:_) -> isBottom $ HM.fromListWith (\ _ _ -> undefined) (x:xs) ------------------------------------------------------------------------ -- * Test list tests :: [Test] tests = [ -- Basic interface testGroup "HashMap.Strict" [ testProperty "singleton is key-strict" pSingletonKeyStrict , testProperty "singleton is value-strict" pSingletonValueStrict , testProperty "member is key-strict" $ keyStrict HM.member , testProperty "lookup is key-strict" $ keyStrict HM.lookup , testProperty "lookupDefault is key-strict" pLookupDefaultKeyStrict , testProperty "! is key-strict" $ keyStrict (flip (HM.!)) , testProperty "delete is key-strict" $ keyStrict HM.delete , testProperty "adjust is key-strict" pAdjustKeyStrict , testProperty "adjust is value-strict" pAdjustValueStrict , testProperty "insert is key-strict" pInsertKeyStrict , testProperty "insert is value-strict" pInsertValueStrict , testProperty "insertWith is key-strict" pInsertWithKeyStrict , testProperty "insertWith is value-strict" pInsertWithValueStrict , testProperty "fromList is key-strict" pFromListKeyStrict , testProperty "fromList is value-strict" pFromListValueStrict , testProperty "fromListWith is key-strict" pFromListWithKeyStrict , testProperty "fromListWith is value-strict" pFromListWithValueStrict ] ] ------------------------------------------------------------------------ -- * Test harness main :: IO () main = defaultMain tests ------------------------------------------------------------------------ -- * Utilities keyStrict :: (Key -> HashMap Key Int -> a) -> HashMap Key Int -> Bool keyStrict f m = isBottom $ f bottom m const2 :: a -> b -> c -> a const2 x _ _ = x
pacak/cuddly-bassoon
unordered-containers-0.2.8.0/tests/Strictness.hs
bsd-3-clause
4,716
0
12
879
1,299
686
613
84
2
module Test where import RIO {-@ LIQUID "--no-termination" @-} {-@ measure counter1 :: World -> Int @-} {-@ measure counter2 :: World -> Int @-} {-@ incr :: RIO <{\x -> true}, {\w1 x w2 -> x = 5}> Int @-} incr :: RIO Int incr = undefined {-@ incr' :: RIO <{\x -> true}, {\w1 x w2 -> x = 5}> Int @-} incr' :: RIO Int incr' = incr >>= return {-@ return5 :: x:{v:Int | v = 5} -> RIO <{\y -> true}, {\w1 y w2 -> y = 5}> Int @-} return5 :: Int -> RIO Int return5 = undefined
mightymoose/liquidhaskell
benchmarks/icfp15/pos/TestM.hs
bsd-3-clause
487
0
6
121
60
36
24
8
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , MagicHash , UnboxedTuples , ScopedTypeVariables , RankNTypes #-} {-# OPTIONS_GHC -Wno-deprecations #-} -- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN -- and Control.Concurrent.SampleVar imports. ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (concurrency) -- -- A common interface to a collection of useful concurrency -- abstractions. -- ----------------------------------------------------------------------------- module Control.Concurrent ( -- * Concurrent Haskell -- $conc_intro -- * Basic concurrency operations ThreadId, myThreadId, forkIO, forkFinally, forkIOWithUnmask, killThread, throwTo, -- ** Threads with affinity forkOn, forkOnWithUnmask, getNumCapabilities, setNumCapabilities, threadCapability, -- * Scheduling -- $conc_scheduling yield, -- ** Blocking -- $blocking -- ** Waiting threadDelay, threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM, -- * Communication abstractions module Control.Concurrent.MVar, module Control.Concurrent.Chan, module Control.Concurrent.QSem, module Control.Concurrent.QSemN, -- * Bound Threads -- $boundthreads rtsSupportsBoundThreads, forkOS, forkOSWithUnmask, isCurrentThreadBound, runInBoundThread, runInUnboundThread, -- * Weak references to ThreadIds mkWeakThreadId, -- * GHC's implementation of concurrency -- |This section describes features specific to GHC's -- implementation of Concurrent Haskell. -- ** Haskell threads and Operating System threads -- $osthreads -- ** Terminating the program -- $termination -- ** Pre-emption -- $preemption -- ** Deadlock -- $deadlock ) where import Control.Exception.Base as Exception import GHC.Conc hiding (threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM) import GHC.IO ( unsafeUnmask, catchException ) import GHC.IORef ( newIORef, readIORef, writeIORef ) import GHC.Base import System.Posix.Types ( Fd ) import Foreign.StablePtr import Foreign.C.Types #if defined(mingw32_HOST_OS) import Foreign.C import System.IO import Data.Functor ( void ) import Data.Int ( Int64 ) #else import qualified GHC.Conc #endif import Control.Concurrent.MVar import Control.Concurrent.Chan import Control.Concurrent.QSem import Control.Concurrent.QSemN {- $conc_intro The concurrency extension for Haskell is described in the paper /Concurrent Haskell/ <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>. Concurrency is \"lightweight\", which means that both thread creation and context switching overheads are extremely low. Scheduling of Haskell threads is done internally in the Haskell runtime system, and doesn't make use of any operating system-supplied thread packages. However, if you want to interact with a foreign library that expects your program to use the operating system-supplied thread package, you can do so by using 'forkOS' instead of 'forkIO'. Haskell threads can communicate via 'MVar's, a kind of synchronised mutable variable (see "Control.Concurrent.MVar"). Several common concurrency abstractions can be built from 'MVar's, and these are provided by the "Control.Concurrent" library. In GHC, threads may also communicate via exceptions. -} {- $conc_scheduling Scheduling may be either pre-emptive or co-operative, depending on the implementation of Concurrent Haskell (see below for information related to specific compilers). In a co-operative system, context switches only occur when you use one of the primitives defined in this module. This means that programs such as: > main = forkIO (write 'a') >> write 'b' > where write c = putChar c >> write c will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@, instead of some random interleaving of @a@s and @b@s. In practice, cooperative multitasking is sufficient for writing simple graphical user interfaces. -} {- $blocking Different Haskell implementations have different characteristics with regard to which operations block /all/ threads. Using GHC without the @-threaded@ option, all foreign calls will block all other Haskell threads in the system, although I\/O operations will not. With the @-threaded@ option, only foreign calls with the @unsafe@ attribute will block all other threads. -} -- | Fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- -- > forkFinally action and_then = -- > mask $ \restore -> -- > forkIO $ try (restore action) >>= and_then -- -- This function is useful for informing the parent when a child -- terminates, for example. -- -- @since 4.6.0.0 forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action and_then = mask $ \restore -> forkIO $ try (restore action) >>= and_then -- --------------------------------------------------------------------------- -- Bound Threads {- $boundthreads #boundthreads# Support for multiple operating system threads and bound threads as described below is currently only available in the GHC runtime system if you use the /-threaded/ option when linking. Other Haskell systems do not currently support multiple operating system threads. A bound thread is a haskell thread that is /bound/ to an operating system thread. While the bound thread is still scheduled by the Haskell run-time system, the operating system thread takes care of all the foreign calls made by the bound thread. To a foreign library, the bound thread will look exactly like an ordinary operating system thread created using OS functions like @pthread_create@ or @CreateThread@. Bound threads can be created using the 'forkOS' function below. All foreign exported functions are run in a bound thread (bound to the OS thread that called the function). Also, the @main@ action of every Haskell program is run in a bound thread. Why do we need this? Because if a foreign library is called from a thread created using 'forkIO', it won't have access to any /thread-local state/ - state variables that have specific values for each OS thread (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some libraries (OpenGL, for example) will not work from a thread created using 'forkIO'. They work fine in threads created using 'forkOS' or when called from @main@ or from a @foreign export@. In terms of performance, 'forkOS' (aka bound) threads are much more expensive than 'forkIO' (aka unbound) threads, because a 'forkOS' thread is tied to a particular OS thread, whereas a 'forkIO' thread can be run by any OS thread. Context-switching between a 'forkOS' thread and a 'forkIO' thread is many times more expensive than between two 'forkIO' threads. Note in particular that the main program thread (the thread running @Main.main@) is always a bound thread, so for good concurrency performance you should ensure that the main thread is not doing repeated communication with other threads in the system. Typically this means forking subthreads to do the work using 'forkIO', and waiting for the results in the main thread. -} -- | 'True' if bound threads are supported. -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound' -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will -- fail. foreign import ccall unsafe rtsSupportsBoundThreads :: Bool {- | Like 'forkIO', this sparks off a new thread to run the 'IO' computation passed as the first argument, and returns the 'ThreadId' of the newly created thread. However, 'forkOS' creates a /bound/ thread, which is necessary if you need to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads"). Using 'forkOS' instead of 'forkIO' makes no difference at all to the scheduling behaviour of the Haskell runtime system. It is a common misconception that you need to use 'forkOS' instead of 'forkIO' to avoid blocking all the Haskell threads when making a foreign call; this isn't the case. To allow foreign calls to be made without blocking all the Haskell threads (with GHC), it is only necessary to use the @-threaded@ option when linking your program, and to make sure the foreign import is not marked @unsafe@. -} forkOS :: IO () -> IO ThreadId foreign export ccall forkOS_entry :: StablePtr (IO ()) -> IO () foreign import ccall "forkOS_entry" forkOS_entry_reimported :: StablePtr (IO ()) -> IO () forkOS_entry :: StablePtr (IO ()) -> IO () forkOS_entry stableAction = do action <- deRefStablePtr stableAction action foreign import ccall forkOS_createThread :: StablePtr (IO ()) -> IO CInt failNonThreaded :: IO a failNonThreaded = fail $ "RTS doesn't support multiple OS threads " ++"(use ghc -threaded when linking)" forkOS action0 | rtsSupportsBoundThreads = do mv <- newEmptyMVar b <- Exception.getMaskingState let -- async exceptions are masked in the child if they are masked -- in the parent, as for forkIO (see #1048). forkOS_createThread -- creates a thread with exceptions masked by default. action1 = case b of Unmasked -> unsafeUnmask action0 MaskedInterruptible -> action0 MaskedUninterruptible -> uninterruptibleMask_ action0 action_plus = catch action1 childHandler entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus) err <- forkOS_createThread entry when (err /= 0) $ fail "Cannot create OS thread." tid <- takeMVar mv freeStablePtr entry return tid | otherwise = failNonThreaded -- | Like 'forkIOWithUnmask', but the child thread is a bound thread, -- as with 'forkOS'. forkOSWithUnmask :: ((forall a . IO a -> IO a) -> IO ()) -> IO ThreadId forkOSWithUnmask io = forkOS (io unsafeUnmask) -- | Returns 'True' if the calling thread is /bound/, that is, if it is -- safe to use foreign libraries that rely on thread-local state from the -- calling thread. isCurrentThreadBound :: IO Bool isCurrentThreadBound = IO $ \ s# -> case isCurrentThreadBound# s# of (# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #) {- | Run the 'IO' computation passed as the first argument. If the calling thread is not /bound/, a bound thread is created temporarily. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. You can wrap a series of foreign function calls that rely on thread-local state with @runInBoundThread@ so that you can use them without knowing whether the current thread is /bound/. -} runInBoundThread :: IO a -> IO a runInBoundThread action | rtsSupportsBoundThreads = do bound <- isCurrentThreadBound if bound then action else do ref <- newIORef undefined let action_plus = Exception.try action >>= writeIORef ref bracket (newStablePtr action_plus) freeStablePtr (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>= unsafeResult | otherwise = failNonThreaded {- | Run the 'IO' computation passed as the first argument. If the calling thread is /bound/, an unbound thread is created temporarily using 'forkIO'. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. Use this function /only/ in the rare case that you have actually observed a performance loss due to the use of bound threads. A program that doesn't need its main thread to be bound and makes /heavy/ use of concurrency (e.g. a web server), might want to wrap its @main@ action in @runInUnboundThread@. Note that exceptions which are thrown to the current thread are thrown in turn to the thread that is executing the given computation. This ensures there's always a way of killing the forked thread. -} runInUnboundThread :: IO a -> IO a runInUnboundThread action = do bound <- isCurrentThreadBound if bound then do mv <- newEmptyMVar mask $ \restore -> do tid <- forkIO $ Exception.try (restore action) >>= putMVar mv let wait = takeMVar mv `catchException` \(e :: SomeException) -> Exception.throwTo tid e >> wait wait >>= unsafeResult else action unsafeResult :: Either SomeException a -> IO a unsafeResult = either Exception.throwIO return -- --------------------------------------------------------------------------- -- threadWaitRead/threadWaitWrite -- | Block the current thread until data is available to read on the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitRead', use -- 'GHC.Conc.closeFdWith'. threadWaitRead :: Fd -> IO () threadWaitRead fd #if defined(mingw32_HOST_OS) -- we have no IO manager implementing threadWaitRead on Windows. -- fdReady does the right thing, but we have to call it in a -- separate thread, otherwise threadWaitRead won't be interruptible, -- and this only works with -threaded. | threaded = withThread (waitFd fd False) | otherwise = case fd of 0 -> do _ <- hWaitForInput stdin (-1) return () -- hWaitForInput does work properly, but we can only -- do this for stdin since we know its FD. _ -> errorWithoutStackTrace "threadWaitRead requires -threaded on Windows, or use System.IO.hWaitForInput" #else = GHC.Conc.threadWaitRead fd #endif -- | Block the current thread until data can be written to the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitWrite', use -- 'GHC.Conc.closeFdWith'. threadWaitWrite :: Fd -> IO () threadWaitWrite fd #if defined(mingw32_HOST_OS) | threaded = withThread (waitFd fd True) | otherwise = errorWithoutStackTrace "threadWaitWrite requires -threaded on Windows" #else = GHC.Conc.threadWaitWrite fd #endif -- | Returns an STM action that can be used to wait for data -- to read from a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitReadSTM :: Fd -> IO (STM (), IO ()) threadWaitReadSTM fd #if defined(mingw32_HOST_OS) | threaded = do v <- newTVarIO Nothing mask_ $ void $ forkIO $ do result <- try (waitFd fd False) atomically (writeTVar v $ Just result) let waitAction = do result <- readTVar v case result of Nothing -> retry Just (Right ()) -> return () Just (Left e) -> throwSTM (e :: IOException) let killAction = return () return (waitAction, killAction) | otherwise = errorWithoutStackTrace "threadWaitReadSTM requires -threaded on Windows" #else = GHC.Conc.threadWaitReadSTM fd #endif -- | Returns an STM action that can be used to wait until data -- can be written to a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitWriteSTM :: Fd -> IO (STM (), IO ()) threadWaitWriteSTM fd #if defined(mingw32_HOST_OS) | threaded = do v <- newTVarIO Nothing mask_ $ void $ forkIO $ do result <- try (waitFd fd True) atomically (writeTVar v $ Just result) let waitAction = do result <- readTVar v case result of Nothing -> retry Just (Right ()) -> return () Just (Left e) -> throwSTM (e :: IOException) let killAction = return () return (waitAction, killAction) | otherwise = errorWithoutStackTrace "threadWaitWriteSTM requires -threaded on Windows" #else = GHC.Conc.threadWaitWriteSTM fd #endif #if defined(mingw32_HOST_OS) foreign import ccall unsafe "rtsSupportsBoundThreads" threaded :: Bool withThread :: IO a -> IO a withThread io = do m <- newEmptyMVar _ <- mask_ $ forkIO $ try io >>= putMVar m x <- takeMVar m case x of Right a -> return a Left e -> throwIO (e :: IOException) waitFd :: Fd -> Bool -> IO () waitFd fd write = do throwErrnoIfMinus1_ "fdReady" $ fdReady (fromIntegral fd) (if write then 1 else 0) (-1) 0 foreign import ccall safe "fdReady" fdReady :: CInt -> CBool -> Int64 -> CBool -> IO CInt #endif -- --------------------------------------------------------------------------- -- More docs {- $osthreads #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and are managed entirely by the GHC runtime. Typically Haskell threads are an order of magnitude or two more efficient (in terms of both time and space) than operating system threads. The downside of having lightweight threads is that only one can run at a time, so if one thread blocks in a foreign call, for example, the other threads cannot continue. The GHC runtime works around this by making use of full OS threads where necessary. When the program is built with the @-threaded@ option (to link against the multithreaded version of the runtime), a thread making a @safe@ foreign call will not block the other threads in the system; another OS thread will take over running Haskell threads until the original call returns. The runtime maintains a pool of these /worker/ threads so that multiple Haskell threads can be involved in external calls simultaneously. The "System.IO" library manages multiplexing in its own way. On Windows systems it uses @safe@ foreign calls to ensure that threads doing I\/O operations don't block the whole runtime, whereas on Unix systems all the currently blocked I\/O requests are managed by a single thread (the /IO manager thread/) using a mechanism such as @epoll@ or @kqueue@, depending on what is provided by the host operating system. The runtime will run a Haskell thread using any of the available worker OS threads. If you need control over which particular OS thread is used to run a given Haskell thread, perhaps because you need to call a foreign library that uses OS-thread-local state, then you need bound threads (see "Control.Concurrent#boundthreads"). If you don't use the @-threaded@ option, then the runtime does not make use of multiple OS threads. Foreign calls will block all other running Haskell threads until the call returns. The "System.IO" library still does multiplexing, so there can be multiple threads doing I\/O, and this is handled internally by the runtime using @select@. -} {- $termination In a standalone GHC program, only the main thread is required to terminate in order for the process to terminate. Thus all other forked threads will simply terminate at the same time as the main thread (the terminology for this kind of behaviour is \"daemonic threads\"). If you want the program to wait for child threads to finish before exiting, you need to program this yourself. A simple mechanism is to have each child thread write to an 'MVar' when it completes, and have the main thread wait on all the 'MVar's before exiting: > myForkIO :: IO () -> IO (MVar ()) > myForkIO io = do > mvar <- newEmptyMVar > forkFinally io (\_ -> putMVar mvar ()) > return mvar Note that we use 'forkFinally' to make sure that the 'MVar' is written to even if the thread dies or is killed for some reason. A better method is to keep a global list of all child threads which we should wait for at the end of the program: > children :: MVar [MVar ()] > children = unsafePerformIO (newMVar []) > > waitForChildren :: IO () > waitForChildren = do > cs <- takeMVar children > case cs of > [] -> return () > m:ms -> do > putMVar children ms > takeMVar m > waitForChildren > > forkChild :: IO () -> IO ThreadId > forkChild io = do > mvar <- newEmptyMVar > childs <- takeMVar children > putMVar children (mvar:childs) > forkFinally io (\_ -> putMVar mvar ()) > > main = > later waitForChildren $ > ... The main thread principle also applies to calls to Haskell from outside, using @foreign export@. When the @foreign export@ed function is invoked, it starts a new main thread, and it returns when this main thread terminates. If the call causes new threads to be forked, they may remain in the system after the @foreign export@ed function has returned. -} {- $preemption GHC implements pre-emptive multitasking: the execution of threads are interleaved in a random fashion. More specifically, a thread may be pre-empted whenever it allocates some memory, which unfortunately means that tight loops which do no allocation tend to lock out other threads (this only seems to happen with pathological benchmark-style code, however). The rescheduling timer runs on a 20ms granularity by default, but this may be altered using the @-i\<n\>@ RTS option. After a rescheduling \"tick\" the running thread is pre-empted as soon as possible. One final note: the @aaaa@ @bbbb@ example may not work too well on GHC (see Scheduling, above), due to the locking on a 'System.IO.Handle'. Only one thread may hold the lock on a 'System.IO.Handle' at any one time, so if a reschedule happens while a thread is holding the lock, the other thread won't be able to run. The upshot is that the switch from @aaaa@ to @bbbbb@ happens infrequently. It can be improved by lowering the reschedule tick period. We also have a patch that causes a reschedule whenever a thread waiting on a lock is woken up, but haven't found it to be useful for anything other than this example :-) -} {- $deadlock GHC attempts to detect when threads are deadlocked using the garbage collector. A thread that is not reachable (cannot be found by following pointers from live objects) must be deadlocked, and in this case the thread is sent an exception. The exception is either 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', 'NonTermination', or 'Deadlock', depending on the way in which the thread is deadlocked. Note that this feature is intended for debugging, and should not be relied on for the correct operation of your program. There is no guarantee that the garbage collector will be accurate enough to detect your deadlock, and no guarantee that the garbage collector will run in a timely enough manner. Basically, the same caveats as for finalizers apply to deadlock detection. There is a subtle interaction between deadlock detection and finalizers (as created by 'Foreign.Concurrent.newForeignPtr' or the functions in "System.Mem.Weak"): if a thread is blocked waiting for a finalizer to run, then the thread will be considered deadlocked and sent an exception. So preferably don't do this, but if you have no alternative then it is possible to prevent the thread from being considered deadlocked by making a 'StablePtr' pointing to it. Don't forget to release the 'StablePtr' later with 'freeStablePtr'. -}
shlevy/ghc
libraries/base/Control/Concurrent.hs
bsd-3-clause
24,947
0
21
6,071
2,009
1,061
948
133
3
module MyForeignLib.AnotherVal where anotherVal = 189
themoritz/cabal
cabal-testsuite/PackageTests/ForeignLibs/src/MyForeignLib/AnotherVal.hs
bsd-3-clause
55
0
4
7
11
7
4
2
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MonoLocalBinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} module T13555 where import Data.Functor.Identity (Identity(..)) data T a type Polynomial a = T a newtype GF fp d = GF (Polynomial fp) type CRTInfo r = (Int -> r, r) type Tagged s b = TaggedT s Identity b newtype TaggedT s m b = TagT { untagT :: m b } class Reflects a i where value :: Tagged a i class CRTrans mon r where crtInfo :: Reflects m Int => TaggedT m mon (CRTInfo r) instance CRTrans Maybe (GF fp d) where crtInfo :: forall m . (Reflects m Int) => TaggedT m Maybe (CRTInfo (GF fp d)) crtInfo = undefined
ezyang/ghc
testsuite/tests/polykinds/T13555.hs
bsd-3-clause
717
0
12
142
230
133
97
-1
-1
module T11246 where import GHC.Exts type Key a = Any
ezyang/ghc
testsuite/tests/typecheck/should_compile/T11246.hs
bsd-3-clause
55
0
4
12
16
11
5
3
0
-- | Module for arbitrary transformations of plot items module Iris.Transformation ( Transformation , identity , translation , scale , apply , aspectTrans , rotateX , rotateZ ) where import qualified Graphics.Rendering.OpenGL as GL import qualified Linear as L import Iris.OpenGL (Viewport (..)) -- | Type used to represent a transformation on a plot item. type Transformation = L.M44 GL.GLfloat -- | The identity transformation does nothing to its operand. identity :: Transformation identity = L.identity -- | Translates the operand to the given point. translation :: L.V3 GL.GLfloat -> Transformation translation (L.V3 x y z) = L.V4 (L.V4 1 0 0 x) (L.V4 0 1 0 y) (L.V4 0 0 1 z) (L.V4 0 0 0 1) -- | Scales the operand uniformly along the cartesian axes. The input vector -- gives the scaling factor along each axis. scale :: L.V3 GL.GLfloat -> Transformation scale (L.V3 xs ys zs) = L.V4 (L.V4 xs 0 0 0) (L.V4 0 ys 0 0) (L.V4 0 0 zs 0) (L.V4 0 0 0 1) -- | Synonym for matrix multiplication. apply :: Transformation -> Transformation -> Transformation apply = (L.!*!) -- | Scales a view so the lengths are invariant to the window aspect ratio. If -- we have a viewport aspect ratio not equal to one, then the clip coordinates -- of -1 to 1 will have pixel lengths, making an image look distorted. aspectTrans :: Viewport -> Transformation aspectTrans (Viewport _ (GL.Size w h)) | aspect >= 1 = scale $ L.V3 1 aspect 1 | otherwise = scale $ L.V3 (1 / aspect) 1 1 where aspect = fromIntegral w / fromIntegral h rotateX :: GL.GLfloat -> Transformation rotateX angle = L.V4 (L.V4 1 0 0 0) (L.V4 0 ca (-sa) 0) (L.V4 0 sa ca 0) (L.V4 0 0 0 1) where ca = cos angle sa = sin angle rotateZ :: GL.GLfloat -> Transformation rotateZ angle = L.V4 (L.V4 ca (-sa) 0 0) (L.V4 sa ca 0 0) (L.V4 0 0 1 0) (L.V4 0 0 0 1) where ca = cos angle sa = sin angle
jdreaver/iris
src/Iris/Transformation.hs
mit
1,958
0
10
470
646
341
305
38
1
{-# LANGUAGE TemplateHaskell #-} module Main where import Prelude hiding (catch,(.)) import System.IO import System.Environment import System.Console.GetOpt import Data.Char import qualified Data.Map as M import Data.List import Data.Lens.Common import Data.Lens.Template import Data.Default import Control.Category import Control.Monad import Control.Monad.Error import Control.Applicative import Control.Exception import Util.Parser import Util.Allocator import ConcSplit import qualified ConcSplit.Leaky as LEAKY import qualified ConcSplit.Safe as SAFE data Conf = Conf { _filesToJoin :: [FilePath], -- empty list means we read from standard input _partPrefix :: FilePath, _partSizes :: Int, _impl :: Impl, _listMethods :: Bool, _helpRequired :: Bool } deriving Show $( makeLenses [''Conf] ) instance Default Conf where def = Conf [] "__part." (1024^2) (SAFE.makeImpl 1024) False False implMap:: M.Map String Impl implMap = let addImpl:: M.Map String Impl -> Impl -> M.Map String Impl addImpl m impl = M.insert (getL suggestedName impl) impl m in foldl' addImpl M.empty [ LEAKY.makeImpl 3, LEAKY.makeImpl 1024, SAFE.makeImpl 3, SAFE.makeImpl 1024 ] options = [ let update p conf = pure $ setL partPrefix p conf in Option ['p'] ["prefix"] (ReqArg update "prefix") "Filename prefix for the output part files", let update s conf = (\p -> setL partSizes p conf) <$> parseSize s in Option ['s'] ["size"] (ReqArg update "size") ("Output parts file size\n" ++ "(can be expressed in the following units: b,K,M,G)\n" ++ "(default: "++ (prettyPrintSize $ getL partSizes def) ++")"), let update m conf = case M.lookup m implMap of Nothing -> throwError $ "Implementation \"" ++ m ++ "\" not found" Just i -> pure $ setL impl i conf in Option ['m'] ["method"] (ReqArg update "method") $ "Method to employ\n(default: "++ getL (impl >>> suggestedName) def ++")", let update = \conf -> pure $ setL listMethods True conf in Option ['l'] ["list"] (NoArg update) "List available methods", let update = \conf -> pure $ setL helpRequired True conf in Option ['h'] ["help"] (NoArg update) "Show this help" ] printUsage::IO () printUsage = do let header = "concsplit [OPTIONS] [FILE...]" examples = [ "concsplit input1.txt -s 1M -m safe1K", "concsplit input1.txt input2.txt -p output -s 1K8b", "concsplit -p readfromstdin -s 1K", "concsplit -l", "concsplit -h" ] putStr $ usageInfo header options putStrLn "Examples:" mapM_ putStrLn . map ((++) "\t") $ examples runSelectedImpl :: Conf -> IO () runSelectedImpl conf = do let parts = infiniteParts (getL partPrefix conf) files = getL filesToJoin conf inputs |null files = [fromPreexistingHandle stdin] |otherwise = paths2allocators ReadMode files getL (impl >>> concsplit) conf inputs (getL partSizes conf) parts main :: IO () main = do args <- getArgs let (conftrans,nonopts,errors) = getOpt Permute options args errEi |null errors = pure () |otherwise = throwError $ head errors confEi = liftA (setL filesToJoin nonopts) (foldM (flip ($)) def conftrans) case errEi *> confEi of Left errmsg -> putStrLn errmsg Right conf |getL helpRequired conf -> printUsage |getL listMethods conf -> mapM_ putStrLn $ ((map (\(k,v) -> k ++ " - " ++ show v)) . M.assocs) implMap |otherwise -> do putStrLn . show $ conf let exioHandler = \e -> do putStrLn "An IO exception happened!" putStrLn $ show (e::IOException) hFlush stdout catch (runSelectedImpl conf) exioHandler
danidiaz/concsplit
src/Main.hs
mit
4,259
0
21
1,389
1,225
627
598
96
2
{-# LANGUAGE BangPatterns, PatternGuards, Trustworthy, CPP #-} {-| This module implements a decision procedure for quantifier-free linear arithmetic. The algorithm is based on the following paper: An Online Proof-Producing Decision Procedure for Mixed-Integer Linear Arithmetic by Sergey Berezin, Vijay Ganesh, and David L. Dill -} module Data.Integer.SAT ( PropSet , noProps , checkSat , assert , Prop(..) , Expr(..) , BoundType(..) , getExprBound , getExprRange , Name , toName , fromName -- * Iterators , allSolutions , slnCurrent , slnNextVal , slnNextVar , slnEnumerate -- * Debug , dotPropSet , sizePropSet , allInerts , ppInerts -- * For QuickCheck , iPickBounded , Bound(..) , tConst ) where import Debug.Trace import Control.Applicative (Alternative (..), Applicative (..), (<$>)) import Control.Monad (MonadPlus (..), ap, guard, liftM) import Data.List (partition) import Data.Map (Map) import qualified Data.Map as Map #if MIN_VERSION_containers(0,6,0) import qualified Data.Map.Strict as MapStrict #endif import Data.Maybe (fromMaybe, mapMaybe, maybeToList) import Text.PrettyPrint #if MIN_VERSION_base(4,9,0) import Prelude hiding ((<>)) #else import Prelude #endif import qualified Control.Monad.Fail as Fail infixr 2 :|| infixr 3 :&& infix 4 :==, :/=, :<, :<=, :>, :>= infixl 6 :+, :- infixl 7 :* -------------------------------------------------------------------------------- -- Solver interface -- | A collection of propositions. newtype PropSet = State (Answer RW) deriving Show dotPropSet :: PropSet -> Doc dotPropSet (State a) = dotAnswer (ppInerts . inerts) a sizePropSet :: PropSet -> (Integer,Integer,Integer) sizePropSet (State a) = answerSize a -- | An empty collection of propositions. noProps :: PropSet noProps = State $ return initRW -- | Add a new proposition to an existing collection. assert :: Prop -> PropSet -> PropSet assert p (State rws) = State $ fmap snd $ m =<< rws where S m = prop p -- | Extract a model from a consistent set of propositions. -- Returns 'Nothing' if the assertions have no model. -- If a variable does not appear in the assignment, then it is 0 (?). checkSat :: PropSet -> Maybe [(Int,Integer)] checkSat (State m) = go m where go None = mzero go (One rw) = return [ (x,v) | (UserName x, v) <- iModel (inerts rw) ] go (Choice m1 m2) = mplus (go m1) (go m2) allInerts :: PropSet -> [Inerts] allInerts (State m) = map inerts (toList m) allSolutions :: PropSet -> [Solutions] allSolutions = map startIter . allInerts -- | Computes bounds on the expression that are compatible with the model. -- Returns `Nothing` if the bound is not known. getExprBound :: BoundType -> Expr -> PropSet -> Maybe Integer getExprBound bt e (State s) = do let S m = expr e check (t,s1) = iTermBound bt t (inerts s1) bs <- mapM check $ toList $ s >>= m case bs of [] -> Nothing _ -> Just (maximum bs) -- | Compute the range of possible values for an expression. -- Returns `Nothing` if the bound is not known. getExprRange :: Expr -> PropSet -> Maybe [Integer] getExprRange e (State s) = do let S m = expr e check (t,s1) = do l <- iTermBound Lower t (inerts s1) u <- iTermBound Upper t (inerts s1) return (l,u) bs <- mapM check $ toList $ s >>= m case bs of [] -> Nothing _ -> let (ls,us) = unzip bs in Just [ x | x <- [ minimum ls .. maximum us ] ] -- | The type of proposition. data Prop = PTrue | PFalse | Prop :|| Prop | Prop :&& Prop | Not Prop | Expr :== Expr | Expr :/= Expr | Expr :< Expr | Expr :> Expr | Expr :<= Expr | Expr :>= Expr deriving (Read,Show) -- | The type of integer expressions. -- Variable names must be non-negative. data Expr = Expr :+ Expr -- ^ Addition | Expr :- Expr -- ^ Subtraction | Integer :* Expr -- ^ Multiplication by a constant | Negate Expr -- ^ Negation | Var Name -- ^ Variable | K Integer -- ^ Constant | If Prop Expr Expr -- ^ A conditional expression | Div Expr Integer -- ^ Division, rounds down | Mod Expr Integer -- ^ Non-negative remainder deriving (Read,Show) prop :: Prop -> S () prop PTrue = return () prop PFalse = mzero prop (p1 :|| p2) = prop p1 `mplus` prop p2 prop (p1 :&& p2) = prop p1 >> prop p2 prop (Not p) = prop (neg p) where neg PTrue = PFalse neg PFalse = PTrue neg (p1 :&& p2) = neg p1 :|| neg p2 neg (p1 :|| p2) = neg p1 :&& neg p2 neg (Not q) = q neg (e1 :== e2) = e1 :/= e2 neg (e1 :/= e2) = e1 :== e2 neg (e1 :< e2) = e1 :>= e2 neg (e1 :<= e2) = e1 :> e2 neg (e1 :> e2) = e1 :<= e2 neg (e1 :>= e2) = e1 :< e2 prop (e1 :== e2) = do t1 <- expr e1 t2 <- expr e2 solveIs0 (t1 |-| t2) prop (e1 :/= e2) = do t1 <- expr e1 t2 <- expr e2 let t = t1 |-| t2 solveIsNeg t `orElse` solveIsNeg (tNeg t) prop (e1 :< e2) = do t1 <- expr e1 t2 <- expr e2 solveIsNeg (t1 |-| t2) prop (e1 :<= e2) = do t1 <- expr e1 t2 <- expr e2 let t = t1 |-| t2 |-| tConst 1 solveIsNeg t prop (e1 :> e2) = prop (e2 :< e1) prop (e1 :>= e2) = prop (e2 :<= e1) expr :: Expr -> S Term expr (e1 :+ e2) = (|+|) <$> expr e1 <*> expr e2 expr (e1 :- e2) = (|-|) <$> expr e1 <*> expr e2 expr (k :* e2) = (k |*|) <$> expr e2 expr (Negate e) = tNeg <$> expr e expr (Var x) = pure (tVar x) expr (K x) = pure (tConst x) expr (If p e1 e2) = do x <- newVar prop (p :&& Var x :== e1 :|| Not p :&& Var x :== e2) return (tVar x) expr (Div e k) = fmap fst $ exprDivMod e k expr (Mod e k) = fmap snd $ exprDivMod e k exprDivMod :: Expr -> Integer -> S (Term,Term) exprDivMod e k = do guard (k /= 0) -- Always unsat q <- newVar r <- newVar let er = Var r prop (k :* Var q :+ er :== e :&& er :< K k :&& K 0 :<= er) return (tVar q, tVar r) -------------------------------------------------------------------------------- data RW = RW { nameSource :: !Int , inerts :: Inerts } deriving Show initRW :: RW initRW = RW { nameSource = 0, inerts = iNone } -------------------------------------------------------------------------------- -- Constraints and Bound on Variables ctLt :: Term -> Term -> Term ctLt t1 t2 = t1 |-| t2 ctEq :: Term -> Term -> Term ctEq t1 t2 = t1 |-| t2 data Bound = Bound Integer Term -- ^ The integer is strictly positive deriving Show data BoundType = Lower | Upper deriving Show toCt :: BoundType -> Name -> Bound -> Term toCt Lower x (Bound c t) = ctLt t (c |*| tVar x) toCt Upper x (Bound c t) = ctLt (c |*| tVar x) t -------------------------------------------------------------------------------- -- Inert set -- | The inert contains the solver state on one possible path. data Inerts = Inerts { bounds :: NameMap ([Bound],[Bound]) -- ^ Known lower and upper bounds for variables. -- Each bound @(c,t)@ in the first list asserts that @t < c * x@ -- Each bound @(c,t)@ in the second list asserts that @c * x < t@ , solved :: NameMap Term -- ^ Definitions for resolved variables. -- These form an idempotent substitution. } deriving Show ppInerts :: Inerts -> Doc ppInerts is = vcat $ [ ppLower x b | (x,(ls,_)) <- bnds, b <- ls ] ++ [ ppUpper x b | (x,(_,us)) <- bnds, b <- us ] ++ [ ppEq e | e <- Map.toList (solved is) ] where bnds = Map.toList (bounds is) ppT c x = ppTerm (c |*| tVar x) ppLower x (Bound c t) = ppTerm t <+> text "<" <+> ppT c x ppUpper x (Bound c t) = ppT c x <+> text "<" <+> ppTerm t ppEq (x,t) = ppName x <+> text "=" <+> ppTerm t -- | An empty inert set. iNone :: Inerts iNone = Inerts { bounds = Map.empty , solved = Map.empty } -- | Rewrite a term using the definitions from an inert set. iApSubst :: Inerts -> Term -> Term iApSubst i t = foldr apS t $ Map.toList $ solved i where apS (x,t1) t2 = tLet x t1 t2 -- | Add a definition. Upper and lower bound constraints that mention -- the variable are "kicked-out" so that they can be reinserted in the -- context of the new knowledge. -- -- * Assumes substitution has already been applied. -- -- * The kicked-out constraints are NOT rewritten, this happens -- when they get inserted in the work queue. iSolved :: Name -> Term -> Inerts -> ([Term], Inerts) iSolved x t i = ( kickedOut , Inerts { bounds = otherBounds , solved = Map.insert x t $ Map.map (tLet x t) $ solved i } ) where (kickedOut, otherBounds) = -- First, we eliminate all entries for `x` let (mb, mp1) = Map.updateLookupWithKey (\_ _ -> Nothing) x (bounds i) -- Next, we elminate all constraints that mentiond `x` in bounds mp2 = Map.mapWithKey extractBounds mp1 in ( [ ct | (lbs,ubs) <- maybeToList mb , ct <- map (toCt Lower x) lbs ++ map (toCt Upper x) ubs ] ++ [ ct | (_,cts) <- Map.elems mp2, ct <- cts ] , fmap fst mp2 ) extractBounds y (lbs,ubs) = let (lbsStay, lbsKick) = partition stay lbs (ubsStay, ubsKick) = partition stay ubs in ( (lbsStay,ubsStay) , map (toCt Lower y) lbsKick ++ map (toCt Upper y) ubsKick ) stay (Bound _ bnd) = not (tHasVar x bnd) -- | Given some lower and upper bounds, find the interval the satisfies them. -- Note the upper and lower bounds are strict (i.e., < and >) boundInterval :: [Bound] -> [Bound] -> Maybe (Maybe Integer, Maybe Integer) boundInterval lbs ubs = do ls <- mapM (normBound Lower) lbs us <- mapM (normBound Upper) ubs let lb = case ls of [] -> Nothing _ -> Just (maximum ls + 1) ub = case us of [] -> Nothing _ -> Just (minimum us - 1) case (lb,ub) of (Just l, Just u) -> guard (l <= u) _ -> return () return (lb,ub) where normBound Lower (Bound c t) = do k <- isConst t return (div (k + c - 1) c) normBound Upper (Bound c t) = do k <- isConst t return (div k c) data Solutions = Done | TopVar Name Integer (Maybe Integer) (Maybe Integer) Inerts | FixedVar Name Integer Solutions deriving Show slnCurrent :: Solutions -> [(Int,Integer)] slnCurrent s = [ (x,v) | (UserName x, v) <- go s ] where go Done = [] go (TopVar x v _ _ is) = (x, v) : iModel (iLet x v is) go (FixedVar x v i) = (x, v) : go i -- | Replace occurances of a variable with an integer. -- WARNING: The integer should be a valid value for the variable. iLet :: Name -> Integer -> Inerts -> Inerts iLet x v is = Inerts { bounds = fmap updBs (bounds is) , solved = fmap (tLetNum x v) (solved is) } where updB (Bound c t) = Bound c (tLetNum x v t) updBs (ls,us) = (map updB ls, map updB us) startIter :: Inerts -> Solutions startIter is = case Map.maxViewWithKey (bounds is) of Nothing -> case Map.maxViewWithKey (solved is) of Nothing -> Done Just ((x,t), mp1) -> case [ y | y <- tVarList t ] of y : _ -> TopVar y 0 Nothing Nothing is [] -> let v = tConstPart t in TopVar x v (Just v) (Just v) $ is { solved = mp1 } Just ((x,(lbs,ubs)), mp1) -> case [ y | Bound _ t <- lbs ++ ubs, y <- tVarList t ] of y : _ -> TopVar y 0 Nothing Nothing is [] -> case boundInterval lbs ubs of Nothing -> error "bug: cannot compute interval?" Just (lb,ub) -> let v = fromMaybe 0 (mplus lb ub) in TopVar x v lb ub $ is { bounds = mp1 } slnEnumerate :: Solutions -> [ Solutions ] slnEnumerate s0 = go s0 [] where go s k = case slnNextVar s of Nothing -> hor s k Just s1 -> go s1 $ case slnNextVal s of Nothing -> k Just s2 -> go s2 k hor s k = s : case slnNextVal s of Nothing -> k Just s1 -> hor s1 k slnNextVal :: Solutions -> Maybe Solutions slnNextVal Done = Nothing slnNextVal (FixedVar x v i) = FixedVar x v `fmap` slnNextVal i slnNextVal it@(TopVar _ _ lb _ _) = case lb of Just _ -> slnNextValWith (+1) it Nothing -> slnNextValWith (subtract 1) it slnNextValWith :: (Integer -> Integer) -> Solutions -> Maybe Solutions slnNextValWith _ Done = Nothing slnNextValWith f (FixedVar x v i) = FixedVar x v `fmap` slnNextValWith f i slnNextValWith f (TopVar x v lb ub is) = do let v1 = f v case lb of Just l -> guard (l <= v1) Nothing -> return () case ub of Just u -> guard (v1 <= u) Nothing -> return () return $ TopVar x v1 lb ub is slnNextVar :: Solutions -> Maybe Solutions slnNextVar Done = Nothing slnNextVar (TopVar x v _ _ is) = Just $ FixedVar x v $ startIter $ iLet x v is slnNextVar (FixedVar x v i) = FixedVar x v `fmap` slnNextVar i -- Given a list of lower (resp. upper) bounds, compute the least (resp. largest) -- value that satisfies them all. iPickBounded :: BoundType -> [Bound] -> Maybe Integer iPickBounded _ [] = Nothing iPickBounded bt bs = do xs <- mapM (normBound bt) bs return $ case bt of Lower -> maximum xs Upper -> minimum xs where -- t < c*x -- <=> t+1 <= c*x -- <=> (t+1)/c <= x -- <=> ceil((t+1)/c) <= x -- <=> t `div` c + 1 <= x normBound Lower (Bound c t) = do k <- isConst t return (k `div` c + 1) -- c*x < t -- <=> c*x <= t-1 -- <=> x <= (t-1)/c -- <=> x <= floor((t-1)/c) -- <=> x <= (t-1) `div` c normBound Upper (Bound c t) = do k <- isConst t return (div (k-1) c) -- | The largest (resp. least) upper (resp. lower) bound on a term -- that will satisfy the model iTermBound :: BoundType -> Term -> Inerts -> Maybe Integer iTermBound bt (T k xs) is = do ks <- mapM summand (Map.toList xs) return $ sum $ k : ks where summand (x,c) = fmap (c *) (iVarBound (newBt c) x is) newBt c = if c > 0 then bt else case bt of Lower -> Upper Upper -> Lower -- | The largest (resp. least) upper (resp. lower) bound on a variable -- that will satisfy the model. iVarBound :: BoundType -> Name -> Inerts -> Maybe Integer iVarBound bt x is | Just t <- Map.lookup x (solved is) = iTermBound bt t is iVarBound bt x is = do both <- Map.lookup x (bounds is) case mapMaybe fromBound (chooseBounds both) of [] -> Nothing bs -> return (combineBounds bs) where fromBound (Bound c t) = fmap (scaleBound c) (iTermBound bt t is) combineBounds = case bt of Upper -> minimum Lower -> maximum chooseBounds = case bt of Upper -> snd Lower -> fst scaleBound c b = case bt of Upper -> div (b-1) c Lower -> div b c + 1 iModel :: Inerts -> [(Name,Integer)] iModel i = goBounds [] (bounds i) where goBounds su mp = case Map.maxViewWithKey mp of Nothing -> goEqs su $ Map.toList $ solved i Just ((x,(lbs0,ubs0)), mp1) -> let lbs = [ Bound c (tLetNums su t) | Bound c t <- lbs0 ] ubs = [ Bound c (tLetNums su t) | Bound c t <- ubs0 ] sln = fromMaybe 0 $ mplus (iPickBounded Lower lbs) (iPickBounded Upper ubs) in goBounds ((x,sln) : su) mp1 goEqs su [] = su goEqs su ((x,t) : more) = let t1 = tLetNums su t vs = tVarList t1 su1 = [ (v,0) | v <- vs ] ++ (x,tConstPart t1) : su in goEqs su1 more -------------------------------------------------------------------------------- -- Solving constraints solveIs0 :: Term -> S () solveIs0 t = solveIs0' =<< apSubst t -- | Solve a constraint if the form @t = 0@. -- Assumes substitution has already been applied. solveIs0' :: Term -> S () solveIs0' t -- A == 0 | Just a <- isConst t = guard (a == 0) -- A + B * x = 0 | Just (a,b,x) <- tIsOneVar t = case divMod (-a) b of (q,0) -> addDef x (tConst q) _ -> mzero -- x + S = 0 -- -x + S = 0 | Just (xc,x,s) <- tGetSimpleCoeff t = addDef x (if xc > 0 then tNeg s else s) -- A * S = 0 | Just (_, s) <- tFactor t = solveIs0 s -- See Section 3.1 of paper for details. -- We obtain an equivalent formulation but with smaller coefficients. | Just (ak,xk,s) <- tLeastAbsCoeff t = do let m = abs ak + 1 v <- newVar let sgn = signum ak soln = (negate sgn * m) |*| tVar v |+| tMapCoeff (\c -> sgn * modulus c m) s addDef xk soln let upd i = div (2*i + m) (2*m) + modulus i m solveIs0 (negate (abs ak) |*| tVar v |+| tMapCoeff upd s) | otherwise = error "solveIs0: unreachable" modulus :: Integer -> Integer -> Integer modulus a m = a - m * div (2 * a + m) (2 * m) solveIsNeg :: Term -> S () solveIsNeg t = solveIsNeg' =<< apSubst t -- | Solve a constraint of the form @t < 0@. -- Assumes that substitution has been applied solveIsNeg' :: Term -> S () solveIsNeg' t -- A < 0 | Just a <- isConst t = guard (a < 0) -- A * S < 0 | Just (_,s) <- tFactor t = solveIsNeg s -- See Section 5.1 of the paper | Just (xc,x,s) <- tLeastVar t = do ctrs <- if xc < 0 -- -XC*x + S < 0 -- S < XC*x then do ubs <- getBounds Upper x let b = negate xc beta = s addBound Lower x (Bound b beta) return [ (a,alpha,b,beta) | Bound a alpha <- ubs ] -- XC*x + S < 0 -- XC*x < -S else do lbs <- getBounds Lower x let a = xc alpha = tNeg s addBound Upper x (Bound a alpha) return [ (a,alpha,b,beta) | Bound b beta <- lbs ] -- See Note [Shadows] mapM_ (\(a,alpha,b,beta) -> do let real = ctLt (a |*| beta) (b |*| alpha) dark = ctLt (tConst (a * b)) (b |*| alpha |-| a |*| beta) gray = [ ctEq (b |*| tVar x) (tConst i |+| beta) | i <- [ 1 .. b - 1 ] ] solveIsNeg real foldl orElse (solveIsNeg dark) (map solveIs0 gray) ) ctrs | otherwise = error "solveIsNeg: unreachable" orElse :: S () -> S () -> S () orElse x y = mplus x y {- Note [Shadows] P: beta < b * x Q: a * x < alpha real: a * beta < b * alpha beta < b * x -- from P a * beta < a * b * x -- (a *) a * beta < b * alpha -- comm. and Q dark: b * alpha - a * beta > a * b gray: b * x = beta + 1 \/ b * x = beta + 2 \/ ... b * x = beta + (b-1) We stop at @b - 1@ because if: > b * x >= beta + b > a * b * x >= a * (beta + b) -- (a *) > a * b * x >= a * beta + a * b -- distrib. > b * alpha > a * beta + a * b -- comm. and Q > b * alpha - a * beta > a * b -- subtract (a * beta) which is covered by the dark shadow. -} -------------------------------------------------------------------------------- -- Monads data Answer a = None | One a | Choice (Answer a) (Answer a) deriving Show answerSize :: Answer a -> (Integer,Integer,Integer) answerSize = go 0 0 0 where go !n !o !c ans = case ans of None -> (n+1, o, c) One _ -> (n, o + 1, c) Choice x y -> case go n o (c+1) x of (n',o',c') -> go n' o' c' y dotAnswer :: (a -> Doc) -> Answer a -> Doc dotAnswer pp g0 = vcat [text "digraph {", nest 2 (fst $ go 0 g0), text "}"] where node x d = integer x <+> brackets (text "label=" <> text (show d)) <> semi edge x y = integer x <+> text "->" <+> integer y go x None = let x' = x + 1 in seq x' ( node x "", x' ) go x (One a) = let x' = x + 1 in seq x' ( node x (show (pp a)), x' ) go x (Choice c1 c2) = let x' = x + 1 (ls1,x1) = go x' c1 (ls2,x2) = go x1 c2 in seq x' ( vcat [ node x "|" , edge x x' , edge x x1 , ls1 , ls2 ], x2 ) toList :: Answer a -> [a] toList a = go a [] where go (Choice xs ys) zs = go xs (go ys zs) go (One x) xs = x : xs go None xs = xs instance Monad Answer where return a = One a None >>= _ = None One a >>= k = k a Choice m1 m2 >>= k = mplus (m1 >>= k) (m2 >>= k) #if !(MIN_VERSION_base(4,13,0)) fail = Fail.fail #endif instance Fail.MonadFail Answer where fail _ = None instance Alternative Answer where empty = mzero (<|>) = mplus instance MonadPlus Answer where mzero = None mplus None x = x -- mplus (Choice x y) z = mplus x (mplus y z) mplus x y = Choice x y instance Functor Answer where fmap _ None = None fmap f (One x) = One (f x) fmap f (Choice x1 x2) = Choice (fmap f x1) (fmap f x2) instance Applicative Answer where pure = return (<*>) = ap newtype S a = S (RW -> Answer (a,RW)) instance Monad S where return a = S $ \s -> return (a,s) S m >>= k = S $ \s -> do (a,s1) <- m s let S m1 = k a m1 s1 instance Alternative S where empty = mzero (<|>) = mplus instance MonadPlus S where mzero = S $ \_ -> mzero mplus (S m1) (S m2) = S $ \s -> mplus (m1 s) (m2 s) instance Functor S where fmap = liftM instance Applicative S where pure = return (<*>) = ap updS :: (RW -> (a,RW)) -> S a updS f = S $ \s -> return (f s) updS_ :: (RW -> RW) -> S () updS_ f = updS $ \rw -> ((),f rw) get :: (RW -> a) -> S a get f = updS $ \rw -> (f rw, rw) newVar :: S Name newVar = updS $ \rw -> ( SysName (nameSource rw) , rw { nameSource = nameSource rw + 1 } ) -- | Get lower ('fst'), or upper ('snd') bounds for a variable. getBounds :: BoundType -> Name -> S [Bound] getBounds f x = get $ \rw -> case Map.lookup x $ bounds $ inerts rw of Nothing -> [] Just bs -> case f of Lower -> fst bs Upper -> snd bs addBound :: BoundType -> Name -> Bound -> S () addBound bt x b = updS_ $ \rw -> let i = inerts rw entry = case bt of Lower -> ([b],[]) Upper -> ([],[b]) jn (newL,newU) (oldL,oldU) = (newL++oldL, newU++oldU) in rw { inerts = i { bounds = Map.insertWith jn x entry (bounds i) }} -- | Add a new definition. -- Assumes substitution has already been applied addDef :: Name -> Term -> S () addDef x t = do newWork <- updS $ \rw -> let (newWork,newInerts) = iSolved x t (inerts rw) in (newWork, rw { inerts = newInerts }) mapM_ solveIsNeg newWork apSubst :: Term -> S Term apSubst t = do i <- get inerts return (iApSubst i t) -------------------------------------------------------------------------------- data Name = UserName !Int | SysName !Int deriving (Read,Show,Eq,Ord) ppName :: Name -> Doc ppName (UserName x) = text "u" <> int x ppName (SysName x) = text "s" <> int x toName :: Int -> Name toName = UserName fromName :: Name -> Maybe Int fromName (UserName x) = Just x fromName (SysName _) = Nothing type NameMap = Map Name -- | The type of terms. The integer is the constant part of the term, -- and the `Map` maps variables (represented by @Int@ to their coefficients). -- The term is a sum of its parts. -- INVARIANT: the `Map` does not map anything to 0. data Term = T !Integer (NameMap Integer) deriving (Eq,Ord) infixl 6 |+|, |-| infixr 7 |*| -- | A constant term. tConst :: Integer -> Term tConst k = T k Map.empty -- | Construct a term with a single variable. tVar :: Name -> Term tVar x = T 0 (Map.singleton x 1) (|+|) :: Term -> Term -> Term T n1 m1 |+| T n2 m2 = T (n1 + n2) $ if Map.null m1 then m2 else if Map.null m2 then m1 else Map.filter (/= 0) $ Map.unionWith (+) m1 m2 (|*|) :: Integer -> Term -> Term 0 |*| _ = tConst 0 1 |*| t = t k |*| T n m = T (k * n) (fmap (k *) m) tNeg :: Term -> Term tNeg t = (-1) |*| t (|-|) :: Term -> Term -> Term t1 |-| t2 = t1 |+| tNeg t2 -- | Replace a variable with a term. tLet :: Name -> Term -> Term -> Term tLet x t1 t2 = let (a,t) = tSplitVar x t2 in a |*| t1 |+| t -- | Replace a variable with a constant. tLetNum :: Name -> Integer -> Term -> Term tLetNum x k t = let (c,T n m) = tSplitVar x t in T (c * k + n) m -- | Replace the given variables with constants. tLetNums :: [(Name,Integer)] -> Term -> Term tLetNums xs t = foldr (\(x,i) t1 -> tLetNum x i t1) t xs instance Show Term where showsPrec c t = showsPrec c (show (ppTerm t)) ppTerm :: Term -> Doc ppTerm (T k m) = case Map.toList m of [] -> integer k xs | k /= 0 -> hsep (integer k : map ppProd xs) x : xs -> hsep (ppFst x : map ppProd xs) where ppFst (x,1) = ppName x ppFst (x,-1) = text "-" <> ppName x ppFst (x,n) = ppMul n x ppProd (x,1) = text "+" <+> ppName x ppProd (x,-1) = text "-" <+> ppName x ppProd (x,n) | n > 0 = text "+" <+> ppMul n x | otherwise = text "-" <+> ppMul (abs n) x ppMul n x = integer n <+> text "*" <+> ppName x -- | Remove a variable from the term, and return its coefficient. -- If the variable is not present in the term, the coefficient is 0. tSplitVar :: Name -> Term -> (Integer, Term) tSplitVar x t@(T n m) = case Map.updateLookupWithKey (\_ _ -> Nothing) x m of (Nothing,_) -> (0,t) (Just k,m1) -> (k, T n m1) -- | Does the term contain this varibale? tHasVar :: Name -> Term -> Bool tHasVar x (T _ m) = Map.member x m -- | Is this terms just an integer. isConst :: Term -> Maybe Integer isConst (T n m) | Map.null m = Just n | otherwise = Nothing tConstPart :: Term -> Integer tConstPart (T n _) = n -- | Returns: @Just (a, b, x)@ if the term is the form: @a + b * x@ tIsOneVar :: Term -> Maybe (Integer, Integer, Name) tIsOneVar (T a m) = case Map.toList m of [ (x,b) ] -> Just (a, b, x) _ -> Nothing -- | Spots terms that contain variables with unit coefficients -- (i.e., of the form @x + t@ or @t - x@). -- Returns (coeff, var, rest of term) tGetSimpleCoeff :: Term -> Maybe (Integer, Name, Term) tGetSimpleCoeff (T a m) = do let (m1,m2) = Map.partition (\x -> x == 1 || x == -1) m ((x,xc), m3) <- Map.minViewWithKey m1 return (xc, x, T a (Map.union m3 m2)) tVarList :: Term -> [Name] tVarList (T _ m) = Map.keys m -- | Try to factor-out a common consant (> 1) from a term. -- For example, @2 + 4x@ becomes @2 * (1 + 2x)@. tFactor :: Term -> Maybe (Integer, Term) tFactor (T c m) = do d <- common (c : Map.elems m) return (d, T (div c d) (fmap (`div` d) m)) where common :: [Integer] -> Maybe Integer common [] = Nothing common [x] = Just x common (x : y : zs) = case gcd x y of 1 -> Nothing n -> common (n : zs) -- | Extract a variable with a coefficient whose absolute value is minimal. tLeastAbsCoeff :: Term -> Maybe (Integer, Name, Term) #if MIN_VERSION_containers(0,6,0) tLeastAbsCoeff (T c m) = do (xc,x,m1) <- MapStrict.foldrWithKey step Nothing m #else tLeastAbsCoeff (T c m) = do (xc,x,m1) <- Map.foldWithKey step Nothing m #endif return (xc, x, T c m1) where step x xc Nothing = Just (xc, x, Map.delete x m) step x xc (Just (yc,_,_)) | abs xc < abs yc = Just (xc, x, Map.delete x m) step _ _ it = it -- | Extract the least variable from a term tLeastVar :: Term -> Maybe (Integer, Name, Term) tLeastVar (T c m) = do ((x,xc), m1) <- Map.minViewWithKey m return (xc, x, T c m1) -- | Apply a function to all coefficients, including the constnat tMapCoeff :: (Integer -> Integer) -> Term -> Term tMapCoeff f (T c m) = T (f c) (fmap f m)
yav/presburger
src/Data/Integer/SAT.hs
mit
29,654
0
20
10,227
10,547
5,421
5,126
619
11
import Data.Array import Data.List (group) import Debug.Trace import qualified Data.Set as Set abundantNumbers = filter isAbundant [12..nmax+5] sum2AbundantNumbers = set where set = Set.fromList [ x + y | x <- abundantNumbers, y <- abundantNumbers, x + y <= nmax ] complement = Set.difference naturals sum2AbundantNumbers where naturals = Set.fromList [1..nmax] sumComplement = sum $ Set.toList complement
arekfu/project_euler
p0023/p0023.hs
mit
434
0
11
85
143
77
66
10
1
-- This program calculates the TVBW representation of the braid -- generator in terms of the structural morphisms of a spherical -- category. To do this, it follows Table 3 of the Finiteness for DW -- MCG reps paper. -- -- We encode a stringnet as a marked CW-complex. -- For now, all duals are right duals. All compositions are in -- standard (anti-diagrammatic) order. -- -- module Stringnet where import Finite import Prelude hiding (product, Left, Right) import Control.Monad.State import Data.Semigroup import qualified Data.Tree as T -- Left and right refer to positions before the braiding operation data Puncture = LeftPuncture | RightPuncture deriving (Show, Eq) data InteriorVertex = Main | Midpoint Edge | Contraction Edge deriving (Show, Eq) data Vertex = Punc Puncture | IV InteriorVertex deriving (Show, Eq) --initial edges data InitialEdge = LeftLoop | RightLoop | LeftLeg | RightLeg deriving (Show, Eq, Enum) instance Finite InitialEdge where allElements = [LeftLoop, RightLoop, LeftLeg, RightLeg] -- Orientations of initial edges are given by arrows in the figures in -- the paper data Edge = -- initial edges IE InitialEdge -- result of adding coev vertex (--(e)--> (coev e) --(e)-->) | FirstHalf Edge | SecondHalf Edge -- connects the start of the two edges with a 1 in the disk | Connector Edge Edge Disk -- stick together parallel edges | TensorE Edge Edge -- don't use this constructor except to pattern match, use "rev" -- instead | Reverse Edge deriving (Show, Eq) data Disk = -- initial disks Outside | LeftDisk | RightDisk -- Edge should be of type Connect | Cut Edge deriving (Show, Eq) data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Eq, Show) instance Functor Tree where fmap f (Leaf l) = Leaf $ f l fmap f (Node a b) = Node (fmap f a) (fmap f b) instance Foldable Tree where foldMap f (Leaf x) = f x foldMap f (Node a b) = (foldMap f a) `mappend` (foldMap f b) data Object = OVar InitialEdge -- Object variable labeling edge | One | Star Object -- Don't use this constructor except to -- pattern match, use "star" instead | TensorO Object Object deriving (Show) data ColoredGraph = ColoredGraph { vertices :: ![InteriorVertex] , edges :: ![Edge] , disks :: ![Disk] -- The edges returned by perimeter should form a -- cycle (the end point of an edge should be the the -- starting point of the next edges). Additionally, -- the edges should either lie in the edges of the -- ColoredGraph or be the reverse of such an edge. -- CCW ordering. , perimeter :: !(Disk -> [Edge]) -- image under contractions , imageVertex :: !(Vertex -> Vertex) , morphismLabel :: !(InteriorVertex -> Morphism) -- CCW ordering, outgoing orientation , edgeTree :: !(Vertex -> Tree Edge) , objectLabel :: !(Edge -> Object) } tensorO :: Object -> Object -> Object tensorO o1 o2 = o1 `TensorO` o2 -- TODO: make tensor Tree structure and composition list structure more -- explicit data Morphism = Phi | Id Object | Lambda Object -- 1 V -> V | LambdaI Object | Rho Object -- V 1 -> V | RhoI Object | Alpha Object Object Object -- associator (xy)z = x(yz) | AlphaI Object Object Object -- inverse associator | Coev Object -- right coev | Ev Object -- right ev | TensorM Morphism Morphism | PivotalJ Object -- X -> X** | PivotalJI Object -- X** -> X | Compose [Morphism] deriving (Show) compose :: Morphism -> Morphism -> Morphism compose (Compose ms) (Compose ns) = Compose $ ms ++ ns compose (Compose ms) n = Compose $ ms ++ [n] compose n (Compose ms) = Compose $ [n] ++ ms compose m n = Compose [m, n] toTensorTree :: Morphism -> Tree Morphism toTensorTree (TensorM x y) = Node (toTensorTree x) (toTensorTree y) toTensorTree x = Leaf x toCompositionList :: Morphism -> [Morphism] toCompositionList (Compose ms) = ms toCompositionList m = [m] toTree :: Morphism -> T.Tree (Maybe Morphism) -- toTree m@(Compose _) = -- T.Node Nothing (map toTree $ toCompositionList m) toTree (TensorM x y) = T.Node Nothing [(toTree x), (toTree y)] toTree x = T.Node (Just x) [] instance Semigroup Morphism where a <> b = compose a b toDataTree :: Tree a -> T.Tree (Maybe a) toDataTree (Leaf x) = T.Node (Just x) [] toDataTree (Node x y) = T.Node Nothing [toDataTree x, toDataTree y] -- Pretty print pprint :: (Show a) => Tree a-> IO () pprint = putStr. T.drawTree . fmap (\x -> case x of Nothing -> "+" Just e -> show e ) . toDataTree -- type cast toIV :: Vertex -> InteriorVertex toIV (IV v) = v rev :: Edge -> Edge rev (Reverse e) = e -- MAYBE: (need to deal with Eq instance) -- rev (TensorE a b) = TensorE (rev a) (rev b) rev e = Reverse e star :: Object -> Object star (Star o) = o star o = Star o -- endpoints before finding the images of the vertices under -- contractions initialEndpoints :: Edge -> [Vertex] initialEndpoints edge = case edge of IE LeftLoop -> [IV Main, IV Main] IE RightLoop -> [IV Main, IV Main] IE LeftLeg -> [IV Main, Punc LeftPuncture] IE RightLeg -> [IV Main, Punc RightPuncture] FirstHalf e -> [(initialEndpoints e) !! 0, IV $ Midpoint e] SecondHalf e -> [IV $ Midpoint e, (initialEndpoints e) !! 1] Connector e1 e2 _ -> [initialStart e1, initialStart e2] TensorE e1 _ -> initialEndpoints e1 Reverse e -> reverse (initialEndpoints e) initialStart :: Edge -> Vertex initialStart e = (initialEndpoints e) !! 0 initialEnd :: Edge -> Vertex initialEnd e = (initialEndpoints e) !! 1 -- TODO: maybe put this into ColoredGraph, to make parallel with -- perimeter also, eliminate "image" endpoints :: Edge -> ColoredGraph -> [Vertex] endpoints e tc = map (imageVertex tc) (initialEndpoints e) -- Monadic versions of methods edgeTreeM :: Vertex -> State ColoredGraph (Tree Edge) edgeTreeM v = state $ \tc -> (edgeTree tc v, tc) endpointsM :: Edge -> State ColoredGraph [Vertex] endpointsM e = state $ \tc -> (endpoints e tc, tc) perimeterM :: Disk -> State ColoredGraph [Edge] perimeterM d = state $ \tc -> (perimeter tc d, tc) start :: Edge -> ColoredGraph -> Vertex start e tc = (endpoints e tc) !! 0 end :: Edge -> ColoredGraph -> Vertex end e tc = (endpoints e tc) !! 1 objectLabel0 :: Edge -> Object objectLabel0 (IE e) = OVar e objectLabel0 (FirstHalf e) = objectLabel0 e objectLabel0 (SecondHalf e) = objectLabel0 e objectLabel0 (Connector _ _ _) = One objectLabel0 (TensorE e1 e2) = TensorO (objectLabel0 e1) (objectLabel0 e2) objectLabel0 (Reverse e) = star (objectLabel0 e) treeLabel :: (Edge -> Object) -> Tree Edge -> Object treeLabel label (Leaf e) = label e treeLabel label (Node x y) = TensorO (treeLabel label x) (treeLabel label y) -- reverseEdge :: Edge -> State ColoredGraph Edge -- reverseEdge e0 = state $ \tc -> -- (rev e0 -- , tc -- { edges = [rev e0] ++ [e | e <- edges tc -- , e /= e0] }) flatten :: Tree a -> [a] flatten (Leaf x) = [x] flatten (Node x y) = (flatten x) ++ (flatten y) replace :: (Eq a) => Tree a -> Tree a -> Tree a -> Tree a replace subTree1 subTree2 bigTree = if bigTree == subTree1 then subTree2 else case bigTree of Leaf x -> Leaf x Node x y -> Node (replace subTree1 subTree2 x) (replace subTree1 subTree2 y) -- Test: replacePlusH Phi (Node (Leaf (Reverse (IE -- RightLoop))) (Node (Leaf (IE RightLeg)) (Leaf (IE RightLoop)))) (Leaf $ IE -- RightLoop) (initialEdgeTree $ IV Main) -- replacePlusH :: ColoredGraph -> Morphism -> Tree Edge -> Tree Edge -> Tree Edge -> (Tree Edge, Tree Morphism) replacePlusH sn m oldSubTree newSubTree bigTree = if bigTree == oldSubTree then (newSubTree, Leaf m) else case bigTree of Leaf x -> (Leaf x, Leaf $ Id $ objectLabel sn x) Node x y -> let (tex, tmx) = replacePlusH sn m oldSubTree newSubTree x (tey, tmy) = replacePlusH sn m oldSubTree newSubTree y in (Node tex tey, Node tmx tmy) tensorMTree :: Tree Morphism -> Morphism tensorMTree (Leaf m) = m tensorMTree (Node x y) = TensorM (tensorMTree x) (tensorMTree y) replacePlus :: ColoredGraph -> Morphism -> Tree Edge -> Tree Edge -> Tree Edge -> (Tree Edge, Morphism) replacePlus sn m oldSubTree newSubTree bigTree = let (eTree, mTree) = replacePlusH sn m oldSubTree newSubTree bigTree in (eTree, tensorMTree mTree) -- TODO: debug the following -- -- data Side = Left | Right -- -- associate :: Side -> InteriorVertex -> Tree Edge -> State ColoredGraph (Tree Edge) -- associate side v0 subTree@(Node x y) = -- let -- (newSubTree, unaugmentedMorphism) = case side of -- Left -> case y of -- Node y0 y1 -> (Node x (Node y0 y1), -- AlphaI (treeLabel x) (treeLabel y0) (treeLabel y1)) -- Right -> case x of -- Node x0 x1 -> (Node (Node x0 x1) y, -- Alpha (treeLabel x0) (treeLabel x1) (treeLabel y)) -- in -- state $ \tc -> -- (newSubTree, -- let -- (newEdgeTree, morphism) = replacePlus -- unaugmentedMorphism -- subTree newSubTree $ edgeTree tc $ IV v0 -- in -- tc -- { edgeTree = \v -> -- if v == IV v0 -- then newEdgeTree -- else edgeTree tc v -- , morphismLabel = \v -> -- if v == v0 -- then Compose morphism -- (morphismLabel tc v) -- else morphismLabel tc v -- } -- ) -- associateL :: InteriorVertex -> Tree Edge -> State ColoredGraph (Tree Edge) -- associateL = associate Left -- associateR :: InteriorVertex -> Tree Edge -> State ColoredGraph (Tree Edge) -- associateR = associate Right -- Test: -- let a = associateL Main (Node (Leaf (Reverse (IE RightLoop))) (Node (Leaf (IE RightLeg)) (Leaf (IE RightLoop)))) -- let tc2 = execState a initialTC -- edgeTree tc2 $ IV Main associateL :: InteriorVertex -> Tree Edge -> State ColoredGraph (Tree Edge) associateL v0 subTree@(Node x yz) = case yz of Node y z -> let newSubTree = (Node (Node x y) z) in state $ \tc -> (newSubTree, let (newEdgeTree, morphism) = replacePlus tc (AlphaI (treeLabel (objectLabel tc) x) (treeLabel (objectLabel tc) y) (treeLabel (objectLabel tc) z)) subTree newSubTree $ edgeTree tc $ IV v0 in tc { edgeTree = \v -> if v == IV v0 then newEdgeTree else edgeTree tc v , morphismLabel = \v -> if v == v0 then compose morphism (morphismLabel tc v) else morphismLabel tc v } ) associateR :: InteriorVertex -> Tree Edge -> State ColoredGraph (Tree Edge) associateR v0 subTree@(Node xy z) = case xy of Node x y -> let newSubTree = (Node x (Node y z)) in state $ \tc -> (newSubTree, let (newEdgeTree, morphism) = replacePlus tc (Alpha (treeLabel (objectLabel tc) x) (treeLabel (objectLabel tc) y) (treeLabel (objectLabel tc) z) ) subTree newSubTree $ edgeTree tc $ IV v0 in tc { edgeTree = \v -> if v == IV v0 then newEdgeTree else edgeTree tc v , morphismLabel = \v -> if v == v0 then compose (morphism) (morphismLabel tc v) else morphismLabel tc v } ) isolateHelperR :: InteriorVertex -> ColoredGraph -> ColoredGraph isolateHelperR v tc = let t = edgeTree tc (IV v) in case t of Node _ (Leaf _) -> tc Node _ (Node _ _) -> isolateHelperR v $ execState (associateL v t) tc isolateHelperL :: InteriorVertex -> ColoredGraph -> ColoredGraph isolateHelperL v tc = let t = edgeTree tc (IV v) in case t of Node (Leaf _) _ -> tc Node (Node _ _) _ -> isolateHelperL v $ execState (associateR v t) tc -- Turns the far right leaf into a depth one leaf isolateR :: InteriorVertex -> State ColoredGraph () isolateR v0 = state $ \tc -> ((), isolateHelperR v0 tc) isolateL :: InteriorVertex -> State ColoredGraph () isolateL v0 = state $ \tc -> ((), isolateHelperL v0 tc) swap :: Tree a -> Tree a swap (Node x y) = Node y x -- zMorphism :: Object -> Object -> Morphism -> Morphism zMorphism xl yl m = ((Id xl) `TensorM` (Rho yl)) <> ((Id xl) `TensorM` ((Id yl) `TensorM` (Ev $ star xl))) -- X (Y 1) <> ((Id xl) `TensorM` (Alpha yl xl (star xl))) -- X (Y (X *X)) <> ((Id xl) `TensorM` (m `TensorM` (Id $ star xl))) -- X 1 *X -> X ((Y X) *X) <> ((PivotalJI xl) `TensorM` (LambdaI $ star xl)) -- **X *X -> X (1 *X) <> (Coev $ star xl) -- 1 -> **X *X -- rotation of the rightmost edge in v0's to the leftside zRotate :: InteriorVertex -> State ColoredGraph () zRotate v0 = isolateR v0 >> ( state $ \tc -> ((), tc { edgeTree = \v -> ( if v == IV v0 then swap else id ) $ edgeTree tc v , morphismLabel = \v -> if v == v0 then case (edgeTree tc (IV v0)) of Node y (Leaf x) -> zMorphism (objectLabel tc x) (treeLabel (objectLabel tc) y) (morphismLabel tc v) else morphismLabel tc v } ) ) rotateToEndHelper :: Edge -> InteriorVertex -> ColoredGraph -> ColoredGraph rotateToEndHelper e0 v0 tc = let es = flatten $ edgeTree tc (IV v0) in if es !! (length es - 1) == e0 then tc else rotateToEndHelper e0 v0 $ execState (zRotate v0) tc rotateToEnd :: Edge -> InteriorVertex -> State ColoredGraph () rotateToEnd e0 v0 = (state $ \tc -> ((), rotateToEndHelper e0 v0 tc)) >> isolateR v0 elemT :: Eq a => a -> Tree a -> Bool elemT u = (elem u) . flatten minimalSuperTree :: (Eq a) => a -> a -> Tree a -> Tree a minimalSuperTree a1 a2 t@(Node x y) | a1 `elemT` x && a2 `elemT` x = minimalSuperTree a1 a2 x | a1 `elemT` y && a2 `elemT` y = minimalSuperTree a1 a2 y | otherwise = t -- Easy optimization: calculate t from previous t isolate2Helper :: Edge -> Edge -> InteriorVertex -> ColoredGraph -> ColoredGraph isolate2Helper e1 e2 v0 tc0 = let t = minimalSuperTree e1 e2 (edgeTree tc0 $ IV v0) in case t of Node x y -> case x of Node _ _ -> isolate2Helper e1 e2 v0 $ execState (associateR v0 t) tc0 Leaf _ -> case y of Node _ _ -> isolate2Helper e1 e2 v0 $ execState (associateL v0 t) tc0 Leaf _ -> tc0 -- Put (rev) e1 and e2 on same node isolate2 :: Edge -> Edge -> InteriorVertex -> State ColoredGraph () isolate2 e1 e2 v0 = state $ \tc0 -> let firstEdge = (flatten $ edgeTree tc0 $ IV v0) !! 0 tc1 = if (e2 == firstEdge) then execState (zRotate v0) tc0 else tc0 in ((), isolate2Helper e1 e2 v0 tc1) -- The disk's perimeter should only have two edges tensorHelper :: Disk -> State ColoredGraph Edge tensorHelper d0 = state $ \tc0 -> let e1 = (perimeter tc0 d0) !! 0 e2 = rev ((perimeter tc0 d0) !! 1) v0 = toIV ((endpoints e1 tc0) !! 0) v1 = toIV ((endpoints e1 tc0) !! 1) product = TensorE e1 e2 edgeImage e = case () of _ | e `elem` [e1, e2] -> product | e `elem` [rev e1, rev e2] -> rev product | otherwise -> e tc = execState (isolate2 e1 e2 v0 >> isolate2 (rev e2) (rev e1) v1 ) tc0 in ( product , tc { edges = map edgeImage (edges tc) , disks = [d | d <- disks tc , d /= d0] , perimeter = (map edgeImage) . (perimeter tc) , edgeTree = (replace (Node (Leaf e1) (Leaf e2)) (Leaf product)) . (replace (Node (Leaf $ rev e2) (Leaf $ rev e1)) (Leaf $ rev product)) . (edgeTree tc) } ) tensorN :: Disk -> ColoredGraph -> ColoredGraph tensorN d0 tc0 = let e1 = (perimeter tc0 d0) !! 0 e2 = rev ((perimeter tc0 d0) !! 1) v0 = toIV ((endpoints e1 tc0) !! 0) v1 = toIV ((endpoints e1 tc0) !! 1) in execState (isolate2 e1 e2 v0 >> isolate2 (rev e2) (rev e1) v1 >> tensorHelper d0 ) tc0 tensor :: Disk -> State ColoredGraph () tensor d = state $ \tc -> ((), tensorN d tc) -- do -- e1 <- fmap (!! 0) (perimeter d0) -- e2 <- fmap rev $ fmap (!! 1) (perimeterM d0) -- v0 <- fmap (!! 0) (endpointsM e1) -- v1 <- fmap (!! 1) (endpointsM e1) -- isolate2 e1 e2 v0 -- isolate2 (rev e2) (rev e1) v1 -- tensorHelper d0 contract :: Edge -> State ColoredGraph InteriorVertex contract e = do v0 <- fmap (toIV . (!! 0)) $ endpointsM e v1 <- fmap (toIV . (!! 1)) $ endpointsM e rotateToEnd e v0 rotateToEnd (rev e) v1 zRotate v1 isolateL v1 contractHelper e leftSubTree :: Tree a -> Tree a leftSubTree (Node x _) = x rightSubTree :: Tree a -> Tree a rightSubTree (Node _ y) = y contractHelper :: Edge -> State ColoredGraph InteriorVertex contractHelper contractedEdge = state $ \tc -> let v0 = toIV $ (endpoints contractedEdge tc) !! 0 v1 = toIV $ (endpoints contractedEdge tc) !! 1 composition = Contraction contractedEdge in (composition, tc { vertices = [composition] ++ [v | v <- vertices tc , not $ v `elem` [v0, v1]] , edges = [e | e <- edges tc , e /= contractedEdge , e /= rev contractedEdge] , imageVertex = (\v -> if v `elem` [IV v0, IV v1] then IV composition else v ) . (imageVertex tc) , edgeTree = \v -> if v == IV composition then Node (leftSubTree $ edgeTree tc $ IV v0) (rightSubTree $ edgeTree tc $ IV v1) else edgeTree tc v , morphismLabel = (\v -> if (v == composition) then compose ((Id $ treeLabel (objectLabel tc) (leftSubTree $ edgeTree tc $ IV v0)) `TensorM` (Ev $ objectLabel tc contractedEdge) `TensorM` (Id $ treeLabel (objectLabel tc) (rightSubTree $ edgeTree tc $ IV v1)) ) (TensorM (morphismLabel tc v0) (morphismLabel tc v1)) else morphismLabel tc v ) , perimeter = \d -> [e | e <- perimeter tc d , e /= contractedEdge , e /= rev contractedEdge ] } ) -- Connect the starting point of the first edge to that of the second -- through the disk The edges e1 and e2 should be distinct elements of -- perimeter d. connect :: Edge -> Edge -> Disk -> State ColoredGraph Edge connect e1 e2 d = state $ \tc -> let connection = Connector e1 e2 d in ( connection , let (edgeTree1, morphism1) = replacePlus tc (RhoI $ objectLabel tc e1) (Leaf e1) (Node (Leaf e1) (Leaf $ connection)) (edgeTree tc $ start e1 tc) (edgeTree2, morphism2) = replacePlus tc (RhoI $ objectLabel tc e2) (Leaf e2) (Node (Leaf e2) (Leaf $ rev connection)) (edgeTree tc $ start e2 tc) in tc { edges = [connection] ++ edges tc , disks = [Cut connection, Cut $ rev connection] ++ [d2 | d2 <- disks tc , d2 /= d] , edgeTree = \v -> case () of _ | v == (start e1 tc) -> edgeTree1 | v == (start e2 tc) -> edgeTree2 | otherwise -> edgeTree tc v , perimeter = \d0 -> case () of _ | d0 == Cut connection -> [connection] ++ (takeWhile (/= e1) $ dropWhile (/= e2) $ cycle $ perimeter tc d) | d0 == Cut (rev connection) -> [rev connection] ++ (takeWhile (/= e2) $ dropWhile (/= e1) $ cycle $ perimeter tc d) | otherwise -> perimeter tc d0 -- Find index of objectlabels , morphismLabel = \v -> case () of _ | v == toIV (start e1 tc) -> morphism1 <> morphismLabel tc v | v == toIV (start e2 tc) -> morphism2 <> morphismLabel tc v | otherwise -> morphismLabel tc v } ) addCoev :: Edge -> State ColoredGraph (InteriorVertex, Edge, Edge) addCoev e = state $ \tc -> let mp = Midpoint e fh = FirstHalf e sh = SecondHalf e in ((mp, fh, sh), tc { vertices = [mp] ++ vertices tc , edges = [fh, sh] ++ [f | f <- edges tc , f /= e , f /= rev e] , edgeTree = \v -> case () of _ | v == IV mp -> Node (Leaf $ rev $ FirstHalf e) (Leaf $ SecondHalf e) | otherwise -> (replace (Leaf e) (Leaf fh)) . (replace (Leaf $ rev e) (Leaf $ rev sh)) $ edgeTree tc v , perimeter = flip (>>=) (\es -> if es == [e] then [fh, sh] else if es == [rev e] then [rev sh, rev fh] else es ) . (map return) . perimeter tc , morphismLabel = \v -> if v == mp then Coev $ objectLabel tc e else morphismLabel tc v } ) -- perimeter before contractions initialPerimeter :: Disk -> [Edge] initialPerimeter Outside = [IE LeftLoop, IE RightLoop] initialPerimeter LeftDisk = [Reverse $ IE LeftLoop, IE LeftLeg, Reverse $ IE LeftLeg] initialPerimeter RightDisk = [Reverse $ IE RightLoop, IE RightLeg, Reverse $ IE RightLeg] initialEdgeTree :: Vertex -> Tree Edge initialEdgeTree v = case v of Punc LeftPuncture -> Leaf $ Reverse $ IE LeftLeg Punc RightPuncture -> Leaf $ Reverse $ IE RightLeg IV Main -> Node (Node (Leaf $ Reverse $ IE RightLoop) (Node (Leaf $ IE RightLeg) (Leaf $ IE RightLoop) ) ) (Node (Leaf $ Reverse $ IE LeftLoop) (Node (Leaf $ IE LeftLeg) (Leaf $ IE LeftLoop) ) ) initialColoredGraph :: ColoredGraph initialColoredGraph = ColoredGraph { vertices = [Main] , edges = map IE [LeftLoop, RightLoop, LeftLeg, RightLeg] , disks = [Outside, LeftDisk, RightDisk] , imageVertex = id , perimeter = initialPerimeter , morphismLabel = (\m -> case m of Main -> Phi) , edgeTree = initialEdgeTree , objectLabel = objectLabel0 } braid :: State ColoredGraph () braid = do (_,l1,r1) <- addCoev $ IE LeftLoop (_,l2,r2) <- addCoev $ IE LeftLeg (_,r13,l3) <- addCoev r1 (_,_,r4) <- addCoev $ IE RightLoop e1 <- connect (rev l1) r2 LeftDisk e2 <- connect (rev l2) (rev r13) (Cut $ e1) e3 <- connect l3 r4 Outside contract e1 contract e2 contract e3 tensor (Cut $ rev e1) tensor (Cut $ rev e2) tensor (Cut $ rev e3) v <- contract r4 -- At this point we're done with local moves, but we still need to -- modify the final vertex's edge tree. It should look the same as -- the initial edge tree, except left and right are swapped. This is -- somewhat implementation-dependent since I haven't specified -- complete edgeTree behavior for most of the local moves. -- -- TODO: make a method to turn a tree into a specified shape -- -- Current Edgetree: -- -- -- -- + -- | -- +- + -- | | -- | +- + -- | | | -- | | +- + -- | | | | -- | | | +- Reverse (FirstHalf (SecondHalf LeftLoop)) -- | | | | -- | | | `- SecondHalf LeftLeg -- | | | -- | | `- FirstHalf (SecondHalf LeftLoop) -- | | -- | `- TensorE (TensorE (TensorE (Reverse (FirstHalf LeftLoop)) (Reverse (FirstHalf LeftLeg))) (SecondHalf (SecondHalf LeftLoop))) (Reverse (FirstHalf RightLoop)) -- | -- `- + -- | -- +- RightLeg -- | -- `- Reverse (TensorE (TensorE (TensorE (Reverse (FirstHalf LeftLoop)) (Reverse (FirstHalf LeftLeg))) (SecondHalf (SecondHalf LeftLoop))) (Reverse (FirstHalf RightLoop))) associateR v (Node (Node (Leaf (Reverse (FirstHalf (SecondHalf $ IE LeftLoop)))) (Leaf (SecondHalf $ IE LeftLeg)) ) (Leaf (FirstHalf (SecondHalf $ IE LeftLoop))) ) et <- edgeTreeM (IV v) associateR v et return () newInitialEdge :: InitialEdge -> Edge newInitialEdge ie = case ie of RightLeg -> SecondHalf (IE LeftLeg) RightLoop -> FirstHalf (SecondHalf (IE LeftLoop)) LeftLeg -> IE RightLeg LeftLoop -> Reverse (TensorE (TensorE (TensorE (Reverse (FirstHalf (IE LeftLoop))) (Reverse (FirstHalf (IE LeftLeg)))) (SecondHalf (SecondHalf (IE LeftLoop)))) (Reverse (FirstHalf (IE RightLoop)))) finalSN :: ColoredGraph finalSN = execState braid initialColoredGraph finalVertex :: InteriorVertex finalVertex = vertices finalSN !! 0 finalMorphism :: Morphism finalMorphism = morphismLabel finalSN finalVertex finalEdgeTree :: Tree Edge finalEdgeTree = edgeTree finalSN $ IV finalVertex -- testDisk = evalState braid initialColoredGraph -- testPerim = perimeter finalSN testDisk -- testE1 = testPerim !! 0 -- testE2 = rev (testPerim !! 1) -- testV0 = toIV $ (endpoints testE1 finalSN) !! 0 -- testV1 = toIV $ (endpoints testE1 finalSN) !! 1 -- testIndex tc e v = elemIndex e $ flatten $ edgeTree tc $ IV v -- ti1 = testIndex finalSN testE1 testV0 -- ti2 = testIndex finalSN testE2 testV0 -- TESTS -- PASS -- testTC = execState (isolate2 (IE LeftLoop) (IE LeftLeg) Main) initialColoredGraph -- pprint $ edgeTree testTC $ IV Main -- PASS test = execState (isolate2 (rev $ IE RightLoop) (IE LeftLoop) Main) initialColoredGraph -- p = pprint $ edgeTree testTC2 Main -- PASS -- testTC3 = execState (zRotate Main) initialColoredGraph -- PASS -- test = execState (rotateToEnd RightLoop Main) initialColoredGraph -- test = execState ( -- do -- zRotate Main -- zRotate Main -- zRotate Main -- isolateR Main -- ) -- initialColoredGraph -- p x = pprint $ edgeTree x $ IV Main
PaulGustafson/stringnet
Stringnet.hs
mit
28,519
0
25
10,152
8,056
4,206
3,850
526
9
-- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. {-# LANGUAGE QuasiQuotes, OverloadedStrings #-} module Bond.Template.Cpp.Apply_cpp (apply_cpp) where import Data.Text.Lazy (Text) import Text.Shakespeare.Text import Bond.Schema.Types import Bond.Template.TypeMapping import Bond.Template.Util import Bond.Template.Cpp.Apply_h import qualified Bond.Template.Cpp.Util as CPP -- generate the *_apply.cpp file from parsed .bond file apply_cpp :: [Protocol] -> MappingContext -> String -> [Import] -> [Declaration] -> (String, Text) apply_cpp protocols cpp file _imports declarations = ("_apply.cpp", [lt| #include "#{file}_apply.h" #include "#{file}_reflection.h" #{CPP.openNamespace cpp} #{newlineSepEnd 1 (applyOverloads protocols attr body) declarations} #{CPP.closeNamespace cpp} |]) where body = [lt| { return bond::Apply<>(transform, value); }|] attr = [lt||]
innovimax/bond
compiler/Bond/Template/Cpp/Apply_cpp.hs
mit
1,000
0
10
148
155
103
52
13
1
module Main where import Options.Applicative import Data.Maybe import Control.Monad import Numeric import Mortgage data Config = Config { cTotalValue :: Int , cDownPct :: Double , cAPR :: Double , cYears :: Int , cPropertyTax :: Double , cHOAPerMonth :: Maybe Int , cAddtionalPerMonth :: Maybe Int , cAddtionalPerYear :: Maybe (Int, Int) } deriving Show cmdline :: Parser Config cmdline = Config <$> argument auto (metavar "PropertyValue" <> help "Total Property value") <*> argument auto (metavar "DownPct" <> help "Down payment percentage (percentage, i.e: 20)") <*> argument auto (metavar "APR" <> help "APR (percentage, i.e: 5.00)") <*> argument auto (metavar "Years" <> help "loan in years") <*> argument auto (metavar "PropertyTax" <> help "anual property tax rate (percentage, i.e: 1.25)") <*> optional (option auto (long "hoa" <> short 'H' <> metavar "HOA" <> help "HOA per month")) <*> optional (option auto (long "monthlyAdd" <> short 'M' <> metavar "monthlyAdditional" <> help "monthly additional pay towards principal")) <*> ( join . liftA readYearly <$> optional (option str (long "yearlyAdd" <> short 'Y' <> metavar "YearlyAdditional" <> help "Yearly addtional payment at <month> towards principal <amt@month>")) ) readYearly :: String -> Maybe (Int, Int) readYearly yearly = listToMaybe (readDec yearly) >>= \(amt, rest) -> if null rest then Nothing else listToMaybe (readDec (tail rest)) >>= \(mon, _) -> if mon < 1 || mon > 12 then Nothing else return (mon, amt) greet :: Config -> IO () greet (Config value down apr years tax hoa madd yearly) = do let loan = MortgageLoan (realToFrac $ fromIntegral value * (100 - down) / 100) apr years acosts = AdditionalCosts (maybe 0 fromIntegral hoa) (realToFrac (fromIntegral value * tax / 100 / 12)) additional = AdditionalPayments (fmap fromIntegral madd) (fmap (fmap fromIntegral) yearly) Nothing runMortgage loan (Just acosts) (Just additional) >>= putStr . prettyShowAmortizedPayments main :: IO () main = execParser opts >>= greet where opts = info (helper <*> cmdline) ( fullDesc <> progDesc "Mortgage Calculator" <> header "MortgageCalc" )
wangbj/MortageCalc
app/Main.hs
mit
2,358
0
17
582
732
371
361
42
3
module Handler.Sitemap ( getRobotsR , getSitemapR ) where import Import import Yesod.Sitemap import qualified Data.Conduit.List as CL getRobotsR :: Handler RepPlain getRobotsR = do app <- getYesod txts <- if appPrivate app then return [ "User-agent: *" , "Disallow: /" ] else do ur <- getUrlRender return [ "Sitemap: " ++ ur SitemapR , "User-agent: *" , "Disallow: /tutorial-raw/" , "Disallow: /hoogle" ] return $ RepPlain $ toContent $ unlines txts getSitemapR :: Handler TypedContent getSitemapR = sitemap $ runDBSource $ do yield $ SitemapUrl HomeR Nothing (Just Daily) (Just 1.0) yield $ SitemapUrl UsersR Nothing (Just Daily) (Just 0.6) yield $ SitemapUrl RecentContentR Nothing (Just Daily) (Just 0.6) selectSource [] [] $= CL.mapMaybeM (\(Entity _ Profile {..}) -> do mus <- getBy $ UniqueUserSummary profileHandle case mus of Just (Entity _ us) | userSummaryTutcount us > 0 -> return $ Just $ SitemapUrl (UserR profileHandle) Nothing (Just Weekly) (Just 0.5) _ -> return Nothing ) selectKeys [] [] $= CL.mapMaybeM (fmap (fmap goTutorial) . getCanonicalRoute) where goTutorial route = SitemapUrl route Nothing (Just Monthly) (Just 0.6)
fpco/schoolofhaskell.com
src/Handler/Sitemap.hs
mit
1,524
0
21
558
439
215
224
-1
-1
import Prelude hiding ((+),(*),(==)) import qualified Prelude as P default (Int) data Expr = Null | Const Int | Var [Char] | Add Expr Expr | Mult Expr Expr class Mathable a where (+) :: (Mathable b) => a -> b -> Expr (*) :: (Mathable b) => a -> b -> Expr toPoly :: a-> Expr (==) :: (Mathable b) => a-> b-> Bool x + y = Add (toPoly x) (toPoly y) x * y = Mult (toPoly x) (toPoly y) x == y = eval (toPoly x) P.== eval (toPoly y) instance Mathable Expr where toPoly x = x instance Mathable Int where toPoly x = (Const x) instance Mathable Integer where toPoly x = (Const (fromInteger x)) instance Mathable Double where toPoly x = (Const (floor x)) instance Mathable Char where toPoly x = (Var [x]) eval (Var x) = error "Cant' evaluate expressions with variables in them" eval (Const x) = x eval (Add p q) = eval p P.+ eval q eval (Mult p (Const 0)) = 0 eval (Mult (Const 0) q) = 0 eval (Mult p q) = eval p P.* eval q doStuff (Add x y) = "Addition" doStuff _ = "Not addition" --x = doStuff (1 + 2)
mirhagk/assignments
2S03/bonus/dsl/bare.hs
mit
1,027
10
10
242
533
278
255
34
1
----------------------------------------------------------------------------- -- | -- Module : Reader.Parser.Component -- License : MIT (see the LICENSE file) -- Maintainer : Felix Klein ([email protected]) -- -- Parser for the MAIN section. -- ----------------------------------------------------------------------------- module Reader.Parser.Component ( componentParser ) where ----------------------------------------------------------------------------- import Text.Parsec ( (<|>) , many , char , sepBy , oneOf ) import Text.Parsec.String ( Parser ) import Text.Parsec.Token ( GenLanguageDef(..) , makeTokenParser , braces , reservedOp , whiteSpace , reserved ) import Data.Types ( SignalDecType(..) ) import Data.Expression ( Expr(..) , ExprPos(..) ) import Reader.Parser.Data ( globalDef ) import Reader.Parser.Utils ( identifier , getPos ) import Reader.Parser.Expression ( exprParser ) import Data.Maybe ( catMaybes ) import Control.Monad ( void , liftM ) ----------------------------------------------------------------------------- data Component = Component { inputs :: [SignalDecType String] , outputs :: [SignalDecType String] , initially :: [Expr String] , preset :: [Expr String] , requirements :: [Expr String] , assumptions :: [Expr String] , invariants :: [Expr String] , guarantees :: [Expr String] } ----------------------------------------------------------------------------- -- | Parses the MAIN section of a specification file. It returns: -- -- * the input signals of the specification -- -- * the output signals of the specification -- -- * the initial configuration of the inputs -- -- * the initial configuration of the outputs -- -- * the requirements of the specification -- -- * the assumptions of the specification -- -- * the invariants of the specification -- -- * the guarantees of the specification componentParser :: Parser ([SignalDecType String], [SignalDecType String], [Expr String], [Expr String], [Expr String], [Expr String], [Expr String], [Expr String]) componentParser = do keyword "MAIN" xs <- br $ many $ componentContentParser Component { inputs = [] , outputs = [] , initially = [] , preset = [] , requirements = [] , assumptions = [] , invariants = [] , guarantees = [] } return ( concatMap inputs xs , concatMap outputs xs , concatMap initially xs , concatMap preset xs , concatMap requirements xs , concatMap assumptions xs , concatMap invariants xs , concatMap guarantees xs ) where tokenparser = makeTokenParser globalDef { opStart = oneOf "=;" , opLetter = oneOf "=;" , reservedOpNames = [ "=", ";" ] , reservedNames = [ "MAIN" , "INPUTS" , "OUTPUTS" , "INITIALLY" , "PRESET" , "ASSUME" , "ASSUMPTIONS" , "REQUIRE" , "REQUIREMENTS" , "ASSERT" , "INVARIANTS" , "GUARANTEE" , "GUARANTEES" ] } componentContentParser c = (sectionParser "INPUTS" signalParser >>= \x -> return c { inputs = x }) <|> (sectionParser "OUTPUTS" signalParser >>= \x -> return c { outputs = x }) <|> (sectionParser "INITIALLY" exprParser >>= \x -> return c { initially = x }) <|> (sectionParser "PRESET" exprParser >>= \x -> return c { preset = x }) <|> (sectionParser "REQUIRE" exprParser >>= \x -> return c { requirements = x }) <|> (sectionParser "REQUIREMENTS" exprParser >>= \x -> return c { requirements = x }) <|> (sectionParser "ASSUME" exprParser >>= \x -> return c { assumptions = x }) <|> (sectionParser "ASSUMPTIONS" exprParser >>= \x -> return c { assumptions = x }) <|> (sectionParser "ASSERT" exprParser >>= \x -> return c { invariants = x }) <|> (sectionParser "INVARIANTS" exprParser >>= \x -> return c { invariants = x }) <|> (sectionParser "GUARANTEE" exprParser >>= \x -> return c { guarantees = x }) <|> (sectionParser "GUARANTEES" exprParser >>= \x -> return c { guarantees = x }) signalParser = do (x,pos) <- identifier (~~) typedBusParser x pos <|> busParser x pos <|> return (SDSingle (x,pos)) busParser x pos = do ch '['; (~~) e <- exprParser ch ']'; p <- getPos; (~~) return $ SDBus (x,(ExprPos (srcBegin pos) p)) e typedBusParser x pos = do (y,p) <- identifier (~~) return $ SDEnum (y,p) (x,pos) sectionParser x p = do keyword x xs <- br $ sepBy (nonEmptyParser p) $ rOp ";" return $ catMaybes xs nonEmptyParser p = liftM return p <|> return Nothing ch = void . char br = braces tokenparser rOp = reservedOp tokenparser (~~) = whiteSpace tokenparser keyword = void . reserved tokenparser -----------------------------------------------------------------------------
reactive-systems/syfco
src/lib/Reader/Parser/Component.hs
mit
5,317
0
23
1,555
1,338
749
589
137
1
-- | Translation of Agda internal @ClauseBody@ to the target logic. {-# LANGUAGE CPP #-} {-# LANGUAGE UnicodeSyntax #-} module Apia.Translation.ClauseBody ( cBodyToFormula , cBodyToTerm , dropProofTermOnCBody ) where ------------------------------------------------------------------------------ import Apia.Prelude import Agda.Syntax.Common ( Nat ) import Agda.Syntax.Internal ( Abs(Abs) , ClauseBody , ClauseBodyF(Bind, Body) ) import Agda.Utils.Impossible ( Impossible(Impossible), throwImpossible ) import Apia.FOL.Types ( LFormula, LTerm ) import Apia.Monad.Base ( T ) import Apia.Monad.Reports ( reportSLn ) import Apia.Translation.Terms ( agdaTermToFormula , agdaTermToTerm ) import Apia.Utils.AgdaAPI.DeBruijn ( ChangeIndex(changeIndex), varToIndex ) import Apia.Utils.AgdaAPI.EtaExpansion ( EtaExpandible(etaExpand) ) #include "undefined.h" ------------------------------------------------------------------------------ -- | Translate an Agda internal 'ClauseBody' to a target logical -- formula. cBodyToFormula ∷ ClauseBody → T LFormula cBodyToFormula (Body term) = etaExpand term >>= agdaTermToFormula cBodyToFormula (Bind (Abs _ cBody)) = cBodyToFormula cBody cBodyToFormula _ = __IMPOSSIBLE__ -- | Translate an Agda internal 'ClauseBody' to a logical term. cBodyToTerm ∷ ClauseBody → T LTerm -- 16 July 2012. N.B. We don't η-expand the term before the -- translation (we don't have a test case where it is neeed). cBodyToTerm (Body term) = agdaTermToTerm term cBodyToTerm (Bind (Abs _ cBody)) = cBodyToTerm cBody cBodyToTerm _ = __IMPOSSIBLE__ dropProofTermOnCBodyIndex ∷ ClauseBody → String → Nat → ClauseBody dropProofTermOnCBodyIndex (Bind (Abs x1 cBody)) x2 index = if x1 == x2 then changeIndex cBody index -- We drop the bind and rename the -- variables inside the body. else Bind (Abs x1 $ dropProofTermOnCBodyIndex cBody x2 index) dropProofTermOnCBodyIndex _ _ _ = __IMPOSSIBLE__ -- To drop the binding on a proof term in a @ClauseBody@, -- -- e.g. drop the binding on @Nn : N n@ where @D : Set@, @n : D@ and @N -- : D → Set@. -- -- We know that the bounded variable is a proof term from the -- invocation to this function. -- | Drop a proof term from an Agda internal 'ClauseBody'. dropProofTermOnCBody ∷ ClauseBody → String → T ClauseBody dropProofTermOnCBody cBody x = do let index ∷ Nat index = varToIndex cBody x reportSLn "drop" 20 $ "The index is: " ++ show index return $ dropProofTermOnCBodyIndex cBody x index
asr/apia
old/Translation/ClauseBody.hs
mit
2,636
0
10
515
483
274
209
41
2
----------------------------------------------------------------------------- -- | -- Module : Control.AFSM.Event -- Copyright : (c) Hanzhong Xu, Meng Meng 2016, -- License : MIT License -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- module Control.AFSM.Event ( extractEvents )where import Control.Applicative import Control.Monad import Control.AFSM.CoreType import Control.AFSM.SMFunctor -- | 'Event' type, there are 4 different events: event a, no event, error event string and exit event. -- data Event a = Event a | NoEvent | ErrEvent String | ExitEvent deriving (Show, Eq, Ord) -- | extract [a] from [Event a] extractEvents :: [Event a] -> [a] extractEvents [] = [] extractEvents (x:xs) = case x of Event a -> a:ys NoEvent -> ys ErrEvent s -> [] ExitEvent -> [] where ys = (extractEvents xs) instance Functor Event where fmap f (Event a) = Event (f a) fmap _ NoEvent = NoEvent fmap _ (ErrEvent s) = (ErrEvent s) fmap _ ExitEvent = ExitEvent instance Applicative Event where pure a = Event a (<*>) (Event f) m = fmap f m (<*>) (ErrEvent s0) (ErrEvent s1) = ErrEvent $ s0 ++ "," ++ s1 (<*>) (ErrEvent s0) _ = ErrEvent s0 (<*>) ExitEvent _ = ExitEvent (<*>) NoEvent _ = NoEvent instance Monad Event where return = pure (>>=) (Event a) f = f a (>>=) NoEvent _ = NoEvent (>>=) (ErrEvent s) _ = (ErrEvent s) (>>=) ExitEvent _ = ExitEvent instance SMFunctor Event where smexec sm NoEvent = (sm, NoEvent) smexec sm (ErrEvent s) = (sm, ErrEvent s) smexec sm ExitEvent = (sm, ExitEvent) smexec (SM (TF f) s) (Event a) = (sm', Event b) where (sm', b) = f s a
PseudoPower/AFSM
src/Control/AFSM/Event.hs
mit
1,837
0
10
436
550
298
252
38
4
{-# LANGUAGE RecordWildCards, DeriveDataTypeable #-} module Main where import qualified CPython as Py import qualified CPython.Types.Module as Py import qualified CPython.Protocols.Object as Py import qualified CPython.Types.Capsule as PyCapsule import qualified CPython.Types.Dictionary as PyDict import qualified CPython.Types.Tuple as PyTuple import qualified CPython.Types.Unicode as PyUnicode import qualified CPython.Types.Exception as PyExc import Data.Text hiding(take) import Emitter import Embed import System.Console.CmdArgs import System.Exit(exitSuccess) import Foreign.StablePtr import Foreign.Ptr import Foreign.C.String data Arguments = Arguments {plugin :: FilePath} deriving (Show, Data, Typeable) sample = Arguments{plugin = def &= help "The Python Plugin to load"} &= summary "Example Main Program" main :: IO () main = do Arguments {..} <- cmdArgs sample registerTheEmbededModule handle pyExceptionHandlerWithoutPythonTraceback Py.initialize handle pyExceptionHandler $ runPlugin plugin handle pyExceptionHandlerWithoutPythonTraceback Py.finalize where pyExceptionHandler :: PyExc.Exception -> IO () pyExceptionHandler exception = handle pyExceptionHandlerWithoutPythonTraceback $ do tracebackModule <- Py.importModule "traceback" print_exc <- PyUnicode.toUnicode "print_exception" >>= Py.getAttribute tracebackModule kwargs <- PyDict.new args <- case PyExc.exceptionTraceback exception of Just tb -> PyTuple.toTuple [PyExc.exceptionType exception, PyExc.exceptionValue exception, tb] _ -> PyTuple.toTuple [PyExc.exceptionType exception, PyExc.exceptionValue exception] _ <- Py.call print_exc args kwargs return () pyExceptionHandlerWithoutPythonTraceback :: PyExc.Exception -> IO () pyExceptionHandlerWithoutPythonTraceback exception = putStrLn "Unexpected Python exception (Please report a bug)" runPlugin :: FilePath -> IO () runPlugin plugin = do pyModule <- Py.importModule $ pack plugin emitterCapsule <- capsulate Emitter attrName <- PyUnicode.toUnicode "emit" args <- PyTuple.toTuple [] runArgs <- PyTuple.toTuple [Py.toObject emitterCapsule] kwargs <- PyDict.new pyPrinter <- PyUnicode.toUnicode "Printer" >>= Py.getAttribute pyModule >>= \classObject -> Py.call classObject args kwargs _ <- PyUnicode.toUnicode "load" >>= Py.getAttribute pyPrinter >>= \classObject -> Py.call classObject args kwargs _ <- PyUnicode.toUnicode "run" >>= Py.getAttribute pyPrinter >>= \classObject -> Py.call classObject runArgs kwargs putStrLn "DEBUG: RunPlugin returns" return ()
zsedem/haskell-python
app/Main.hs
mit
2,669
0
17
452
683
347
336
54
2
module Language.Rebeca.Fold.Erlang.Refinement where import Control.Monad.Reader import Control.Monad.State import Data.Either (either) import Data.Maybe (fromMaybe) import Language.Fold import Language.Erlang.Builder import Language.Erlang.Syntax import qualified Language.Rebeca.Absrebeca as R import Language.Rebeca.Algebra import Language.Rebeca.Fold type Compiler = ReaderT CompilerConf (State CompilerState) data CompilerConf = CompilerConf { moduleName :: String , rtfactor :: Integer , monitor :: Bool } initialConf = CompilerConf { moduleName = "" , rtfactor = 0 , monitor = False } data CompilerState = CompilerState { env :: [(String, String)] , kr :: [String] , sv :: [String] , lv :: [String] } initialState = CompilerState { env = [] , kr = [] , sv = [] , lv = [] } setEnvVars names = lift get >>= \rec -> put (rec { env = names }) setKnownRebecs names = lift get >>= \rec -> put (rec { kr = names }) setStateVars names = lift get >>= \rec -> put (rec { sv = names }) setLocalVars names = lift get >>= \rec -> put (rec { lv = [] }) addLocalVar name = lift get >>= \rec -> put (rec { lv = name : (lv rec) }) getModuleName :: Compiler String getModuleName = ask >>= return . moduleName getRtFactor :: Compiler Integer getRtFactor = ask >>= return . rtfactor getMonitor :: Compiler Bool getMonitor = ask >>= return . monitor getEnvVars = lift get >>= return . env getKnownRebecs = lift get >>= return . kr getStateVars = lift get >>= return . sv getLocalVars = lift get >>= return . lv defaultVal "int" = "0" defaultVal "time" = "0" defaultVal "boolean" = "false" defaultVal s = error ("no default value for " ++ s) cast :: Exp -> String -> Exp cast val tn | tn == "int" || tn == "time" = Apply (atomE "list_to_integer") [val] | otherwise = val refinementAlgebra = RebecaAlgebra { identF = \id -> return id , modelF = \envs rcs mai -> do envs' <- sequence envs setEnvVars envs' rcs' <- sequence rcs mai' <- mai moduleName <- getModuleName rtfactor <- getRtFactor return (Program (Module moduleName) [Export ["main/1"]] [] [Define "RT_FACTOR" (num rtfactor)] (concat rcs' ++ [mai'])) , envVarF = \tp -> tp , reactiveClassF = \id _ kr sv msi ms -> do setKnownRebecs [] setStateVars [] id' <- id kr' <- kr setKnownRebecs kr' sv' <- sv setStateVars (map (\(_, id, _) -> id) sv') msi' <- msi ms' <- sequence ms let initialsv = Assign (varP "StateVars") (Apply (moduleE "dict" "from_list") [listE (map (\(_, i, d) -> tupleE [atomE i, either atomE (\x -> x) d]) sv')]) initiallv = Assign (varP "LocalVars") (Apply (moduleE "dict" "new") []) recurs = Apply (atomE id') [varE "Env", varE "InstanceName", varE "KnownRebecs", varE "NewStateVars"] return ([ Function id' [varP "Env", varP "InstanceName"] $ Receive [ Match (tupleP (map varP kr')) Nothing $ Apply (atomE id') [ varE "Env", varE "InstanceName" , Apply (moduleE "dict" "from_list") [listE (map (\k -> tupleE [atomE k, varE k]) kr')] ]] , Function id' [varP "Env", varP "InstanceName", varP "KnownRebecs"] $ Seq (Seq initialsv (Seq initiallv (Assign (tupleP [varP "NewStateVars", varP "_"]) (Receive [msi'])))) recurs , Function id' [varP "Env", varP "InstanceName", varP "KnownRebecs", varP "StateVars"] $ Seq (Seq initiallv (Assign (tupleP [varP "NewStateVars", varP "_"]) (Receive ms'))) recurs]) , noKnownRebecsF = return [] , knownRebecsF = \tvds -> do tvds' <- sequence tvds return (map (\(_, id, _) -> id) tvds') , noStateVarsF = return [] , stateVarsF = \tvds -> sequence tvds >>= return , msgSrvInitF = \tps stms -> do setLocalVars [] tps' <- sequence tps stms' <- sequence stms let patterns = tupleP [tupleP [varP "Sender", varP "TT", varP "DL"], atomP "initial", tupleP (map (varP . snd) tps')] pred = InfixExp OpLOr (InfixExp OpEq (varE "DL") (atomE "inf")) (InfixExp OpLEq (Apply (moduleE "rebeca" "now") []) (varE "DL")) return (Match patterns Nothing (Case pred [ Match (atomP "true") Nothing (formatReceive "initial" $ apply $ reverse stms') , Match (atomP "false") Nothing (formatDrop "initial" retstm)])) , msgSrvF = \id tps stms -> do setLocalVars [] id' <- id tps' <- sequence tps stms' <- sequence stms let patterns = tupleP [tupleP [varP "Sender", varP "TT", varP "DL"], atomP id', tupleP (map (varP . snd) tps')] pred = InfixExp OpLOr (InfixExp OpEq (varE "DL") (atomE "inf")) (InfixExp OpLEq (Apply (moduleE "rebeca" "now") []) (varE "DL")) return (Match patterns Nothing (Case pred [ Match (atomP "true") Nothing (formatReceive id' $ apply $ reverse stms') , Match (atomP "false") Nothing (formatDrop id' retstm)])) , vDeclAssignF = \id _ -> id , vDeclF = \id -> id , typedVarDeclF = \tn id -> do tn' <- tn id' <- id return (tn', id', Left (defaultVal tn')) , typedVarDeclAssF = \tn id exp -> do tn' <- tn id' <- id exp' <- exp return (tn', id', Right exp') , typedParameterF = \tn id -> tn >>= \tn' -> id >>= \id' -> return (tn', id') , basicTypeIntF = return "int" , basicTypeTimeF = return "time" , basicTypeBooleanF = return "boolean" , builtInF = \bt -> bt , classTypeF = \id -> id , assF = \id aop exp -> do id' <- id aop' <- aop exp' <- exp sv <- getStateVars lv <- getLocalVars let assignment | id' `elem` sv = tupleE [Apply (moduleE "dict" "store") [atomE id', exp', varE "StateVars"], varE "LocalVars"] | id' `elem` lv = tupleE [varE "StateVars", Apply (moduleE "dict" "store") [atomE id', exp', varE "LocalVars"]] | otherwise = error $ "unknown variable name " ++ id' return (stm assignment) , localF = \tvd -> do (_, i, d) <- tvd addLocalVar i return (stm $ tupleE [varE "StateVars", Apply (moduleE "dict" "store") [atomE i, either atomE id d, varE "LocalVars"]]) , callF = \id0 id exps aft dea -> do id0' <- id0 id' <- id exps' <- sequence exps aft' <- aft dea' <- dea kr <- getKnownRebecs let target | id0' == "self" = atomE "self()" | id0' `elem` kr = Apply (moduleE "dict" "fetch") [atomE id0', varE "KnownRebecs"] | otherwise = varE id0' -- TODO: this is unsafe, we need to store formal parameters of the method in state as well, and check let deadline = fromMaybe (atomE "inf") dea' return $ stm $ case aft' of -- TODO lookup id0 Nothing -> Seq (Apply (moduleE "rebeca" "send") [target, atomE id', tupleE exps', deadline]) retstm Just aft'' -> Seq (Apply (moduleE "rebeca" "sendafter") [aft'', target, atomE id', tupleE exps', deadline]) retstm , delayF = \exp -> exp >>= \exp' -> return (stm $ Seq (Apply (moduleE "rebeca" "delay") [exp']) retstm) , selF = \exp cs elseifs els -> do exp' <- exp cs' <- cs elseifs' <- sequence elseifs els' <- els let true = Match (atomP "true") Nothing cs' false = foldr (\f x -> f x) els' elseifs' return (stm $ Case exp' [true, false]) , singleCompStmF = \stm -> stm >>= \stm' -> return (Call stm' params) , multCompStmF = \stms -> sequence stms >>= \stms' -> return $ case stms' of [] -> retstm [stm] -> Call stm params _ -> apply $ reverse stms' , noAfterF = return Nothing , withAfterF = \exp -> exp >>= \exp' -> return (Just exp') , noDeadlineF = return Nothing , withDeadlineF = \exp -> exp >>= \exp' -> return (Just exp') , elseifStmF = \exp cs -> do exp' <- exp cs' <- cs let fn :: Match -> Match fn m = Match (atomP "false") Nothing (Case exp' [Match (atomP "true") Nothing cs', m]) return fn , emptyElseStmF = return (Match (atomP "false") Nothing retstm) , elseStmF = \cs -> cs >>= \cs' -> return (Match (atomP "false") Nothing cs') , lorF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpLOr exp0' exp') , landF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpLAnd exp0' exp') , bitorF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (atomE "bitor") , bitexorF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (atomE "bitexor") , bitandF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (atomE "bitand") , eqF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpEq exp0' exp') , neqF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpNEq exp0' exp') , lthenF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpLT exp0' exp') , grthenF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpGT exp0' exp') , leF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpLEq exp0' exp') , geF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpGEq exp0' exp') , leftF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (atomE "left") , rightF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (atomE "right") , plusF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpAdd exp0' exp') , minusF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpSub exp0' exp') , timesF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpMul exp0' exp') , divF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpDiv exp0' exp') , modF = \exp0 exp -> exp0 >>= \exp0' -> exp >>= \exp' -> return (InfixExp OpMod exp0' exp') , expcoercionF = \exp -> exp >>= \exp' -> return (atomE "expcoercion") , nondetF = \exps -> sequence exps >>= \exps' -> return (Apply (moduleE "rebeca" "nondet") [listE exps']) , preopF = \uop exp -> uop >>= \uop' -> exp >>= \exp' -> return (Call (ExpVal uop') exp') , nowF = return (Apply (moduleE "rebeca" "now") []) , constF = \con -> con >>= \con' -> return (ExpVal con') , varF = \ids -> do ids' <- sequence ids sv <- getStateVars kr <- getKnownRebecs lv <- getLocalVars env <- getEnvVars case ids' of "self":[id] -> return (Apply (moduleE "dict" "fetch") [atomE id, varE "StateVars"]) [id] -> if id `elem` sv then return (Apply (moduleE "dict" "fetch") [atomE id, varE "StateVars"]) else if id `elem` kr then return (Apply (moduleE "dict" "fetch") [atomE id, varE "KnownRebecs"]) else if id `elem` lv then return (Apply (moduleE "dict" "fetch") [atomE id, varE "LocalVars"]) else if id `elem` (map snd env) then return (Apply (moduleE "dict" "fetch") [atomE id, varE "Env"]) else return (varE id) -- TODO: not safe, needs to lookup from formal parameters of method _ -> error "no variable or functionality not implemented" , constantIntF = \i -> return (num i) , constantTrueF = return (atom "true") , constantFalseF = return (atom "false") , unaryPlusF = return (atom "+") , unaryNegativeF = return (atom "-") , unaryComplementF = error "alg: unaryComplementF" , unaryLogicalNegF = return (atom "not") , opAssignF = return "=" , opAssignMulF = error "alg: opAssignMulF" , opAssignDivF = error "alg: opAssignDivF" , opAssignModF = error "alg: opAssignModF" , opAssignAddF = error "alg: opAssignAddF" , opAssignSubF = error "alg: opAssignSubF" , mainF = \ins -> do ins' <- sequence ins envs <- getEnvVars let env = Assign (varP "Env") (Apply (moduleE "dict" "from_list") [listE $ map (\e -> tupleE [atomE (snd e), cast (varE (snd e)) (fst e)]) envs]) spawns = foldr1 Seq (map fst ins') links = foldr1 Seq (map (fst . snd) ins') initials = foldr1 Seq (map (snd . snd) ins') return (Function "main" [listP $ (map (varP . snd) envs)] (Seq env (Seq spawns (Seq links initials)))) , instanceDeclF = \tvd vds exps -> do tvd' <- tvd vds' <- sequence vds exps' <- sequence exps kr <- getKnownRebecs let (tn, id, de) = tvd' rebecName = id fn = FunAnon [] (Apply (atomE tn) [varE "Env", Apply (atomE "list_to_atom") [stringE (rebecName)]]) -- TODO: rebecName is wrong spawn = Assign (varP (rebecName)) (Call (atomE "spawn") fn) link = Send (varE (rebecName)) (tupleE (map varE vds')) initial = Apply (moduleE "rebeca" "send") [varE (rebecName), atomE "initial"] return (spawn,(link,initial)) } formatReceive msgsrv e = Seq (Apply (moduleE "io" "format") [stringE $ "~s." ++ msgsrv ++ "~n", listE [varE "InstanceName"]]) e formatDrop msgsrv e = Seq (Apply (moduleE "io" "format") [stringE $ "dropping ~s." ++ msgsrv ++ "~n", listE [varE "InstanceName"]]) e params = tupleE [varE "StateVars", varE "LocalVars"] stm = FunAnon [tupleP [varP "StateVars", varP "LocalVars"]] apply = foldr Call params retstm = tupleE [varE "StateVars", varE "LocalVars"] runRefine :: R.Model -> Compiler Program runRefine model = fold refinementAlgebra model translateRefinement :: String -> Integer -> Bool -> R.Model -> Program translateRefinement modelName rtfactor monitor model = evalState (runReaderT (runRefine model) (initialConf {moduleName = modelName, rtfactor = rtfactor, monitor = monitor })) initialState
arnihermann/timedreb2erl
src/Language/Rebeca/Fold/Erlang/Refinement.hs
mit
14,072
0
28
3,915
5,510
2,860
2,650
264
10
module CellularAutomata2D ( -- * Rules Rule(..), -- * Torus shaped space Torus(..), getCell, setCell, setCells, remapIndex, getSpaceSize, initSpace, initSpaceIO, update, -- * Space Utils forSpace, -- * Initializing Spaces randomSpace, initSpaceWithCells, initBoolSpaceWithCells, fromMatrix, -- * Helper for Rules moorIndexDeltas, neumannIndexDeltas, makeTotalMoorRule, choice, count, countCells, chooseWithPropability, makeReversibleRule, makeVotingRule, makeVotingMoorRule) where import System.Random (randomRIO, Random) import Data.Array (listArray, bounds, (!), Array, (//)) import Control.Arrow import Control.Monad (forM_) import Control.Applicative ((<$>)) -------------------------------- General Concepts ------------------------------ -- | A Rule is a function that returns a new cell value for an old state. -- The new cell value is in the IO Monad so that you can implement nondeterministic -- (stochastic) automata. The neighborhood is specified by a list of offsets from the cell -- coordinate. data Rule a = Rule { ruleNeighborhoodDeltas :: [(Int, Int)] , ruleFunction :: a -> [a] -> IO a } ------------------------------- Torus shaped space ------------------------- -- | A Torus is basically a plane with top and bottom connected as well as left and right connected. newtype Torus a = Torus { getCells :: Array (Int, Int) a } deriving (Show, Read, Eq) instance Functor Torus where fmap f = Torus . fmap f . getCells -- | Get a cell at a coordinate in the space. getCell :: Torus a -> (Int, Int) -> a getCell space index = getCells space ! remapIndex space index -- | Set a cell at a coordinate in the space to a new value. setCell :: Torus a -> (Int, Int) -> a -> Torus a setCell space index newState = Torus $ getCells space // [(remapIndex space index, newState)] -- | Set a bunch of cells specified by there coordinate to new values. setCells :: Torus a -> [((Int, Int), a)] -> Torus a setCells space cells = Torus $ getCells space // map (first (remapIndex space)) cells -- | wrap the index around the edges of the space remapIndex :: Torus a -> (Int, Int) -> (Int, Int) remapIndex space (row, col) = (row `mod` h, col `mod` w) where (h, w) = getSpaceSize space -- | Get the dimensions of the space rows * columns getSpaceSize :: Torus a -> (Int, Int) getSpaceSize (Torus space) = (maxRow + 1, maxCol + 1) where (_, (maxRow, maxCol)) = bounds space -- | Initializes the space using a given function that takes a coordinate -- and returns the cell value in the IO Monad (so you can easily e.g. generate -- a random space configuration). initSpaceIO :: (Int, Int) -> ((Int, Int) -> IO a) -> IO (Torus a) initSpaceIO (h, w) initFn = Torus . listArray ((0, 0), (h - 1, w - 1)) <$> sequence [initFn (row, col) | row <- [0..h-1], col <- [0..w-1]] -- | Initializes the space using a pure function witch take the coordinate of -- the cell and returns the cell value initSpace :: (Int, Int) -> ((Int, Int) -> a) -> Torus a initSpace (h, w) initFn = Torus $ listArray ((0, 0), (h - 1, w - 1)) [initFn (row, col) | row <- [0..h-1], col <- [0..w-1]] -- | Updates a given space by one generation using a given rule. update :: Rule a -> Torus a -> IO (Torus a) update rule space = initSpaceIO (getSpaceSize space) updateCell where updateCell (row, col) = ruleFunction rule self friends where friends = map (\(dr, dc) -> getCell space (row + dr, col + dc)) (ruleNeighborhoodDeltas rule) self = getCell space (row, col) ----------------------------------- Space Utils ------------------------------- -- | Iterates over a given space and calls a given function on the -- coordinate and value of each cells. -- This is done in row major order. forSpace :: Torus a -> ((Int, Int) -> a -> IO ()) -> IO () forSpace space fn = forM_ [0..spaceHeight - 1] $ \row -> forM_ [0..spaceWidth - 1] $ \col -> fn (row, col) (getCell space (row, col)) where (spaceHeight, spaceWidth) = getSpaceSize space -------------------------------- Initializing Spaces ------------------------------ -- | Initializes a space of a given shape using a list of possible cells. -- Each cell is randomly chosen from the list. -- You might want to duplicate elements in the list to adjust the frequency's -- (probability to be chosen) of the cell values. randomSpace :: (Int, Int) -> [a] -> IO (Torus a) randomSpace shape cellStateDist = initSpaceIO shape $ const $ choice cellStateDist -- | Initializes a space with a default background cell value and a few cells -- at given coordinates with individual values. initSpaceWithCells :: (Int, Int) -> a -> [((Int, Int), a)] -> Torus a initSpaceWithCells shape defaultValue = setCells (initSpace shape (const defaultValue)) -- | Specialized version of initSpaceWithDefault for int spaces with 0 as the background. initBoolSpaceWithCells :: (Int, Int) -> [(Int, Int)] -> Torus Bool initBoolSpaceWithCells shape cells = initSpaceWithCells shape False (zip cells (repeat True)) -- | creates a new space from a grid of cells represented as a list of lists fromMatrix :: [[a]] -> Torus a fromMatrix mtx = initSpaceWithCells (length mtx, length $ head mtx) undefined cellsOfMatrix where cellsOfMatrix = concat $ zipWith makeRow [0..] mtx makeRow rowIndex = zipWith (\colIndex cell -> ((rowIndex, colIndex), cell)) [0..] ----------------------------------- Helper for Rules ---------------------------------- -- | The Moor neighborhood, witch is used in a lot cellular automata like -- conway's game of life. moorIndexDeltas :: [(Int, Int)] moorIndexDeltas = [(dy, dx) | dx <- [-1..1], dy <- [-1..1], not (dx == 0 && dy == 0)] -- | The von Neunmann neighborhood. neumannIndexDeltas :: [(Int, Int)] neumannIndexDeltas = [(dy, dx) | dx <- [-1..1], dy <- [-1..1], (dx == 0) /= (dy == 0)] -- | Creates a life like automata from a list of neighborhood sizes in witch -- a new cell is born and a list of neighborhood sizes where the cell stays -- alive. e.g. the game of life is makeTotalMoorRule [2,3] [3] makeTotalMoorRule :: [Int] -> [Int] -> Rule Bool makeTotalMoorRule getBorn stayAlive = Rule moorIndexDeltas (\self neighborhood -> return $ count neighborhood `elem` (if self then stayAlive else getBorn)) -- | Count the number of True (on/alive cells) in the given neighborhood count :: [Bool] -> Int count = countCells True -- | Count the number of cell states in the given neighbprhood countCells :: Eq a => a -> [a] -> Int countCells x = length . filter (== x) -- | Selects one random element from a list. -- The list has to be finite. -- O(n) choice :: [a] -> IO a choice xs = (xs !!) `fmap` randomRIO (0, length xs - 1) -- | Return the first element a with propability p otherwise return b chooseWithPropability :: Double -> a -> a -> IO a chooseWithPropability p a b = (\x -> if x < p then a else b) <$> randomRIO (0, 1) -- | Creates a reversible rule from a non reversible rule by remembering the state and always -- xoring the new state with the old one. makeReversibleRule :: Rule Int -> Rule (Int, Int) makeReversibleRule rule = Rule (ruleNeighborhoodDeltas rule) (\(c', c) cs -> ruleFunction rule c (map snd cs) >>= \nextC -> return (c, if c' /= nextC then 1 else 0)) -- | Creates a "voting rule", that is a rule for boolean states that only depends on the -- number of "on" or True cells in the neighborhood and the cell itself makeVotingRule :: [(Int, Int)] -> (Int -> Bool) -> Rule Bool makeVotingRule indexDeltas p = Rule indexDeltas $ \self neighborhood -> return $ p (count $ self : neighborhood) makeVotingMoorRule :: (Int -> Bool) -> Rule Bool makeVotingMoorRule = makeVotingRule moorIndexDeltas
orion-42/cellular-automata-2d
CellularAutomata2D.hs
mit
7,748
0
14
1,499
2,106
1,183
923
-1
-1
module TileRider.DrawTile where import qualified Graphics.UI.SDL.Types as SDL.T import Control.Monad import Control.Applicative import Data.Maybe import Foreign.C.Types import SDL.Geometry import SDL.Draw import Directional import Geometry import TileRider.Drag import TileRider.SlidingGrid import TileRider.SmoothSlidingGrid import TileRider.GameInput import TileRider.GameState import TileRider.GameTile import TileRider.Grid import qualified TileRider.Grid as Grid import Utils.Utils drawTileAt :: SDL.T.Renderer -> GeomPoint -> GeomPoint -> GameTile -> IO () drawTileAt r scale@(w, h) origin@(x, y) (GameTile path role) = case role of PathTile -> f Green GoalTile -> f Blue SpawnTile -> f Red NothingTile -> f Yellow where f color = do setColor r color fillRectangle r target setColor r Black sequenceRect (drawTilePaths r scale origin <*> path) target = SDL.Geometry.toRect x y w h drawTilePaths :: SDL.T.Renderer -> GeomPoint -> GeomPoint -> Rectangular (Bool -> IO ()) drawTilePaths r scale origin = f <$> center <*> outer where scale' = pairMap (`quot` 2) scale center = pure (origin + scale') outer = (+) <$> center <*> ((* scale') <$> (fmap pairToTuple signedVectors)) f x x' b = when b $ drawLine r x x' drawTile :: SDL.T.Renderer -> GridDrawInfo CInt -> TileZipper (SmoothSliding GameTile) -> IO () drawTile r (GridDrawInfo scale origin) t = case tile of EmptyTile -> return () SlidingTile x -> f x FixedTile x -> f x where tile = gridItem t coord = pairMap fromIntegral $ gridCoord t f (SmoothSliding offset gameTile) = drawTileAt r scale origin' gameTile where origin' = (scale * coord) + origin + offset drawTiles :: RealFrac a => SDL.T.Renderer -> GridDrawInfo CInt -> Maybe (PartialMoveResult a) -> TileZipper GameTile -> IO () drawTiles r drawInfo moveM z = gridSequenceFrom (drawTile r drawInfo) szz'' where szz'' = fromMaybe (error "wtf, there's no (0, 0) tile?") (Grid.moveTo SDL.Geometry.zero sz') sz' = case moveM of Nothing -> sz Just move@(PartialMoveResult dir _ coord) -> fromMaybe (error "the partial move failed!") szM' where szM' = atCoord (partialSlide dir (toGeomPoint $ offsetAmount_ move)) (pairToTuple coord) sz sz = toSmoothSliding z drawPlayer :: RealFrac a => SDL.T.Renderer -> GridDrawInfo CInt -> Maybe (PartialMoveResult a) -> Point Int -> IO () drawPlayer r (GridDrawInfo scale origin) move p = do setColor r Black fillRectangle r target where (x0, y0) = origin + (toGeomPointInt p * scale) + pairMap (`quot` 4) scale + offset (w', h') = pairMap (`quot` 2) scale target = SDL.Geometry.toRect x0 y0 w' h' offset = toGeomPoint (offsetAmount move) drawGrid :: SDL.T.Renderer -> GridDrawInfo CInt -> GridInput -> GridState -> IO () drawGrid r drawInfo (GridInput _ partialMove) (GridState player _ tiles) = do drawTiles r drawInfo tileMove tiles drawPlayer r drawInfo playerMove player where (tileMove, playerMove) = case partialMove of Nothing -> (Nothing, Nothing) Just (PartialMoveResult _ _ coord) -> if pairToTuple coord == player then (Nothing, partialMove) else (partialMove, Nothing) offsetAmount :: Num a => Maybe (PartialMoveResult a) -> Point a offsetAmount = maybe SDL.Geometry.zero offsetAmount_ offsetAmount_ :: Num a => PartialMoveResult a -> Point a offsetAmount_ (PartialMoveResult dir dist _) = pairToTuple . toPair $ injectAxis (toAxis $ GridOriented dir dist) 0
ublubu/tile-rider
src/TileRider/DrawTile.hs
mit
3,662
0
17
843
1,262
646
616
76
4
module Rebase.GHC.IO.Encoding.Iconv ( module GHC.IO.Encoding.Iconv ) where import GHC.IO.Encoding.Iconv
nikita-volkov/rebase
library/Rebase/GHC/IO/Encoding/Iconv.hs
mit
107
0
5
12
26
19
7
4
0
{-| Module : WekaData Description : Works with weka *.arff data and files. License : MIT Stability : development Works with weka *.arff data and files. -} module WekaData ( -- * Raw Data RawWekaData(..) -- * Attributes , WekaDataAttribute(WekaAttrNum, WekaAttrNom) , wekaAttributeName , wekaAttribute2str -- * Search by attr. name , findInMap , findInMapWithAttr , lookupInMap , lookupInMapWithAttr , lookupInSet , lookupInList -- * *.arff files , readWekaData , wekaDataFromLines -- * Data Containers , WekaVal (WVal) , wVal2Pair , getWVal , WekaEntry(..) , wekaData2Sparse -- * Search 'WekaVal' by attr. name , lookupWValInMap , lookupWValInSet , stringifyWekaAttr , stringifyWekaData ) where import Data.Typeable import Data.Function (on) import Data.List import Data.List.Split import Data.Char import Data.Ord import qualified Data.Map as Map import qualified Data.Set as Set import Data.Map (Map) import Data.Set (Set) import Data.Maybe (fromMaybe) import Control.Applicative ----------------------------------------------------------------------------- -- | Data read from Weka @*.arff@ files. data RawWekaData = RawWekaData { rwdName :: String -- ^ relation , rwdAttrs :: [WekaDataAttribute] -- ^ attributes , rawWekaData :: [[String]] -- ^ raw data } instance (Show WekaDataAttribute) => Show RawWekaData where show (RawWekaData name attrs dta) = "RawWekaData " ++ name ++ "\n" ++ "Attributes:\n\t" ++ intercalate "\n\t" (map wekaAttribute2str attrs) ++ "Data:\n" ++ intercalate "\n\t" (map show dta) -- | Weka attribute. data WekaDataAttribute = WekaAttrNum String -- ^ numeric attribute | WekaAttrNom String [String] -- ^ nominal attribute with its domain | WekaAttrExtractor String -- ^ an extractor intented to be used for sets and maps deriving Typeable instance Eq WekaDataAttribute where x == y = wekaAttributeName x == wekaAttributeName y instance Ord WekaDataAttribute where compare = compare `on` wekaAttributeName getFromMaybe name = fromMaybe (error $ "attribute '" ++ name ++ "' not found") -- | Find an attribute by name in a map with attribute keys. findInMap :: String -> Map WekaDataAttribute a -> a findInMap name = getFromMaybe name . lookupInMap name -- fromMaybe (error $ "attribute '" ++ name ++ "' not found") . lookupInMap name -- | Try to find an attribute by name in a map with attribute keys. lookupInMap :: String -> Map WekaDataAttribute a -> Maybe a lookupInMap name = Map.lookup (WekaAttrExtractor name) -- | Find an attribute by name in a map with attribute keys. findInMapWithAttr :: String -> Map WekaDataAttribute a -> (WekaDataAttribute, a) findInMapWithAttr name = getFromMaybe name . lookupInMapWithAttr name lookupElem :: (Int -> a -> b) -> (WekaDataAttribute -> a -> Maybe Int) -> String -> a -> Maybe b lookupElem elemAt lookupIndex name x = fmap (`elemAt` x) (lookupIndex (WekaAttrExtractor name) x) -- | Try to find an attribute by name in a map with attribute keys. lookupInMapWithAttr :: String -> Map WekaDataAttribute a -> Maybe (WekaDataAttribute, a) lookupInMapWithAttr = lookupElem Map.elemAt Map.lookupIndex -- | Try to find an attribute by name in a set of attributes. lookupInSet :: String -> Set WekaDataAttribute -> Maybe WekaDataAttribute lookupInSet = lookupElem Set.elemAt Set.lookupIndex lookupInList :: String -> [WekaDataAttribute] -> Maybe WekaDataAttribute lookupInList = lookupElem (flip (!!)) elemIndex -- | Get name of a 'WekaDataAttribute'. wekaAttributeName (WekaAttrNum name) = name wekaAttributeName (WekaAttrNom name _) = name wekaAttributeName (WekaAttrExtractor name) = name wekaAttribute2str (WekaAttrNum name) = "Numeric " ++ name wekaAttribute2str (WekaAttrNom name domain) = "Nominal " ++ name ++ " " ++ show domain wekaAttribute2str (WekaAttrExtractor name) = "Extractor " ++ name ----------------------------------------------------------------------------- data WekaVal = WVal WekaDataAttribute String | WValExtractor String deriving Typeable instance Eq WekaVal where (WVal a1 v1) == (WVal a2 v2) = a1 == a2 && v1 == v2 (WVal a v) == (WValExtractor n) = wekaAttributeName a == n e@(WValExtractor _) == v@(WVal _ _) = v == e instance Ord WekaVal where (WVal a1 v1) `compare` (WVal a2 v2) | a1 == a2 = v1 `compare` v2 | otherwise = a1 `compare` a2 (WVal a _) `compare` (WValExtractor n) = wekaAttributeName a `compare` n e@(WValExtractor n) `compare` v@(WVal a _) = n `compare` wekaAttributeName a lookupWVal elemAt lookupIndex name x = fmap (`elemAt` x) (lookupIndex (WValExtractor name) x) -- | Try to find a 'WekaVal' by attribute name in a set of 'WekaVal's. lookupWValInMap :: String -> Map WekaVal v -> Maybe WekaVal lookupWValInMap = lookupWVal (\x -> fst . Map.elemAt x) Map.lookupIndex -- | Try to find a 'WekaVal' by attribute name in a set of 'WekaVal's. lookupWValInSet :: String -> Set WekaVal -> Maybe WekaVal lookupWValInSet = lookupWVal Set.elemAt Set.lookupIndex data WekaEntry = WEntry (Set WekaVal) | WSortedEntry [WekaVal] deriving (Eq, Ord, Typeable) extractWEntry (WEntry set) = Set.toList set extractWEntry (WSortedEntry l) = l wVal2Pair (WVal a v) = (a, v) getWVal (WVal _ v) = v ----------------------------------------------------------------------------- -- | Tries to read a *.arff file. readWekaData :: String -- ^ file name -> IO RawWekaData readWekaData filename = do lines <- splitOn "\n" <$> readFile filename -- same as fmap (splitOn "\n") (readFile filename) return $ wekaDataFromLines lines wekaDataFromLines :: [String] -> RawWekaData wekaDataFromLines lines = readWekaData' lines Nothing [] [] readWekaData' :: [String] -> Maybe String -> [WekaDataAttribute] -> [[String]] -> RawWekaData -- ignore comments and empty lines readWekaData' (l:lines) name attrs dta | "%" `isPrefixOf` l || null l = readWekaData' lines name attrs dta -- handling name readWekaData' (l:lines) Nothing [] [] | "@relation " `isPrefixOf` l = let name = dropComment $ drop (length "@relation ") l in readWekaData' lines (Just name) [] [] -- handling attributes readWekaData' (l:lines) name@(Just _) attrs [] | "@attribute " `isPrefixOf` l = let attr = readWekaAttr . dropSpaces . dropComment $ l in readWekaData' lines name (attr:attrs) [] -- handling data readWekaData' (l:lines) name@(Just _) attrs@(_:_) dta | "@data" `isPrefixOf` l = readWekaData' lines name attrs dta | otherwise = readWekaData' lines name attrs (splitOn "," l : dta) -- return result readWekaData' [] (Just name) attrs dta = RawWekaData name (reverse attrs) (reverse dta) dropComment = takeWhile (/= '%') dropSpaces = dropWhile isSpace -- | Reads weka attribute from a line. readWekaAttr :: String -> WekaDataAttribute readWekaAttr line | null l' = error $ "readWekaAttr: empty attribute: " ++ show line | head l' == '{' = WekaAttrNom name domain | "numeric" `isPrefixOf` l' = WekaAttrNum name | otherwise = error $ show l' where l = dropSpaces $ drop (length "@attribute ") line (name, len) = if head l == '\'' then (takeWhile (/= '\'') (drop 1 l), 2) else (takeWhile (/= ' ') l, 0) l' = dropSpaces $ drop (length name + len) l f = filter (fmap not $ (||) <$> isSpace <*> (`elem` "{}")) domain = map f $ splitOn "," l' ----------------------------------------------------------------------------- -- | in the data: __foreach__ nominal attribute with /singleton/ domain: -- -- 1. drop the '?' items -- 2. create a 'WekaEntry' for the rest of attributes wekaData2Sparse :: RawWekaData -> [WekaEntry] wekaData2Sparse (RawWekaData _ attrs dta) = do entry <- dta return . WEntry . Set.fromList . map (uncurry WVal) . filter ((/=) "?" . snd) $ zip attrs entry ----------------------------------------------------------------------------- stringifyWekaAttr :: WekaDataAttribute -> String stringifyWekaAttr (WekaAttrNum name) = "@attribute " ++ show name ++ " numeric" stringifyWekaAttr (WekaAttrNom name domain) = "@attribute " ++ show name ++ " {" ++ intercalate "," (map quoteIfNeeded domain) ++ "}" stringifyWekaData :: String -> [WekaEntry] -> String stringifyWekaData relName entries@(e:_) = intercalate "\n" $ rel : "" : attrs ++ "" : "@data" : vals where rel = "@relation " ++ show relName (attrs', _) = unzip . map wVal2Pair $ extractWEntry e attrs = map stringifyWekaAttr attrs' vals = map (intercalate "," . map (quoteIfNeeded . getWVal) . extractWEntry) entries quoteIfNeeded s = if any isSpace s then '\'' : s ++ "'" else s
fehu/min-dat--weka-data
src/WekaData.hs
mit
9,269
0
13
2,233
2,463
1,300
1,163
-1
-1
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} module Eurocode5.Fasteners.Bolts where import qualified Eurocode5.Wood.WoodCommon as WC data Bolt = Bolt { diam :: Double -- ^ Diameter of bolt [mm] } deriving Show type Degrees = Double type Radians = Double toRadians :: Degrees -> Radians toRadians d = (d/180.0) * pi toDegrees :: Radians -> Degrees toDegrees r = (r/pi) * 180.0 k90 :: Bolt -> WC.Wood -> Double k90 Bolt { diam } WC.Wood { wcat } = wcf + (0.015*diam) where wcf | wcat == WC.SoftWood = 1.35 | wcat == WC.HardWood = 0.9 | otherwise = 1.3 -- | Characteristic capacity of bolt against wood -- | in the fiber direction fh0k :: Bolt -> WC.Wood -> Double -- ^ [N/mm2] fh0k Bolt { diam } WC.Wood { rho } = 0.082 * (1.0 - (0.01*diam)) * rho -- | Characteristic capacity of bolt against wood -- | at an angle between force and fiber direction fhak :: Bolt -> WC.Wood -> Double -- ^ Angle between force and fiber direction [degrees] -> Double -- ^ [N/mm2] fhak b w ang = (fh0k b w) / ((k90'*s) + c) where k90' = k90 b w rads = toRadians ang s = (sin rads)**2.0 c = (cos rads)**2.0 holeEdgePressure :: Bolt -> WC.Wood -> Double -- ^ Angle between force and fiber direction [degrees] -> Double -- ^ [kN] holeEdgePressure b w ang = (fhak b w ang) * (diam b) * (WC.t w) / 1000.0
baalbek/eurocode5
src/Eurocode5/Fasteners/Bolts.hs
gpl-2.0
1,513
0
11
464
442
241
201
37
1
--just need to compare the left most and right most path main = do leftT <- readFile "p067_triangle.txt" let left = reverse $ mapReadInt $ map words . lines $ leftT putStrLn $ show $ bestPath left bestPath triangle = head $ foldl collapse (head triangle) (tail triangle) collapse lower higher = zipWith (+) higher best where best = zipWith max lower shifted shifted = tail lower mapReadInt x = map (map read) x
NaevaTheCat/Project-Euler-Haskell
P67.hs
gpl-2.0
441
0
13
104
150
72
78
9
1
{- | Module : $Header$ Copyright : (c) Dominik Luecke, Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Complexity analysis of OWL2 -} module OWL2.Sublogic where import OWL2.AS import OWL2.MS import OWL2.Sign import OWL2.Morphism import Data.List import Data.Maybe import qualified Data.Set as Set data NumberRestrictions = None | Unqualified | Qualified deriving (Show, Eq, Ord) owlDatatypes :: Set.Set Datatype owlDatatypes = Set.fromList predefIRIs data OWLSub = OWLSub { numberRestrictions :: NumberRestrictions , nominals :: Bool , inverseRoles :: Bool , roleTransitivity :: Bool , roleHierarchy :: Bool , complexRoleInclusions :: Bool , addFeatures :: Bool , datatype :: Set.Set Datatype } deriving (Show, Eq, Ord) -- | sROIQ(D) slTop :: OWLSub slTop = OWLSub { numberRestrictions = Qualified , nominals = True , inverseRoles = True , roleTransitivity = True , roleHierarchy = True , complexRoleInclusions = True , addFeatures = True , datatype = owlDatatypes } -- | ALC slBottom :: OWLSub slBottom = OWLSub { numberRestrictions = None , nominals = False , inverseRoles = False , roleTransitivity = False , roleHierarchy = False , complexRoleInclusions = False , addFeatures = False , datatype = Set.empty } slMax :: OWLSub -> OWLSub -> OWLSub slMax sl1 sl2 = OWLSub { numberRestrictions = max (numberRestrictions sl1) (numberRestrictions sl2) , nominals = max (nominals sl1) (nominals sl2) , inverseRoles = max (inverseRoles sl1) (inverseRoles sl2) , roleTransitivity = max (roleTransitivity sl1) (roleTransitivity sl2) , roleHierarchy = max (roleHierarchy sl1) (roleHierarchy sl2) , complexRoleInclusions = max (complexRoleInclusions sl1) (complexRoleInclusions sl2) , addFeatures = max (addFeatures sl1) (addFeatures sl2) , datatype = Set.union (datatype sl1) (datatype sl2) } -- | Naming for Description Logics slName :: OWLSub -> String slName sl = (if complexRoleInclusions sl || addFeatures sl then (if addFeatures sl then "s" else "") ++ "R" else (if roleTransitivity sl then "S" else "ALC") ++ if roleHierarchy sl then "H" else "") ++ (if nominals sl then "O" else "") ++ (if inverseRoles sl then "I" else "") ++ (case numberRestrictions sl of Qualified -> "Q" Unqualified -> "N" None -> "") ++ let ds = datatype sl in if Set.null ds then "" else "-D|" ++ (if ds == owlDatatypes then "-|" else intercalate "|" (map printDatatype $ Set.toList ds) ++ "|") requireQualNumberRestrictions :: OWLSub -> OWLSub requireQualNumberRestrictions sl = sl {numberRestrictions = Qualified} requireNumberRestrictions :: OWLSub -> OWLSub requireNumberRestrictions sl = let nr = numberRestrictions sl in sl {numberRestrictions = if nr /= Qualified then Unqualified else nr} requireRoleTransitivity :: OWLSub -> OWLSub requireRoleTransitivity sl = sl {roleTransitivity = True} requireRoleHierarchy :: OWLSub -> OWLSub requireRoleHierarchy sl = sl {roleHierarchy = True} requireComplexRoleInclusions :: OWLSub -> OWLSub requireComplexRoleInclusions sl = (requireRoleHierarchy $ requireRoleTransitivity sl) {complexRoleInclusions = True} requireAddFeatures :: OWLSub -> OWLSub requireAddFeatures sl = (requireComplexRoleInclusions sl) {addFeatures = True} requireNominals :: OWLSub -> OWLSub requireNominals sl = sl {nominals = True} requireInverseRoles :: OWLSub -> OWLSub requireInverseRoles sl = sl {inverseRoles = True} slDatatype :: Datatype -> OWLSub slDatatype dt = slBottom {datatype = if isDatatypeKey dt then Set.singleton dt else Set.empty} slObjProp :: ObjectPropertyExpression -> OWLSub slObjProp o = case o of ObjectProp _ -> slBottom ObjectInverseOf _ -> requireInverseRoles slBottom slEntity :: Entity -> OWLSub slEntity (Entity et iri) = case et of Datatype -> slDatatype iri _ -> slBottom slDataRange :: DataRange -> OWLSub slDataRange rn = case rn of DataType ur _ -> slDatatype ur DataComplementOf c -> slDataRange c DataOneOf _ -> requireNominals slBottom DataJunction _ drl -> foldl slMax slBottom $ map slDataRange drl slClassExpression :: ClassExpression -> OWLSub slClassExpression des = case des of ObjectJunction _ dec -> foldl slMax slBottom $ map slClassExpression dec ObjectComplementOf dec -> slClassExpression dec ObjectOneOf _ -> requireNominals slBottom ObjectValuesFrom _ o d -> slMax (slObjProp o) (slClassExpression d) ObjectHasSelf o -> requireAddFeatures $ slObjProp o ObjectHasValue o _ -> slObjProp o ObjectCardinality c -> slObjCard c DataValuesFrom _ _ dr -> slDataRange dr DataCardinality c -> slDataCard c _ -> slBottom slDataCard :: Cardinality DataPropertyExpression DataRange -> OWLSub slDataCard (Cardinality _ _ _ x) = requireNumberRestrictions $ case x of Nothing -> slBottom Just y -> slDataRange y slObjCard :: Cardinality ObjectPropertyExpression ClassExpression -> OWLSub slObjCard (Cardinality _ _ op x) = requireNumberRestrictions $ case x of Nothing -> slObjProp op Just y -> slMax (slObjProp op) (slClassExpression y) slLFB :: Maybe Relation -> ListFrameBit -> OWLSub slLFB mr lfb = case lfb of ExpressionBit anl -> foldl slMax slBottom $ map (slClassExpression . snd) anl ObjectBit anl -> slMax (case fromMaybe (error "relation needed") mr of EDRelation Disjoint -> requireAddFeatures slBottom _ -> slBottom) $ foldl slMax slBottom $ map (slObjProp . snd) anl DataBit _ -> case fromMaybe (error "relation needed") mr of EDRelation Disjoint -> requireAddFeatures slBottom _ -> slBottom IndividualSameOrDifferent _ -> requireNominals slBottom ObjectCharacteristics anl -> foldl slMax slBottom $ map ((\ c -> case c of Transitive -> requireRoleTransitivity slBottom Reflexive -> requireAddFeatures slBottom Irreflexive -> requireAddFeatures slBottom Asymmetric -> requireAddFeatures slBottom _ -> slBottom) . snd) anl DataPropRange anl -> foldl slMax slBottom $ map (slDataRange . snd) anl _ -> slBottom slAFB :: AnnFrameBit -> OWLSub slAFB afb = case afb of DatatypeBit dr -> slDataRange dr ClassDisjointUnion cel -> foldl slMax slBottom $ map slClassExpression cel ClassHasKey opl _ -> foldl slMax slBottom $ map slObjProp opl ObjectSubPropertyChain opl -> requireComplexRoleInclusions $ requireRoleHierarchy $ foldl slMax slBottom $ map slObjProp opl _ -> slBottom slFB :: FrameBit -> OWLSub slFB fb = case fb of AnnFrameBit _ afb -> slAFB afb ListFrameBit mr lfb -> slMax (slLFB mr lfb) $ case mr of Nothing -> slBottom Just r -> case r of SubPropertyOf -> requireRoleHierarchy slBottom InverseOf -> requireInverseRoles slBottom _ -> slBottom -- maybe addFeatures ?? slAxiom :: Axiom -> OWLSub slAxiom (PlainAxiom ext fb) = case ext of Misc _ -> slFB fb ClassEntity ce -> slMax (slFB fb) (slClassExpression ce) ObjectEntity o -> slMax (slFB fb) (slObjProp o) SimpleEntity e -> slMax (slEntity e) (slFB fb) slFrame :: Frame -> OWLSub slFrame = foldl slMax slBottom . map slAxiom . getAxioms slODoc :: OntologyDocument -> OWLSub slODoc = foldl slMax slBottom . map slFrame . ontFrames . ontology slSig :: Sign -> OWLSub slSig sig = let dts = Set.toList $ datatypes sig in if Set.size (dataProperties sig) == 0 && null dts then slBottom else foldl slMax slBottom $ map slDatatype dts slMor :: OWLMorphism -> OWLSub slMor mor = slMax (slSig $ osource mor) $ slSig $ otarget mor -- projections along sublogics prMor :: OWLSub -> OWLMorphism -> OWLMorphism prMor s a = a { osource = prSig s $ osource a , otarget = prSig s $ otarget a } prSig :: OWLSub -> Sign -> Sign prSig s a = if datatype s == Set.empty then a {datatypes = Set.empty, dataProperties = Set.empty} else a prODoc :: OWLSub -> OntologyDocument -> OntologyDocument prODoc s a = let o = (ontology a) {ontFrames = filter ((s >=) . slFrame) $ ontFrames $ ontology a } in a {ontology = o}
nevrenato/Hets_Fork
OWL2/Sublogic.hs
gpl-2.0
8,415
0
17
1,896
2,537
1,296
1,241
189
13
{-# LANGUAGE OverloadedStrings #-} import Data.Aeson import Data.Text import Control.Applicative ((<$>)) import Network.HTTP.Types import qualified Data.Map as Map import Network.HTTP.Conduit import qualified Data.HashMap.Lazy as LHashMap import qualified Data.Text.IO as IO (putStrLn) import Data.Vector ((!)) getJSON :: String -> IO (Either String Value) getJSON url = eitherDecode <$> simpleHttp url getJSONObject :: String -> IO Object getJSONObject url = getJSON url >>= \(Right (Object jsonObject)) -> return jsonObject main :: IO () main = do putStr "1) " jsonObject <- getJSONObject "https://www.bitstamp.net/api/ticker/" case (LHashMap.lookup "last" jsonObject) of Just (String val) -> IO.putStrLn val _ -> error "Couldn't get the key" putStr "2) " jsonObject <- getJSONObject "https://btc-e.com/api/2/btc_usd/ticker" case (LHashMap.lookup "ticker" jsonObject) of Just (Object v) -> case LHashMap.lookup "last" v of Just (Number n) -> putStrLn $ show n _ -> error "error 2" _ -> error "Couldn't get the key" putStr "3) " jsonObject <- getJSONObject "https://btc-e.com/api/2/ltc_btc/ticker" case (LHashMap.lookup "ticker" jsonObject) of Just (Object v) -> case LHashMap.lookup "last" v of Just (Number n) -> putStrLn $ show n _ -> error "error 2" _ -> error "Couldn't get the key" putStr "4) " jsonObject <- getJSONObject "https://api.bitfinex.com/v1/ticker/btcusd" case (LHashMap.lookup "last_price" jsonObject) of Just (String val) -> IO.putStrLn val _ -> error "Couldn't get the key" putStr "5) " jsonObject <- getJSONObject "https://coinbase.com/api/v1/prices/buy" case (LHashMap.lookup "amount" jsonObject) of (Just (String val)) -> IO.putStrLn val _ -> error "Couldn't get the key" putStr "6) " request <- parseUrl "https://api.kraken.com/0/public/Ticker" res <- withManager $ httpLbs $ configureRequest request let toPrint = do Object jsonObject <- decode $ responseBody res :: Maybe Value Object jsonObject2 <- LHashMap.lookup "result" jsonObject Object jsonObject3 <- LHashMap.lookup "XXBTZUSD" jsonObject2 Array d <- LHashMap.lookup "c" jsonObject3 String val <- return $ d ! 1 return val case toPrint of Just a -> IO.putStrLn a _ -> error "Unexpected JSON" where configureRequest r = r { method = Network.HTTP.Types.methodPost, requestHeaders = ("content-type", "application/json") : requestHeaders r, requestBody = RequestBodyLBS (encode $ Map.fromList [("pair" :: Text, "XXBTZUSD" :: Text)]) }
GildedHonour/BitcoinPriceAnalizer
src/Main.hs
gpl-2.0
2,686
0
15
601
811
390
421
64
9
------------------------------------------------------------------ -- | -- Module : Gom.CodeGen.Abstract -- Copyright : (c) Paul Brauner 2009 -- (c) Emilie Balland 2009 -- (c) INRIA 2009 -- Licence : GPL (see COPYING) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (requires generalized newtype deriving) -------------------------------------------------------------------- module Gom.CodeGen.Abstract ( compAbstract ) where import Gom.CodeGen.Common import Gom.SymbolTable import Gom.Config import Gom.FileGen import Text.PrettyPrint.Leijen hiding ((<$>)) -- | Generates the @ModAbstractType@ abstract java class for module @Mod@. compAbstract :: Gen FileHierarchy compAbstract = do at <- abstractType -- if haskell option is enabled, generate abstract toHaskell hs <- ifConf haskell hask [] -- if sharing option is enabled, generate abstract methods ss <- ifConf sharing [abstractSharing] [] -- if visit option is enabled, implement visitable iv <- ifConf visit [jVisitable] [] -- if sharing option is enabled, implement shared is <- ifConf sharing [jSharedId] [] -- generate renderString and/or renderChar rs <- str <$> askSt importsString <*> askSt importsChar -- if random is enabled, generate builtin random generation ra <- ifConf random [randomBuiltins] [] -- if depth is enabled, generate size abstract method de <- ifConf depth [abstractDepth] [] -- if size is enabled, generate size abstract method si <- ifConf size [abstractSize] [] -- build the class return $ Class at (cl at (hs++ss++rs++ra++de++si) (iv++is)) where cl at e i = rClass (public <+> abstract) (text at) Nothing i (body e) body = vcat . (always ++) always = [abstractSymbolName,toStringBody,abstractToStringBuilder] hask = [toHaskellBody,abstractToHaskellBuilder] str True _ = [renderStringMethod,renderCharMethod] str False True = [renderCharMethod] str False False = []
polux/hgom
src/Gom/CodeGen/Abstract.hs
gpl-3.0
2,346
0
16
703
415
227
188
25
3
{-# LANGUAGE KindSignatures,DataKinds,GADTs,ScopedTypeVariables,RankNTypes,TypeOperators,FlexibleContexts #-} module Language.SMTLib2.QuickCheck where import qualified Language.SMTLib2.Internals.Backend as B import Language.SMTLib2.Internals.Expression hiding (AnyFunction) import Language.SMTLib2.Internals.Type import Language.SMTLib2.Internals.Type.List (List(..)) import qualified Language.SMTLib2.Internals.Type.List as List import Language.SMTLib2.Internals.Type.Nat import Test.QuickCheck hiding (Args) import Test.QuickCheck.Monadic import Data.Dependent.Map (DMap) import qualified Data.Dependent.Map as DMap import Data.Set (Set) import qualified Data.Set as Set import Data.Proxy import Data.Functor.Identity import Data.GADT.Show import Data.GADT.Compare import Control.Monad.State.Strict import qualified GHC.TypeLits as TL data ExprGen m b var qvar fun farg lvar e tp = ExprGen ((forall t. Expression var qvar fun farg lvar e t -> b -> m (e t,b)) -> b -> m (e tp,b)) type BackendExprGen b tp = ExprGen (B.SMTMonad b) b (B.Var b) (B.QVar b) (B.Fun b) (B.FunArg b) (B.LVar b) (B.Expr b) tp newtype VarSet v (tp :: Type) = VarSet (Set (v tp)) data GenContext var qvar fun = GenCtx { allVars :: DMap Repr (VarSet var) , allQVars :: DMap Repr (VarSet qvar) , allFuns :: DMap Repr (VarSet (AnyFunction fun)) } data AnyFunction f (tp :: Type) = forall (arg::[Type]). AnyFunction (f '(arg,tp)) data AnyType = forall tp. AnyType (Repr tp) data AnyTypes = forall tps. AnyTypes (List Repr tps) data AnyNatural = forall n. AnyNatural (Natural n) data TestExpr var qvar fun farg lvar tp = TestExpr (Expression var qvar fun farg lvar (TestExpr var qvar fun farg lvar) tp) type TestExprGen var qvar fun farg lvar tp = ExprGen Identity () var qvar fun farg lvar (TestExpr var qvar fun farg lvar) tp emptyContext :: GenContext var qvar fun emptyContext = GenCtx { allVars = DMap.empty , allQVars = DMap.empty , allFuns = DMap.empty } roundTripTest :: (B.Backend b,B.SMTMonad b ~ IO) => GenContext (B.Var b) (B.QVar b) (B.Fun b) -> IO b -> Property roundTripTest ctx (cb::IO b) = monadicIO $ do AnyType tp <- pick genType expr <- pick (genTestExpr tp ctx) cond <- run $ do b <- cb (expr1,nb) <- encodeTestExpr expr b let expr2 = decodeTestExpr expr1 nb return $ expr2==expr assert cond {-roundTripTest :: B.Backend b => GenContext (B.Var b) (B.QVar b) (B.Fun b) -> PropertyM (StateT b (B.SMTMonad b)) () roundTripTest ctx = do AnyType (_::Proxy tp) <- pick genType expr1 <- pick (genTestExpr ctx) b <- lift get (expr2,nb) <- lift $ lift $ encodeTestExpr expr1 b lift $ put nb let expr3 = decodeTestExpr expr2 nb assert $ expr1 == expr3-} encodeTestExpr :: (B.Backend b) => TestExpr (B.Var b) (B.QVar b) (B.Fun b) (B.FunArg b) (B.LVar b) tp -> b -> B.SMTMonad b (B.Expr b tp,b) encodeTestExpr e b = runStateT (encode' e) b where encode' :: (B.Backend b) => TestExpr (B.Var b) (B.QVar b) (B.Fun b) (B.FunArg b) (B.LVar b) tp -> StateT b (B.SMTMonad b) (B.Expr b tp) encode' (TestExpr e) = do e' <- mapExpr return return return return return encode' e b <- get (ne,nb) <- lift $ B.toBackend e' b put nb return ne decodeTestExpr :: (B.Backend b) => B.Expr b tp -> b -> TestExpr (B.Var b) (B.QVar b) (B.Fun b) (B.FunArg b) (B.LVar b) tp decodeTestExpr e b = TestExpr $ runIdentity $ mapExpr return return return return return (\e' -> return (decodeTestExpr e' b)) (B.fromBackend b e) genTestExpr :: (GetFunType fun) => Repr tp -> GenContext var qvar fun -> Gen (TestExpr var qvar fun farg lvar tp) genTestExpr tp ctx = do ExprGen egen <- genExpr tp ctx return $ fst $ runIdentity (egen (\e _ -> return (TestExpr e,())) ()) genExpr :: (Monad m,GetFunType fun) => Repr t -> GenContext var qvar fun -> Gen (ExprGen m b var qvar fun farg lvar e t) genExpr tp ctx = sized $ \sz -> if sz==0 then oneof [ gen | Just gen <- [genVar tp ,genQVar tp ,Just $ genConst tp] ] else resize (sz `div` 2) $ oneof [genApp tp] where genVar tp = do VarSet vs <- DMap.lookup tp (allVars ctx) if Set.null vs then Nothing else return $ elements [ ExprGen (\f -> f (Var v)) | v <- Set.toList vs ] genQVar tp = do VarSet vs <- DMap.lookup tp (allQVars ctx) if Set.null vs then Nothing else return $ elements [ ExprGen (\f -> f (QVar v)) | v <- Set.toList vs ] genConst :: (Monad m) => Repr t -> Gen (ExprGen m b var qvar fun farg lvar e t) genConst tp = case tp of BoolRepr -> do val <- arbitrary return $ ExprGen $ \f -> f (Const $ BoolValue val) IntRepr -> do val <- arbitrary return $ ExprGen $ \f -> f (Const $ IntValue val) RealRepr -> do val <- arbitrary return $ ExprGen $ \f -> f (Const $ RealValue val) BitVecRepr bw -> do val <- choose (0,2^(bwSize bw)-1) return $ ExprGen $ \f -> f (Const $ BitVecValue val bw) ArrayRepr idx el -> do ExprGen c <- genConst el return $ ExprGen $ \f b -> do (rel,b1) <- c f b f (App (ConstArray idx el) (rel ::: Nil)) b1 --genApp :: (Monad m) => Repr tp -- -> Gen (ExprGen m b var qvar fun con field farg lvar e tp) genApp tp = do AnyFunction fun <- genFunction tp ctx let (args,_) = getFunType fun args' <- List.mapM (\tp -> genExpr tp ctx) args return $ ExprGen $ \f b -> do (nb,rargs) <- List.mapAccumM (\b (ExprGen g) -> do (expr,nb) <- g f b return (nb,expr) ) b args' f (App fun rargs) nb genFunction :: Repr tp -> GenContext var qvar fun -> Gen (AnyFunction (Function fun) tp) genFunction tp ctx = oneof [ gen | Just gen <- [genFun ,genBuiltin tp] ] where genFun = do VarSet funs <- DMap.lookup tp (allFuns ctx) if Set.null funs then Nothing else return $ elements [ AnyFunction (Fun f) | AnyFunction f <- Set.toList funs ] genBuiltin :: Repr t -> Maybe (Gen (AnyFunction (Function fun) t)) genBuiltin tp = case tp of BoolRepr -> Just $ oneof [do AnyType tp <- genType AnyNatural sz <- genNatural elements [AnyFunction (Eq tp sz) ,AnyFunction (Distinct tp sz)] ,do op <- elements [Ge,Gt,Le,Lt] return $ AnyFunction (Ord NumInt op) ,do op <- elements [Ge,Gt,Le,Lt] return $ AnyFunction (Ord NumReal op) ,return $ AnyFunction Not ,do AnyNatural sz <- genNatural op <- elements [And,Or,XOr,Implies] return (AnyFunction (Logic op sz)) ,return $ AnyFunction (ITE tp) ,do op <- elements [BVULE,BVULT,BVUGE,BVUGT,BVSLE,BVSLT,BVSGE,BVSGT] sz <- arbitrarySizedNatural case TL.someNatVal sz of Just (TL.SomeNat sz') -> return $ AnyFunction (BVComp op (bw sz')) ,do AnyTypes idx <- genTypes return $ AnyFunction (Select idx tp) ] IntRepr -> Just $ oneof [do AnyNatural len <- genNatural op <- elements [Plus,Mult,Minus] return (AnyFunction (Arith NumInt op len)) ,do op <- elements [Div,Mod,Rem] return $ AnyFunction (ArithIntBin op) ,return $ AnyFunction (Abs NumInt) ,return $ AnyFunction (ITE tp) ,return $ AnyFunction ToInt ,do AnyTypes idx <- genTypes return $ AnyFunction (Select idx tp) ] RealRepr -> Just $ oneof [do AnyNatural sz <- genNatural op <- elements [Plus,Mult,Minus] return (AnyFunction (Arith NumReal op sz)) ,return $ AnyFunction Divide ,return $ AnyFunction (Abs NumReal) ,return $ AnyFunction ToReal ,return $ AnyFunction (ITE tp) ,do AnyTypes idx <- genTypes return $ AnyFunction (Select idx tp) ] (BitVecRepr bw) -> Just $ oneof [return $ AnyFunction (ITE tp) ,do op <- elements [BVAdd,BVSub,BVMul,BVURem,BVSRem,BVUDiv,BVSDiv,BVSHL,BVLSHR,BVASHR,BVXor,BVAnd,BVOr] return $ AnyFunction (BVBin op bw) ,do op <- elements [BVNot,BVNeg] return $ AnyFunction (BVUn op bw) ,do AnyTypes idx <- genTypes return $ AnyFunction (Select idx tp) --TODO: Concat, Extract ] ArrayRepr idx el -> Just $ oneof [return $ AnyFunction (ITE tp) ,do AnyTypes idx' <- genTypes return $ AnyFunction (Select idx' tp) ,return $ AnyFunction (Store idx el) ,return $ AnyFunction (ConstArray idx el)] _ -> Nothing genType :: Gen AnyType genType = sized $ \sz -> oneof $ [return $ AnyType BoolRepr ,return $ AnyType IntRepr ,return $ AnyType RealRepr ,do sz <- arbitrarySizedNatural case TL.someNatVal sz of Just (TL.SomeNat sz') -> return $ AnyType (BitVecRepr (bw sz'))]++ (if sz>0 then [do AnyTypes tps <- resize (sz `div` 2) genTypes AnyType tp <- resize (sz `div` 2) genType return $ AnyType (ArrayRepr tps tp) ] else []) genTypes :: Gen AnyTypes genTypes = sized $ \len -> gen' len where gen' 0 = return $ AnyTypes Nil gen' n = do AnyTypes tps <- gen' (n-1) AnyType tp <- genType return $ AnyTypes (tp ::: tps) genNatural :: Gen AnyNatural genNatural = sized $ \len -> reifyNat (fromIntegral len) (return.AnyNatural) withAllEqLen :: Repr tp -> Int -> (forall tps. List Repr (tp ': tps) -> a) -> a withAllEqLen tp 0 f = f (tp ::: Nil) withAllEqLen tp n f = withAllEqLen tp (n-1) $ \tps -> f (tp ::: tps) instance (GShow var,GShow qvar,GShow fun,GShow farg,GShow lvar) => GShow (TestExpr var qvar fun farg lvar) where gshowsPrec n (TestExpr e) = gshowsPrec n e instance (GShow var,GShow qvar,GShow fun,GShow farg,GShow lvar) => Show (TestExpr var qvar fun farg lvar tp) where showsPrec = gshowsPrec instance Show AnyType where show (AnyType tp) = show tp instance (GEq var,GEq qvar,GEq fun,GEq farg,GEq lvar) => GEq (TestExpr var qvar fun farg lvar) where geq (TestExpr x) (TestExpr y) = geq x y instance (GEq var,GEq qvar,GEq fun,GEq farg,GEq lvar) => Eq (TestExpr var qvar fun farg lvar tp) where (==) (TestExpr x) (TestExpr y) = x==y
hguenther/smtlib2
extras/quickcheck/Language/SMTLib2/QuickCheck.hs
gpl-3.0
12,375
1
23
4,787
4,251
2,160
2,091
-1
-1
import Data.QLogic.BoxWorld import Data.QLogic import Data.List import Data.Poset.ConcretePoset import Data.QLogic import Data.Set (Set) import qualified Data.Set as Set import Data.IntSet (IntSet) import qualified Data.IntSet as IS import Data.QLogic.Utils import Data.Maybe x = Observable 'X' [0, 1] y = Observable 'Y' [0, 1] box = [x, y] system = Three (box, box, box) -- system = Two (box, box) -- system = Two ((Two (box, box)), box) main :: IO () main = do let ql = boxWorldLogic system a = read "[X0X0X0]+[X1X0X0]+[X0X1Y0]+[X1X1Y0]" :: Question (Three Atomic) b = read "[Y0X0X0]+[Y0X0X1]+[Y0X1X0]+[Y0X1X1]" :: Question (Three Atomic) c = read "[X0X0X0]+[X1X0X0]" :: Question (Three Atomic) c' = Question (Three (Trivial, Atomic 'X' 0, Atomic 'X' 0)) q2set = toRepr ql set2q = fromRepr ql logic = logicRepr ql print $ q2set a print $ q2set b print $ set2q . q2set $ b -- print "Number of -- print $ sum . map (length . set2q) $ elementsOf ql print $ q2set c == q2set c' print $ compatIn logic (q2set a) (q2set b) print $ compatIn ql a b print $ length . elementsOf $ ql
ttylec/QLogic
research/concrete3.hs
gpl-3.0
1,198
0
14
306
390
206
184
32
1
{-# LANGUAGE OverloadedStrings #-} module Html (toHtml, htmlDoc) where import Types (Recipe (..), showIngredient) import Prelude hiding (head) tag :: String -> String -> String tag t str = "<" ++ t ++ ">" ++ str ++ "</" ++ t ++ ">\n" h1 :: String -> String h1 = tag "h1" h2 :: String -> String h2 = tag "h2" p :: String -> String p = tag "p" em :: String -> String em = tag "em" ol :: String -> String ol = tag "ul" ul :: String -> String ul = tag "ul" li :: String -> String li = tag "li" toHtml :: Recipe -> String toHtml recipe = mconcat [ h1 $ recipeName recipe, p $ description recipe, p (em "Serving size:" ++ show (servingSize recipe)), h2 "Ingredients", p $ ul ( concatMap (li . showIngredient 1) (ingredients recipe) ), h2 "Directions", ol (concatMap li (directions recipe)) ] html :: String -> String html = tag "html" head :: String -> String head = tag "head" title :: String -> String title = tag "title" body :: String -> String body = tag "body" htmlDoc :: Maybe String -> String -> String htmlDoc cssUrl bodyHtml = mconcat [ "<!DOCTYPE html>", html $ mconcat [ head $ mconcat [ "<meta charset=\"UTF-8\">", case cssUrl of Just url -> "<link rel=\"stylesheet\" href=\"" ++ url ++ "\">" Nothing -> "", title "Recipes" ], body bodyHtml ] ]
JackKiefer/herms
src/Html.hs
gpl-3.0
1,548
0
17
534
499
262
237
56
2
mergeSort :: (Ord a) => [a] -> [a] mergeSort [] = [] mergeSort (x:[]) = [x] mergeSort l = merge (mergeSort a) (mergeSort b) where (a,b) = splitMid l splitMid l = splitAt ((length l) `div` 2) l merge a [] = a merge [] b = b merge a@(ah:at) b@(bh:bt) | ah <= bh = ah : merge at b | otherwise = bh : merge a bt insertionSort :: (Ord a) => [a] -> [a] insertionSort [] = [] insertionSort (lh:lt) = insertionSort' [] lh lt where insertionSort' a x [] = insert a x [] insertionSort' a x (bh:bt) = insertionSort' (insert a x []) bh bt insert [] x b = x:b insert a x b | last a <= x = a ++ [x] ++ b | otherwise = insert (init a) x ((last a):b) radixSort :: [Int] -> [Int] radixSort [] = [] radixSort (x:[]) = [x] radixSort l = radixSort' l (numDigits (maximum l)) where b = 16 numDigits 0 = 1 numDigits x = 1 + numDigits (x `div` b) radixSort' [] d = [] radixSort' l 0 = l radixSort' l d = concat [radixSort' x (d-1) | x <- (putInBuckets l)] where putInBuckets [] = [[] | x <- [1,2..b]] putInBuckets (lh:lt) = (take i p) ++ [(p !! i) ++ [lh]] ++ (drop (i+1) p) where p = putInBuckets lt i = (lh `div` (b^(d-1))) `mod` b
apvanzanten/learningMeAHaskell
sorts.hs
gpl-3.0
1,426
0
17
553
747
388
359
34
5
{-# 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.AndroidEnterprise.Entitlements.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves details of an entitlement. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.entitlements.get@. module Network.Google.Resource.AndroidEnterprise.Entitlements.Get ( -- * REST Resource EntitlementsGetResource -- * Creating a Request , entitlementsGet , EntitlementsGet -- * Request Lenses , egEntitlementId , egEnterpriseId , egUserId ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.entitlements.get@ method which the -- 'EntitlementsGet' request conforms to. type EntitlementsGetResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "users" :> Capture "userId" Text :> "entitlements" :> Capture "entitlementId" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Entitlement -- | Retrieves details of an entitlement. -- -- /See:/ 'entitlementsGet' smart constructor. data EntitlementsGet = EntitlementsGet' { _egEntitlementId :: !Text , _egEnterpriseId :: !Text , _egUserId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'EntitlementsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'egEntitlementId' -- -- * 'egEnterpriseId' -- -- * 'egUserId' entitlementsGet :: Text -- ^ 'egEntitlementId' -> Text -- ^ 'egEnterpriseId' -> Text -- ^ 'egUserId' -> EntitlementsGet entitlementsGet pEgEntitlementId_ pEgEnterpriseId_ pEgUserId_ = EntitlementsGet' { _egEntitlementId = pEgEntitlementId_ , _egEnterpriseId = pEgEnterpriseId_ , _egUserId = pEgUserId_ } -- | The ID of the entitlement (a product ID), e.g. -- \"app:com.google.android.gm\". egEntitlementId :: Lens' EntitlementsGet Text egEntitlementId = lens _egEntitlementId (\ s a -> s{_egEntitlementId = a}) -- | The ID of the enterprise. egEnterpriseId :: Lens' EntitlementsGet Text egEnterpriseId = lens _egEnterpriseId (\ s a -> s{_egEnterpriseId = a}) -- | The ID of the user. egUserId :: Lens' EntitlementsGet Text egUserId = lens _egUserId (\ s a -> s{_egUserId = a}) instance GoogleRequest EntitlementsGet where type Rs EntitlementsGet = Entitlement type Scopes EntitlementsGet = '["https://www.googleapis.com/auth/androidenterprise"] requestClient EntitlementsGet'{..} = go _egEnterpriseId _egUserId _egEntitlementId (Just AltJSON) androidEnterpriseService where go = buildClient (Proxy :: Proxy EntitlementsGetResource) mempty
rueshyna/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Entitlements/Get.hs
mpl-2.0
3,697
0
16
873
461
275
186
75
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.IAM.CreateUser -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new user for your AWS account. -- -- For information about limitations on the number of users you can create, -- see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html Limitations on IAM Entities> -- in the /IAM User Guide/. -- -- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html AWS API Reference> for CreateUser. module Network.AWS.IAM.CreateUser ( -- * Creating a Request createUser , CreateUser -- * Request Lenses , cuPath , cuUserName -- * Destructuring the Response , createUserResponse , CreateUserResponse -- * Response Lenses , cursUser , cursResponseStatus ) where import Network.AWS.IAM.Types import Network.AWS.IAM.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'createUser' smart constructor. data CreateUser = CreateUser' { _cuPath :: !(Maybe Text) , _cuUserName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateUser' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cuPath' -- -- * 'cuUserName' createUser :: Text -- ^ 'cuUserName' -> CreateUser createUser pUserName_ = CreateUser' { _cuPath = Nothing , _cuUserName = pUserName_ } -- | The path for the user name. For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. -- -- This parameter is optional. If it is not included, it defaults to a -- slash (\/). cuPath :: Lens' CreateUser (Maybe Text) cuPath = lens _cuPath (\ s a -> s{_cuPath = a}); -- | The name of the user to create. cuUserName :: Lens' CreateUser Text cuUserName = lens _cuUserName (\ s a -> s{_cuUserName = a}); instance AWSRequest CreateUser where type Rs CreateUser = CreateUserResponse request = postQuery iAM response = receiveXMLWrapper "CreateUserResult" (\ s h x -> CreateUserResponse' <$> (x .@? "User") <*> (pure (fromEnum s))) instance ToHeaders CreateUser where toHeaders = const mempty instance ToPath CreateUser where toPath = const "/" instance ToQuery CreateUser where toQuery CreateUser'{..} = mconcat ["Action" =: ("CreateUser" :: ByteString), "Version" =: ("2010-05-08" :: ByteString), "Path" =: _cuPath, "UserName" =: _cuUserName] -- | Contains the response to a successful CreateUser request. -- -- /See:/ 'createUserResponse' smart constructor. data CreateUserResponse = CreateUserResponse' { _cursUser :: !(Maybe User) , _cursResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateUserResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cursUser' -- -- * 'cursResponseStatus' createUserResponse :: Int -- ^ 'cursResponseStatus' -> CreateUserResponse createUserResponse pResponseStatus_ = CreateUserResponse' { _cursUser = Nothing , _cursResponseStatus = pResponseStatus_ } -- | Information about the user. cursUser :: Lens' CreateUserResponse (Maybe User) cursUser = lens _cursUser (\ s a -> s{_cursUser = a}); -- | The response status code. cursResponseStatus :: Lens' CreateUserResponse Int cursResponseStatus = lens _cursResponseStatus (\ s a -> s{_cursResponseStatus = a});
olorin/amazonka
amazonka-iam/gen/Network/AWS/IAM/CreateUser.hs
mpl-2.0
4,369
0
13
950
638
385
253
79
1
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.Project where import Import import Data.Filter import Data.Order import Data.Time.Format import Handler.Comment as Com import Handler.Discussion import Handler.Utils import Model.Application import Model.Comment import Model.Comment.ActionPermissions import Model.Comment.HandlerInfo import Model.Comment.Mods import Model.Comment.Sql import Model.Currency import Model.Discussion import Model.Issue import Model.Markdown.Diff import Model.Project import Model.Role import Model.Shares import Model.SnowdriftEvent import Model.User import Model.Wiki import System.Locale (defaultTimeLocale) import View.Comment import View.Project import View.SnowdriftEvent import View.Time import Widgets.Preview import Data.Default (def) import qualified Data.Foldable as F import Data.List (sortBy) import qualified Data.Map as M import Data.Maybe (maybeToList) import qualified Data.Set as S import qualified Data.Text as T import Data.Tree (Forest, Tree) import qualified Data.Tree as Tree import System.Random (randomIO) import Text.Cassius (cassiusFile) import Text.Printf import Yesod.AtomFeed import Yesod.RssFeed -------------------------------------------------------------------------------- -- Utility functions lookupGetParamDefault :: Read a => Text -> a -> Handler a lookupGetParamDefault name def_val = do maybe_value <- lookupGetParam name return (fromMaybe def_val (maybe_value >>= readMaybe . T.unpack)) -- | Require any of the given Roles, failing with permissionDenied if none are satisfied. requireRolesAny :: [Role] -> Text -> Text -> Handler (UserId, Entity Project) requireRolesAny roles project_handle err_msg = do user_id <- requireAuthId (project, ok) <- runYDB $ do project@(Entity project_id _) <- getBy404 (UniqueProjectHandle project_handle) ok <- userHasRolesAnyDB roles user_id project_id return (project, ok) unless ok $ permissionDenied err_msg return (user_id, project) -- | Sanity check for Project Comment pages. Redirects if the comment was rethreaded. -- 404's if the comment doesn't exist. 403 if permission denied. checkComment :: Text -> CommentId -> Handler (Maybe (Entity User), Entity Project, Comment) checkComment project_handle comment_id = do muser <- maybeAuth (project, comment) <- checkComment' (entityKey <$> muser) project_handle comment_id return (muser, project, comment) -- | Like checkComment, but authentication is required. checkCommentRequireAuth :: Text -> CommentId -> Handler (Entity User, Entity Project, Comment) checkCommentRequireAuth project_handle comment_id = do user@(Entity user_id _) <- requireAuth (project, comment) <- checkComment' (Just user_id) project_handle comment_id return (user, project, comment) -- | Abstract checkComment and checkCommentRequireAuth. You shouldn't use this function directly. checkComment' :: Maybe UserId -> Text -> CommentId -> Handler (Entity Project, Comment) checkComment' muser_id project_handle comment_id = do redirectIfRethreaded comment_id (project, ecomment) <- runYDB $ do project@(Entity project_id _) <- getBy404 (UniqueProjectHandle project_handle) let has_permission = exprCommentProjectPermissionFilter muser_id (val project_id) ecomment <- fetchCommentDB comment_id has_permission return (project, ecomment) case ecomment of Left CommentNotFound -> notFound Left CommentPermissionDenied -> permissionDenied "You don't have permission to view this comment." Right comment -> if commentDiscussion comment /= projectDiscussion (entityVal project) then notFound else return (project, comment) checkProjectCommentActionPermission :: (CommentActionPermissions -> Bool) -> Entity User -> Text -> Entity Comment -> Handler () checkProjectCommentActionPermission can_perform_action user project_handle comment@(Entity comment_id _) = do action_permissions <- lookupErr "checkProjectCommentActionPermission: comment id not found in map" comment_id <$> makeProjectCommentActionPermissionsMap (Just user) project_handle def [comment] unless (can_perform_action action_permissions) (permissionDenied "You don't have permission to perform this action.") makeProjectCommentForestWidget :: Maybe (Entity User) -> ProjectId -> Text -> [Entity Comment] -> CommentMods -> Handler MaxDepth -> Bool -> Widget -> Handler (Widget, Forest (Entity Comment)) makeProjectCommentForestWidget muser project_id project_handle comments = makeCommentForestWidget (projectCommentHandlerInfo muser project_id project_handle) comments muser makeProjectCommentTreeWidget :: Maybe (Entity User) -> ProjectId -> Text -> Entity Comment -> CommentMods -> Handler MaxDepth -> Bool -> Widget -> Handler (Widget, Tree (Entity Comment)) makeProjectCommentTreeWidget a b c d e f g h = do (widget, [tree]) <- makeProjectCommentForestWidget a b c [d] e f g h return (widget, tree) makeProjectCommentActionWidget :: MakeCommentActionWidget -> Text -> CommentId -> CommentMods -> Handler MaxDepth -> Handler (Widget, Tree (Entity Comment)) makeProjectCommentActionWidget make_comment_action_widget project_handle comment_id mods get_max_depth = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id let handler_info = projectCommentHandlerInfo (Just user) project_id project_handle make_comment_action_widget (Entity comment_id comment) user handler_info mods get_max_depth False projectDiscussionPage :: Text -> Widget -> Widget projectDiscussionPage project_handle widget = do $(widgetFile "project_discussion_wrapper") toWidget $(cassiusFile "templates/comment.cassius") ------------------------------------------------------------------------------- -- getProjectsR :: Handler Html getProjectsR = do project_summaries <- runDB $ do projects <- fetchPublicProjectsDB forM projects $ \project -> do pledges <- fetchProjectPledgesDB $ entityKey project discussions <- fetchProjectDiscussionsDB $ entityKey project tickets <- fetchProjectOpenTicketsDB (entityKey project) Nothing let summary = summarizeProject project pledges discussions tickets return (project, summary) let discussionsCount = getCount . summaryDiscussionCount let ticketsCount = getCount . summaryTicketCount defaultLayout $ do snowdriftTitle "Projects" $(widgetFile "projects") -------------------------------------------------------------------------------- -- / getProjectR :: Text -> Handler Html getProjectR project_handle = do mviewer_id <- maybeAuthId (project_id, project, is_watching, pledges, pledge) <- runYDB $ do Entity project_id project <- getBy404 $ UniqueProjectHandle project_handle pledges <- fetchProjectSharesDB project_id (pledge, is_watching) <- case mviewer_id of Nothing -> return (Nothing, False) Just viewer_id -> (,) <$> getBy (UniquePledge viewer_id project_id) <*> userIsWatchingProjectDB viewer_id project_id return (project_id, project, is_watching, pledges, pledge) defaultLayout $ do snowdriftTitle $ projectName project renderProject (Just project_id) project mviewer_id is_watching pledges pledge postProjectR :: Text -> Handler Html postProjectR project_handle = do (viewer_id, Entity project_id project) <- requireRolesAny [Admin] project_handle "You do not have permission to edit this project." ((result, _), _) <- runFormPost $ editProjectForm Nothing now <- liftIO getCurrentTime case result of FormSuccess (UpdateProject name blurb description tags github_repo logo) -> lookupPostMode >>= \case Just PostMode -> do runDB $ do when (projectBlurb project /= blurb) $ do project_update <- insert $ ProjectUpdate now project_id viewer_id blurb (diffMarkdown (projectDescription project) description) last_update <- getBy $ UniqueProjectLastUpdate project_id case last_update of Just (Entity k _) -> repsert k $ ProjectLastUpdate project_id project_update Nothing -> void $ insert $ ProjectLastUpdate project_id project_update update $ \p -> do set p [ ProjectName =. val name , ProjectBlurb =. val blurb , ProjectDescription =. val description , ProjectGithubRepo =. val github_repo , ProjectLogo =. val logo ] where_ (p ^. ProjectId ==. val project_id) tag_ids <- forM tags $ \tag_name -> do tag_entity_list <- select $ from $ \tag -> do where_ (tag ^. TagName ==. val tag_name) return tag case tag_entity_list of [] -> insert $ Tag tag_name Entity tag_id _ : _ -> return tag_id delete $ from $ \pt -> where_ (pt ^. ProjectTagProject ==. val project_id) forM_ tag_ids $ \tag_id -> insert (ProjectTag project_id tag_id) alertSuccess "project updated" redirect $ ProjectR project_handle _ -> do let preview_project = project { projectName = name , projectBlurb = blurb , projectDescription = description , projectGithubRepo = github_repo , projectLogo = logo } (form, _) <- generateFormPost $ editProjectForm (Just (preview_project, tags)) defaultLayout $ previewWidget form "update" $ renderProject (Just project_id) preview_project Nothing False [] Nothing x -> do alertDanger $ T.pack $ show x redirect $ ProjectR project_handle -------------------------------------------------------------------------------- -- /applications (List of submitted applications) getApplicationsR :: Text -> Handler Html getApplicationsR project_handle = do viewer_id <- requireAuthId (project, applications) <- runYDB $ do Entity project_id project <- getBy404 (UniqueProjectHandle project_handle) ok <- userIsAffiliatedWithProjectDB viewer_id project_id unless ok $ lift (permissionDenied "You don't have permission to view this page.") applications <- fetchProjectVolunteerApplicationsDB project_id userReadVolunteerApplicationsDB viewer_id return (project, applications) defaultLayout $ do snowdriftTitle $ projectName project <> " Volunteer Applications" $(widgetFile "applications") -------------------------------------------------------------------------------- -- /application (Form for new application) getApplicationR :: Text -> VolunteerApplicationId -> Handler Html getApplicationR project_handle application_id = do viewer_id <- requireAuthId (project, user, application, interests, num_interests) <- runYDB $ do Entity project_id project <- getBy404 (UniqueProjectHandle project_handle) ok <- userIsAffiliatedWithProjectDB viewer_id project_id unless ok $ lift (permissionDenied "You don't have permission to view this page.") application <- get404 application_id let user_id = volunteerApplicationUser application user <- get404 user_id (interests, num_interests) <- (T.intercalate ", " &&& length) <$> fetchApplicationVolunteerInterestsDB application_id return (project, Entity user_id user, application, interests, num_interests) defaultLayout $ do snowdriftDashTitle (projectName project <> " Volunteer Application") (userDisplayName user) $(widgetFile "application") -------------------------------------------------------------------------------- -- /edit getEditProjectR :: Text -> Handler Html getEditProjectR project_handle = do (_, Entity project_id project) <- requireRolesAny [Admin] project_handle "You do not have permission to edit this project." tags <- runDB $ select $ from $ \(p_t `InnerJoin` tag) -> do on_ (p_t ^. ProjectTagTag ==. tag ^. TagId) where_ (p_t ^. ProjectTagProject ==. val project_id) return tag (project_form, _) <- generateFormPost $ editProjectForm (Just (project, map (tagName . entityVal) tags)) defaultLayout $ do snowdriftTitle $ projectName project $(widgetFile "edit_project") -------------------------------------------------------------------------------- -- /feed -- | This function is responsible for hitting every relevant event table. Nothing -- statically guarantees that. getProjectFeedR :: Text -> Handler TypedContent getProjectFeedR project_handle = do let lim = 26 -- limit 'lim' from each table, then take 'lim - 1' languages <- getLanguages muser <- maybeAuth let muser_id = entityKey <$> muser before <- lookupGetUTCTimeDefaultNow "before" ( project_id, project, is_watching, comment_events, rethread_events, closing_events, claiming_events, unclaiming_events, wiki_page_events, wiki_edit_events, blog_post_events, new_pledge_events, updated_pledge_events, deleted_pledge_events, discussion_map, wiki_target_map, user_map, earlier_closures_map, earlier_retracts_map, closure_map, retract_map, ticket_map, claim_map, flag_map ) <- runYDB $ do Entity project_id project <- getBy404 (UniqueProjectHandle project_handle) is_watching <- maybe (pure False) (flip userIsWatchingProjectDB project_id) muser_id comment_events <- fetchProjectCommentPostedEventsIncludingRethreadedBeforeDB project_id muser_id before lim rethread_events <- fetchProjectCommentRethreadEventsBeforeDB project_id muser_id before lim closing_events <- fetchProjectCommentClosingEventsBeforeDB project_id muser_id before lim claiming_events <- fetchProjectTicketClaimingEventsBeforeDB project_id before lim unclaiming_events <- fetchProjectTicketUnclaimingEventsBeforeDB project_id before lim wiki_page_events <- fetchProjectWikiPageEventsWithTargetsBeforeDB languages project_id before lim blog_post_events <- fetchProjectBlogPostEventsBeforeDB project_id before lim wiki_edit_events <- fetchProjectWikiEditEventsWithTargetsBeforeDB languages project_id before lim new_pledge_events <- fetchProjectNewPledgeEventsBeforeDB project_id before lim updated_pledge_events <- fetchProjectUpdatedPledgeEventsBeforeDB project_id before lim deleted_pledge_events <- fetchProjectDeletedPledgeEventsBeforeDB project_id before lim -- Suplementary maps for displaying the data. If something above requires extra -- data to display the project feed row, it MUST be used to fetch the data below! let (comment_ids, comment_users) = F.foldMap (\(_, Entity comment_id comment) -> ([comment_id], [commentUser comment])) comment_events (wiki_edit_users, wiki_edit_pages) = F.foldMap (\(_, Entity _ e, _) -> ([wikiEditUser e], [wikiEditPage e])) wiki_edit_events (blog_post_users) = F.foldMap (\(_, Entity _ e) -> [blogPostUser e]) blog_post_events shares_pledged = map (entityVal . snd) new_pledge_events <> map (\(_, _, x) -> entityVal x) updated_pledge_events closing_users = map (commentClosingClosedBy . entityVal . snd) closing_events rethreading_users = map (rethreadModerator . entityVal . snd) rethread_events ticket_claiming_users = map (either (ticketClaimingUser . entityVal) (ticketOldClaimingUser . entityVal) . snd) claiming_events ticket_unclaiming_users = map (ticketOldClaimingUser . entityVal . snd) unclaiming_events pledging_users = map sharesPledgedUser shares_pledged unpledging_users = map (eventDeletedPledgeUser . snd) deleted_pledge_events -- All users: comment posters, wiki page creators, etc. user_ids = S.toList $ mconcat [ S.fromList comment_users , S.fromList closing_users , S.fromList rethreading_users , S.fromList wiki_edit_users , S.fromList blog_post_users , S.fromList ticket_claiming_users , S.fromList ticket_unclaiming_users , S.fromList pledging_users , S.fromList unpledging_users ] discussion_map <- fetchProjectDiscussionsDB project_id >>= fetchDiscussionsDB languages let claimed_comment_ids = map (either (ticketClaimingTicket . entityVal) (ticketOldClaimingTicket . entityVal) . snd) claiming_events unclaimed_comment_ids = map (ticketOldClaimingTicket . entityVal . snd) unclaiming_events closed_comment_ids = map (commentClosingComment . entityVal . snd) closing_events ticket_map <- fetchCommentTicketsDB $ mconcat [ S.fromList comment_ids , S.fromList claimed_comment_ids , S.fromList unclaimed_comment_ids , S.fromList closed_comment_ids ] -- WikiPages keyed by their own IDs (contained in a WikiEdit) wiki_targets <- pickTargetsByLanguage languages <$> fetchWikiPageTargetsInDB wiki_edit_pages let wiki_target_map = M.fromList $ map ((wikiTargetPage &&& id) . entityVal) wiki_targets user_map <- entitiesMap <$> fetchUsersInDB user_ids earlier_closures_map <- fetchCommentsAncestorClosuresDB comment_ids earlier_retracts_map <- fetchCommentsAncestorRetractsDB comment_ids closure_map <- makeCommentClosingMapDB comment_ids retract_map <- makeCommentRetractingMapDB comment_ids claim_map <- makeClaimedTicketMapDB comment_ids flag_map <- makeFlagMapDB comment_ids return ( project_id, project, is_watching, comment_events, rethread_events, closing_events, claiming_events, unclaiming_events, wiki_page_events, wiki_edit_events, blog_post_events, new_pledge_events, updated_pledge_events, deleted_pledge_events, discussion_map, wiki_target_map, user_map, earlier_closures_map, earlier_retracts_map, closure_map, retract_map, ticket_map, claim_map, flag_map ) action_permissions_map <- makeProjectCommentActionPermissionsMap muser project_handle def (map snd comment_events) let all_unsorted_events :: [(Route App, SnowdriftEvent)] all_unsorted_events = mconcat [ map (EventCommentPostedR *** onEntity ECommentPosted) comment_events , map (EventCommentRethreadedR *** onEntity ECommentRethreaded) rethread_events , map (EventCommentClosingR *** onEntity ECommentClosed) closing_events , map (EventTicketClaimedR *** ETicketClaimed . (onEntity (,) +++ onEntity (,))) claiming_events , map (EventTicketUnclaimedR *** onEntity ETicketUnclaimed) unclaiming_events , map (\(eid, Entity wpid wp, wt) -> (EventWikiPageR eid, EWikiPage wpid wp wt)) wiki_page_events , map (\(eid, Entity weid we, wt) -> (EventWikiEditR eid, EWikiEdit weid we wt)) wiki_edit_events , map (EventBlogPostR *** onEntity EBlogPost) blog_post_events , map (EventNewPledgeR *** onEntity ENewPledge) new_pledge_events , map (\(eid, shares, pledge) -> (EventUpdatedPledgeR eid, eup2se shares pledge)) updated_pledge_events , map (EventDeletedPledgeR *** edp2se) deleted_pledge_events ] (events, more_events) = splitAt (lim-1) (sortBy (snowdriftEventNewestToOldest `on` snd) all_unsorted_events) -- For pagination: Nothing means no more pages, Just time means set the 'before' -- GET param to that time. Note that this means 'before' should be a <= relation, -- rather than a <. mnext_before :: Maybe Text mnext_before = case more_events of [] -> Nothing ((_, next_event):_) -> (Just . T.pack . show . snowdriftEventTime) next_event now <- liftIO getCurrentTime Just route <- getCurrentRoute render <- getUrlRender let feed = Feed "project feed" route HomeR "Snowdrift Community" "" "en" now $ mapMaybe (uncurry $ snowdriftEventToFeedEntry render project_handle user_map discussion_map wiki_target_map ticket_map) events selectRep $ do provideRep $ atomFeed feed provideRep $ rssFeed feed provideRep $ defaultLayout $ do snowdriftDashTitle (projectName project) "Feed" $(widgetFile "project_feed") toWidget $(cassiusFile "templates/comment.cassius") where -- "event updated pledge to snowdrift event" eup2se :: Int64 -> Entity SharesPledged -> SnowdriftEvent eup2se old_shares (Entity shares_pledged_id shares_pledged) = EUpdatedPledge old_shares shares_pledged_id shares_pledged -- "event deleted pledge to snowdrift event" edp2se :: EventDeletedPledge -> SnowdriftEvent edp2se (EventDeletedPledge a b c d) = EDeletedPledge a b c d -------------------------------------------------------------------------------- -- /invite getInviteR :: Text -> Handler Html getInviteR project_handle = do (_, Entity _ project) <- requireRolesAny [Admin] project_handle "You must be a project admin to invite." now <- liftIO getCurrentTime maybe_invite_code <- lookupSession "InviteCode" maybe_invite_role <- fmap (read . T.unpack) <$> lookupSession "InviteRole" deleteSession "InviteCode" deleteSession "InviteRole" let maybe_link = InvitationR project_handle <$> maybe_invite_code (invite_form, _) <- generateFormPost inviteForm outstanding_invites <- runDB $ select $ from $ \invite -> do where_ ( invite ^. InviteRedeemed ==. val False ) orderBy [ desc (invite ^. InviteCreatedTs) ] return invite redeemed_invites <- runDB $ select $ from $ \invite -> do where_ ( invite ^. InviteRedeemed ==. val True ) orderBy [ desc (invite ^. InviteCreatedTs) ] limit 20 return invite let redeemed_users = S.fromList $ mapMaybe (inviteRedeemedBy . entityVal) redeemed_invites redeemed_inviters = S.fromList $ map (inviteUser . entityVal) redeemed_invites outstanding_inviters = S.fromList $ map (inviteUser . entityVal) outstanding_invites user_ids = S.toList $ redeemed_users `S.union` redeemed_inviters `S.union` outstanding_inviters user_entities <- runDB $ selectList [ UserId <-. user_ids ] [] let users = M.fromList $ map (entityKey &&& id) user_entities let format_user Nothing = "NULL" format_user (Just user_id) = let Entity _ user = fromMaybe (error "getInviteR: user_id not found in users map") (M.lookup user_id users) in fromMaybe (userIdent user) $ userName user format_inviter user_id = userDisplayName $ fromMaybe (error "getInviteR(#2): user_id not found in users map") (M.lookup user_id users) defaultLayout $ do snowdriftDashTitle (projectName project) "Send Invite" $(widgetFile "invite") postInviteR :: Text -> Handler Html postInviteR project_handle = do (user_id, Entity project_id _) <- requireRolesAny [Admin] project_handle "You must be a project admin to invite." now <- liftIO getCurrentTime invite <- liftIO randomIO ((result, _), _) <- runFormPost inviteForm case result of FormSuccess (tag, role) -> do let invite_code = T.pack $ printf "%016x" (invite :: Int64) _ <- runDB $ insert $ Invite now project_id invite_code user_id role tag False Nothing Nothing setSession "InviteCode" invite_code setSession "InviteRole" (T.pack $ show role) _ -> alertDanger "Error in submitting form." redirect $ InviteR project_handle -------------------------------------------------------------------------------- -- /patrons getProjectPatronsR :: Text -> Handler Html getProjectPatronsR project_handle = do _ <- requireAuthId page <- lookupGetParamDefault "page" 0 per_page <- lookupGetParamDefault "count" 20 (project, pledges, user_payouts_map) <- runYDB $ do Entity project_id project <- getBy404 $ UniqueProjectHandle project_handle pledges <- select $ from $ \(pledge `InnerJoin` user) -> do on_ $ pledge ^. PledgeUser ==. user ^. UserId where_ $ pledge ^. PledgeProject ==. val project_id &&. pledge ^. PledgeFundedShares >. val 0 orderBy [ desc (pledge ^. PledgeFundedShares), asc (user ^. UserName), asc (user ^. UserId)] offset page limit per_page return (pledge, user) last_paydays <- case projectLastPayday project of Nothing -> return [] Just last_payday -> select $ from $ \payday -> do where_ $ payday ^. PaydayId <=. val last_payday orderBy [ desc $ payday ^. PaydayId ] limit 2 return payday user_payouts <- select $ from $ \(transaction `InnerJoin` user) -> do where_ $ transaction ^. TransactionPayday `in_` valList (map (Just . entityKey) last_paydays) on_ $ transaction ^. TransactionDebit ==. just (user ^. UserAccount) groupBy $ user ^. UserId return (user ^. UserId, count $ transaction ^. TransactionId) return (project, pledges, M.fromList $ map ((\(Value x :: Value UserId) -> x) *** (\(Value x :: Value Int) -> x)) user_payouts) defaultLayout $ do snowdriftTitle $ projectName project <> " Patrons" $(widgetFile "project_patrons") -------------------------------------------------------------------------------- -- /pledge getUpdatePledgeR :: Text -> Handler Html getUpdatePledgeR project_handle = do _ <- requireAuthId Entity project_id project <- runYDB $ getBy404 $ UniqueProjectHandle project_handle ((result, _), _) <- runFormGet $ pledgeForm project_id let dangerRedirect msg = do alertDanger msg redirect $ ProjectR project_handle case result of FormSuccess (SharesPurchaseOrder new_user_shares) -> do user_id <- requireAuthId (confirm_form, _) <- generateFormPost $ projectConfirmPledgeForm (Just new_user_shares) (mpledge, other_shares, pledges) <- runDB $ do pledges <- fetchProjectSharesDB project_id mpledge <- getBy $ UniquePledge user_id project_id other_shares <- fmap unwrapValues $ select $ from $ \p -> do where_ $ p ^. PledgeProject ==. val project_id &&. p ^. PledgeUser !=. val user_id return $ p ^. PledgeShares return (mpledge, other_shares, pledges) let new_user_mills = millMilray new_user_shares case mpledge of Just (Entity _ pledge) | pledgeShares pledge == new_user_shares -> do alertWarning $ T.unwords [ "Your pledge was already at" , T.pack (show new_user_mills) <> "." , "Thank you for your support!" ] redirect (ProjectR project_handle) _ -> do let old_user_shares = maybe 0 (pledgeShares . entityVal) mpledge old_user_mills = millMilray old_user_shares numPatrons = toInteger $ length pledges new_project_shares = filter (>0) [new_user_shares] ++ other_shares old_project_shares = filter (>0) [old_user_shares] ++ other_shares new_share_value = projectComputeShareValue new_project_shares old_share_value = projectComputeShareValue old_project_shares new_user_amount = new_share_value $* fromIntegral new_user_shares old_user_amount = old_share_value $* fromIntegral old_user_shares new_project_amount = new_share_value $* fromIntegral (sum new_project_shares) old_project_amount = old_share_value $* fromIntegral (sum old_project_shares) user_decrease = old_user_amount - new_user_amount user_increase = new_user_amount - old_user_amount project_decrease = old_project_amount - new_project_amount project_increase = new_project_amount - old_project_amount matching_drop = project_decrease - user_decrease matched_extra = project_increase - new_user_amount defaultLayout $ do snowdriftDashTitle (projectName project) "update pledge" $(widgetFile "update_pledge") FormMissing -> dangerRedirect "Form missing." FormFailure errors -> dangerRedirect $ T.snoc (T.intercalate "; " errors) '.' postUpdatePledgeR :: Text -> Handler Html postUpdatePledgeR project_handle = do ((result, _), _) <- runFormPost $ projectConfirmPledgeForm Nothing isConfirmed <- maybe False (T.isPrefixOf "yes") <$> lookupPostParam "confirm" case result of FormSuccess (SharesPurchaseOrder shares) -> do when isConfirmed $ updateUserPledge project_handle shares redirect (ProjectR project_handle) _ -> do alertDanger "error occurred in form submission" redirect (UpdatePledgeR project_handle) -------------------------------------------------------------------------------- -- /t getTicketsR :: Text -> Handler Html getTicketsR project_handle = do muser_id <- maybeAuthId (project, tagged_tickets) <- runYDB $ do Entity project_id project <- getBy404 (UniqueProjectHandle project_handle) tagged_tickets <- fetchProjectOpenTicketsDB project_id muser_id return (project, tagged_tickets) ((result, formWidget), encType) <- runFormGet viewForm let (filter_expression, order_expression) = case result of FormSuccess x -> x _ -> (defaultFilter, defaultOrder) github_issues <- getGithubIssues project let issues = sortBy (flip compare `on` order_expression . issueOrderable) $ filter (filter_expression . issueFilterable) $ map mkSomeIssue tagged_tickets ++ map mkSomeIssue github_issues defaultLayout $ do snowdriftTitle $ projectName project <> " Tickets" $(widgetFile "tickets") -------------------------------------------------------------------------------- -- /t/#TicketId getTicketR :: Text -> TicketId -> Handler () getTicketR project_handle ticket_id = do Ticket{..} <- runYDB $ do void $ getBy404 $ UniqueProjectHandle project_handle get404 ticket_id -- TODO - check that the comment is associated with the correct project redirect $ CommentDirectLinkR ticketComment -------------------------------------------------------------------------------- -- /transactions getProjectTransactionsR :: Text -> Handler Html getProjectTransactionsR project_handle = do (project, account, account_map, transaction_groups) <- runYDB $ do Entity _ project :: Entity Project <- getBy404 $ UniqueProjectHandle project_handle account <- get404 $ projectAccount project transactions <- select $ from $ \t -> do where_ $ t ^. TransactionCredit ==. val (Just $ projectAccount project) ||. t ^. TransactionDebit ==. val (Just $ projectAccount project) orderBy [ desc $ t ^. TransactionTs ] return t let accounts = S.toList $ S.fromList $ concatMap (\(Entity _ t) -> maybeToList (transactionCredit t) <> maybeToList (transactionDebit t)) transactions users_by_account <- fmap (M.fromList . map (userAccount . entityVal &&& Right)) $ select $ from $ \u -> do where_ $ u ^. UserAccount `in_` valList accounts return u projects_by_account <- fmap (M.fromList . map (projectAccount . entityVal &&& Left)) $ select $ from $ \p -> do where_ $ p ^. ProjectAccount `in_` valList accounts return p let account_map = projects_by_account `M.union` users_by_account payday_map <- fmap (M.fromList . map (entityKey &&& id)) $ select $ from $ \pd -> do where_ $ pd ^. PaydayId `in_` valList (S.toList $ S.fromList $ mapMaybe (transactionPayday . entityVal) transactions) return pd return (project, account, account_map, process payday_map transactions) let getOtherAccount transaction | transactionCredit transaction == Just (projectAccount project) = transactionDebit transaction | transactionDebit transaction == Just (projectAccount project) = transactionCredit transaction | otherwise = Nothing defaultLayout $ do snowdriftTitle $ projectName project <> " Transactions" $(widgetFile "project_transactions") where process payday_map = let process' [] [] = [] process' (t':ts') [] = [(fmap (payday_map M.!) $ transactionPayday $ entityVal t', reverse (t':ts'))] process' [] (t:ts) = process' [t] ts process' (t':ts') (t:ts) | transactionPayday (entityVal t') == transactionPayday (entityVal t) = process' (t:t':ts') ts | otherwise = (fmap (payday_map M.!) $ transactionPayday $ entityVal t', reverse (t':ts')) : process' [t] ts in process' [] -------------------------------------------------------------------------------- -- /w getWikiPagesR :: Text -> Handler Html getWikiPagesR project_handle = do void maybeAuthId languages <- getLanguages (project, wiki_targets) <- runYDB $ do Entity project_id project <- getBy404 $ UniqueProjectHandle project_handle wiki_targets <- getProjectWikiPages languages project_id return (project, wiki_targets) defaultLayout $ do snowdriftTitle $ projectName project <> " Wiki" $(widgetFile "wiki_pages") -------------------------------------------------------------------------------- -- /watch, /unwatch postWatchProjectR, postUnwatchProjectR :: ProjectId -> Handler () postWatchProjectR = watchOrUnwatchProject userWatchProjectDB "Watching " postUnwatchProjectR = watchOrUnwatchProject userUnwatchProjectDB "No longer watching " watchOrUnwatchProject :: (UserId -> ProjectId -> DB ()) -> Text -> ProjectId -> Handler () watchOrUnwatchProject action msg project_id = do user_id <- requireAuthId project <- runYDB $ do action user_id project_id get404 project_id alertSuccess (msg <> projectName project <> ".") redirect $ ProjectR $ projectHandle project -------------------------------------------------------------------------------- -- /c/#CommentId getProjectCommentR :: Text -> CommentId -> Handler Html getProjectCommentR project_handle comment_id = do (muser, Entity project_id _, comment) <- checkComment project_handle comment_id (widget, comment_tree) <- makeProjectCommentTreeWidget muser project_id project_handle (Entity comment_id comment) def getMaxDepth False mempty case muser of Nothing -> return () Just (Entity user_id _) -> runDB (userMaybeViewProjectCommentsDB user_id project_id (map entityKey (Tree.flatten comment_tree))) defaultLayout (projectDiscussionPage project_handle widget) -------------------------------------------------------------------------------- -- /c/#CommentId/approve getApproveProjectCommentR :: Text -> CommentId -> Handler Html getApproveProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeApproveCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postApproveProjectCommentR :: Text -> CommentId -> Handler Html postApproveProjectCommentR project_handle comment_id = do (user@(Entity user_id _), _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_approve user project_handle (Entity comment_id comment) postApproveComment user_id comment_id comment redirect (ProjectCommentR project_handle comment_id) -------------------------------------------------------------------------------- -- /c/#CommentId/claim getClaimProjectCommentR :: Text -> CommentId -> Handler Html getClaimProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeClaimCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postClaimProjectCommentR :: Text -> CommentId -> Handler Html postClaimProjectCommentR project_handle comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_claim user project_handle (Entity comment_id comment) postClaimComment user comment_id comment (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect (ProjectCommentR project_handle comment_id) Just (widget, form) -> defaultLayout $ previewWidget form "claim" (projectDiscussionPage project_handle widget) -------------------------------------------------------------------------------- -- /c/#CommentId/close getCloseProjectCommentR :: Text -> CommentId -> Handler Html getCloseProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeCloseCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postCloseProjectCommentR :: Text -> CommentId -> Handler Html postCloseProjectCommentR project_handle comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_close user project_handle (Entity comment_id comment) postCloseComment user comment_id comment (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect (ProjectCommentR project_handle comment_id) Just (widget, form) -> defaultLayout $ previewWidget form "close" (projectDiscussionPage project_handle widget) -------------------------------------------------------------------------------- -- /c/#CommentId/delete getDeleteProjectCommentR :: Text -> CommentId -> Handler Html getDeleteProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeDeleteCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postDeleteProjectCommentR :: Text -> CommentId -> Handler Html postDeleteProjectCommentR project_handle comment_id = do (user, _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_delete user project_handle (Entity comment_id comment) was_deleted <- postDeleteComment comment_id if was_deleted then redirect (ProjectDiscussionR project_handle) else redirect (ProjectCommentR project_handle comment_id) -------------------------------------------------------------------------------- -- /c/#CommentId/edit getEditProjectCommentR :: Text -> CommentId -> Handler Html getEditProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeEditCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postEditProjectCommentR :: Text -> CommentId -> Handler Html postEditProjectCommentR project_handle comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_edit user project_handle (Entity comment_id comment) postEditComment user (Entity comment_id comment) (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect (ProjectCommentR project_handle comment_id) -- Edit made. Just (widget, form) -> defaultLayout $ previewWidget form "post" (projectDiscussionPage project_handle widget) -------------------------------------------------------------------------------- -- /c/#CommentId/flag getFlagProjectCommentR :: Text -> CommentId -> Handler Html getFlagProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeFlagCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postFlagProjectCommentR :: Text -> CommentId -> Handler Html postFlagProjectCommentR project_handle comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_flag user project_handle (Entity comment_id comment) postFlagComment user (Entity comment_id comment) (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect (ProjectDiscussionR project_handle) Just (widget, form) -> defaultLayout $ previewWidget form "flag" (projectDiscussionPage project_handle widget) -------------------------------------------------------------------------------- -- /c/#CommentId/reply getReplyProjectCommentR :: Text -> CommentId -> Handler Html getReplyProjectCommentR project_handle parent_id = do (widget, _) <- makeProjectCommentActionWidget makeReplyCommentWidget project_handle parent_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postReplyProjectCommentR :: Text -> CommentId -> Handler Html postReplyProjectCommentR project_handle parent_id = do (user, Entity _ project, parent) <- checkCommentRequireAuth project_handle parent_id checkProjectCommentActionPermission can_reply user project_handle (Entity parent_id parent) postNewComment (Just parent_id) user (projectDiscussion project) (makeProjectCommentActionPermissionsMap (Just user) project_handle def) >>= \case ConfirmedPost (Left err) -> do alertDanger err redirect $ ReplyProjectCommentR project_handle parent_id ConfirmedPost (Right _) -> redirect $ ProjectCommentR project_handle parent_id Com.Preview (widget, form) -> defaultLayout $ previewWidget form "post" $ projectDiscussionPage project_handle widget -------------------------------------------------------------------------------- -- /c/#CommentId/rethread getRethreadProjectCommentR :: Text -> CommentId -> Handler Html getRethreadProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeRethreadCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postRethreadProjectCommentR :: Text -> CommentId -> Handler Html postRethreadProjectCommentR project_handle comment_id = do (user@(Entity user_id _), _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_rethread user project_handle (Entity comment_id comment) postRethreadComment user_id comment_id comment -------------------------------------------------------------------------------- -- /c/#CommentId/retract getRetractProjectCommentR :: Text -> CommentId -> Handler Html getRetractProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeRetractCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postRetractProjectCommentR :: Text -> CommentId -> Handler Html postRetractProjectCommentR project_handle comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_retract user project_handle (Entity comment_id comment) postRetractComment user comment_id comment (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect (ProjectCommentR project_handle comment_id) Just (widget, form) -> defaultLayout $ previewWidget form "retract" (projectDiscussionPage project_handle widget) -------------------------------------------------------------------------------- -- /c/#CommentId/tags getProjectCommentTagsR :: Text -> CommentId -> Handler Html getProjectCommentTagsR _ = getCommentTags -------------------------------------------------------------------------------- -- /c/#CommentId/tag/#TagId getProjectCommentTagR :: Text -> CommentId -> TagId -> Handler Html getProjectCommentTagR _ = getCommentTagR postProjectCommentTagR :: Text -> CommentId -> TagId -> Handler () postProjectCommentTagR _ = postCommentTagR -------------------------------------------------------------------------------- -- /c/#CommentId/tag/apply, /c/#CommentId/tag/create postProjectCommentApplyTagR, postProjectCommentCreateTagR:: Text -> CommentId -> Handler Html postProjectCommentApplyTagR = applyOrCreate postCommentApplyTag postProjectCommentCreateTagR = applyOrCreate postCommentCreateTag applyOrCreate :: (CommentId -> Handler ()) -> Text -> CommentId -> Handler Html applyOrCreate action project_handle comment_id = do action comment_id redirect (ProjectCommentR project_handle comment_id) -------------------------------------------------------------------------------- -- /c/#CommentId/tag/new getProjectCommentAddTagR :: Text -> CommentId -> Handler Html getProjectCommentAddTagR project_handle comment_id = do (user@(Entity user_id _), Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_add_tag user project_handle (Entity comment_id comment) getProjectCommentAddTag comment_id project_id user_id -------------------------------------------------------------------------------- -- /c/#CommentId/unclaim getUnclaimProjectCommentR :: Text -> CommentId -> Handler Html getUnclaimProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeUnclaimCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postUnclaimProjectCommentR :: Text -> CommentId -> Handler Html postUnclaimProjectCommentR project_handle comment_id = do (user, Entity project_id _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_unclaim user project_handle (Entity comment_id comment) postUnclaimComment user comment_id comment (projectCommentHandlerInfo (Just user) project_id project_handle) >>= \case Nothing -> redirect (ProjectCommentR project_handle comment_id) Just (widget, form) -> defaultLayout $ previewWidget form "unclaim" (projectDiscussionPage project_handle widget) -------------------------------------------------------------------------------- -- /c/#CommentId/watch getWatchProjectCommentR :: Text -> CommentId -> Handler Html getWatchProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeWatchCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postWatchProjectCommentR ::Text -> CommentId -> Handler Html postWatchProjectCommentR project_handle comment_id = do (viewer@(Entity viewer_id _), _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_watch viewer project_handle (Entity comment_id comment) postWatchComment viewer_id comment_id redirect (ProjectCommentR project_handle comment_id) -------------------------------------------------------------------------------- -- /c/#CommentId/unwatch getUnwatchProjectCommentR :: Text -> CommentId -> Handler Html getUnwatchProjectCommentR project_handle comment_id = do (widget, _) <- makeProjectCommentActionWidget makeUnwatchCommentWidget project_handle comment_id def getMaxDepth defaultLayout (projectDiscussionPage project_handle widget) postUnwatchProjectCommentR ::Text -> CommentId -> Handler Html postUnwatchProjectCommentR project_handle comment_id = do (viewer@(Entity viewer_id _), _, comment) <- checkCommentRequireAuth project_handle comment_id checkProjectCommentActionPermission can_watch viewer project_handle (Entity comment_id comment) postUnwatchComment viewer_id comment_id redirect (ProjectCommentR project_handle comment_id) -------------------------------------------------------------------------------- -- /contact -- ProjectContactR stuff posts a private new topic to project discussion getProjectContactR :: Text -> Handler Html getProjectContactR project_handle = do (project_contact_form, _) <- generateFormPost projectContactForm Entity _ project <- runYDB $ getBy404 (UniqueProjectHandle project_handle) defaultLayout $ do snowdriftTitle $ "Contact " <> projectName project $(widgetFile "project_contact") postProjectContactR :: Text -> Handler Html postProjectContactR project_handle = do maybe_user_id <- maybeAuthId ((result, _), _) <- runFormPost projectContactForm Entity _ project <- runYDB $ getBy404 (UniqueProjectHandle project_handle) case result of FormSuccess (content, language) -> do _ <- runSDB (postApprovedCommentDB (fromMaybe anonymousUser maybe_user_id) Nothing (projectDiscussion project) content VisPrivate language) alertSuccess "Comment submitted. Thank you for your input!" _ -> alertDanger "Error occurred when submitting form." redirect $ ProjectContactR project_handle -------------------------------------------------------------------------------- -- /d getProjectDiscussionR :: Text -> Handler Html getProjectDiscussionR = getDiscussion . getProjectDiscussion getProjectDiscussion :: Text -> (DiscussionId -> ExprCommentCond -> DB [Entity Comment]) -> Handler Html getProjectDiscussion project_handle get_root_comments = do muser <- maybeAuth let muser_id = entityKey <$> muser (Entity project_id project, root_comments) <- runYDB $ do p@(Entity project_id project) <- getBy404 (UniqueProjectHandle project_handle) let has_permission = exprCommentProjectPermissionFilter muser_id (val project_id) root_comments <- get_root_comments (projectDiscussion project) has_permission return (p, root_comments) (comment_forest_no_css, _) <- makeProjectCommentForestWidget muser project_id project_handle root_comments def getMaxDepth False mempty let has_comments = not (null root_comments) comment_forest = do comment_forest_no_css toWidget $(cassiusFile "templates/comment.cassius") (comment_form, _) <- generateFormPost commentNewTopicForm defaultLayout $ do snowdriftTitle $ projectName project <> " Discussion" $(widgetFile "project_discuss") -------------------------------------------------------------------------------- -- /d/new getNewProjectDiscussionR :: Text -> Handler Html getNewProjectDiscussionR project_handle = do void requireAuth let widget = commentNewTopicFormWidget defaultLayout (projectDiscussionPage project_handle widget) postNewProjectDiscussionR :: Text -> Handler Html postNewProjectDiscussionR project_handle = do user <- requireAuth Entity _ Project{..} <- runYDB (getBy404 (UniqueProjectHandle project_handle)) postNewComment Nothing user projectDiscussion (makeProjectCommentActionPermissionsMap (Just user) project_handle def) >>= \case ConfirmedPost (Left err) -> do alertDanger err redirect $ NewProjectDiscussionR project_handle ConfirmedPost (Right comment_id) -> redirect $ ProjectCommentR project_handle comment_id Com.Preview (widget, form) -> defaultLayout $ previewWidget form "post" $ projectDiscussionPage project_handle widget
akegalj/snowdrift
Handler/Project.hs
agpl-3.0
55,883
0
32
13,969
12,335
6,045
6,290
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module Data.HPB ( -- * Interface for message. FieldNumber , MessageRep , HasMessageRep(..) , emptyMessageRep , Required(..) , PackedStatus(..) , FieldDef , serializeMessage , serializeMessage' , deserializeMessage , deserializeMessage' , getDelimited , putDelimited -- * Field definitions , int32Field , int64Field , uint32Field , uint64Field , sint32Field , sint64Field , boolField , enumField -- ** Length delimited fields , bytesField , stringField , messageField -- ** Fixed width fields , fixed32Field , fixed64Field , sfixed32Field , sfixed64Field , floatField , doubleField -- * Repeated field definitions , int32RepeatedField , int64RepeatedField , uint32RepeatedField , uint64RepeatedField , sint32RepeatedField , sint64RepeatedField , boolRepeatedField , enumRepeatedField -- ** Length delimited fields , bytesRepeatedField , stringRepeatedField , messageRepeatedField -- ** Fixed width fields , fixed32RepeatedField , fixed64RepeatedField , sfixed32RepeatedField , sfixed64RepeatedField , floatRepeatedField , doubleRepeatedField -- * Utilities , varint64 -- * Re-exports , Data.Int.Int32 , Data.Int.Int64 , Data.Word.Word32 , Data.Word.Word64 , Seq.Seq , Data.Text.Text , B.ByteString , Data.Monoid.Monoid(..) , Data.Semigroup.Semigroup(..) , Data.String.fromString , (Control.Lens.&) , Control.Lens.Lens , Control.Lens.Lens' , Control.Lens.lens , Prelude.Bool(..) , Prelude.Eq , Prelude.Enum(..) , Prelude.Ord , Prelude.Show , Prelude.error , Prelude.show , Prelude.undefined , (Prelude.++) , (Prelude..) ) where import Control.Lens hiding (Getter, Setter) import Control.Monad import Control.Monad.ST import Control.Monad.State.Strict import Data.Binary.IEEE754 import Data.Bits import qualified Data.ByteString as B import qualified Data.ByteString.Unsafe as B import Data.ByteString.Builder import qualified Data.ByteString.Lazy as LazyB import qualified Data.Foldable as Fold import qualified Data.HashMap.Strict as HMap import qualified Data.HashSet as HSet import qualified Data.HashTable.ST.Basic as H import Data.Int import Data.Maybe import Data.Monoid hiding ( (<>) ) import Data.Semigroup import Data.Sequence as Seq import qualified Data.String import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import qualified Data.Vector as V import Data.Word import Foreign import System.IO #if !MIN_VERSION_base(4,13,0) import Control.Monad.Fail( MonadFail ) #endif #if !MIN_VERSION_base(4,8,0) import Data.Functor ((<$>)) #endif ------------------------------------------------------------------------ -- WireType type WireType = Word32 varintType :: WireType varintType = 0 fixed64Type :: WireType fixed64Type = 1 lengthDelimType :: WireType lengthDelimType = 2 fixed32Type :: WireType fixed32Type = 5 ------------------------------------------------------------------------ -- Zigzag primitives zigzag32 :: Int32 -> Word32 zigzag32 n = fromIntegral $ (n `shiftL` 1) `xor` (n `shiftR` 31) izigzag32 :: Word32 -> Int32 izigzag32 x = fromIntegral $ (x `shiftR` 1) `xor` mask where mask = negate (x .&. 0x1) zigzag64 :: Int64 -> Word64 zigzag64 n = fromIntegral $ (n `shiftL` 1) `xor` (n `shiftR` 63) izigzag64 :: Word64 -> Int64 izigzag64 x = fromIntegral $ (x `shiftR` 1) `xor` mask where mask = negate (x .&. 0x1) ------------------------------------------------------------------------ -- Word bytesting primitives. shiftl_w32 :: Word32 -> Int -> Word32 shiftl_w32 = shiftL shiftl_w64 :: Word64 -> Int -> Word64 shiftl_w64 = shiftL word32le :: B.ByteString -> Word32 word32le = \s -> (fromIntegral (s `B.unsafeIndex` 3) `shiftl_w32` 24) .|. (fromIntegral (s `B.unsafeIndex` 2) `shiftl_w32` 16) .|. (fromIntegral (s `B.unsafeIndex` 1) `shiftl_w32` 8) .|. (fromIntegral (s `B.unsafeIndex` 0) ) word64le :: B.ByteString -> Word64 word64le = \s -> (fromIntegral (s `B.unsafeIndex` 7) `shiftl_w64` 56) .|. (fromIntegral (s `B.unsafeIndex` 6) `shiftl_w64` 48) .|. (fromIntegral (s `B.unsafeIndex` 5) `shiftl_w64` 40) .|. (fromIntegral (s `B.unsafeIndex` 4) `shiftl_w64` 32) .|. (fromIntegral (s `B.unsafeIndex` 3) `shiftl_w64` 24) .|. (fromIntegral (s `B.unsafeIndex` 2) `shiftl_w64` 16) .|. (fromIntegral (s `B.unsafeIndex` 1) `shiftl_w64` 8) .|. (fromIntegral (s `B.unsafeIndex` 0) ) ------------------------------------------------------------------------ -- FieldNumber -- | Identifier for a message field. type FieldNumber = Word32 type ReadFn a = B.ByteString -> (a, B.ByteString) readVarint :: ReadFn Word64 readVarint = runState (readVarint' nextByteInByteString) nextByteInByteString :: State B.ByteString Word8 nextByteInByteString = state f where f s0 = case B.uncons s0 of Nothing -> error "Expected varint before end of buffer." Just (w, s) -> (w, s) {-# INLINE readVarint' #-} readVarint' :: Monad m => m Word8 -> m Word64 readVarint' = go 0 0 where go sh old f = do w <- f let new_val = old .|. (fromIntegral (w .&. 0x7f) `shiftL` sh) if (w .&. 0x80) /= 0 then go (sh + 7) new_val f else return new_val readUntilEnd :: ReadFn a -> B.ByteString -> [a] readUntilEnd r s | B.null s = [] | otherwise = let (n,s') = r s in n : readUntilEnd r s' ------------------------------------------------------------------------ -- Serialization primitives varint32 :: Word32 -> Builder varint32 w | low7 == w = word8 (fromIntegral low7) | otherwise = word8 (fromIntegral (0x80 .|. low7)) <> varint32 (w `shiftR` 7) where low7 = w .&. 0x7F varint64 :: Word64 -> Builder varint64 w | low7 == w = word8 (fromIntegral low7) | otherwise = word8 (fromIntegral (0x80 .|. low7)) <> varint64 (w `shiftR` 7) where low7 = w .&. 0x7F fieldNum :: FieldNumber -> WireType -> Builder fieldNum num tp = varint32 (num `shiftL` 3 .|. tp) ------------------------------------------------------------------------ -- MessageRep data Required a = Req | Opt a data MessageRep a = Rep { initMessage :: !a , mergeMessage :: !(a -> a -> a) , messageName :: !Text , fieldDeserializers :: !(HMap.HashMap FieldNumber (FieldDeserializer a)) , fieldSerializers :: !(V.Vector (a -> Builder)) , requiredFields :: !(V.Vector (FieldNumber, Text)) } insSerializer :: Lens' a f -> (f -> Builder) -> MessageRep a -> MessageRep a insSerializer l serializer rep = rep { fieldSerializers = V.snoc (fieldSerializers rep) (serializer . view l) } insDeserializer :: FieldNumber -> FieldDeserializer a -> MessageRep a -> MessageRep a insDeserializer num fd rep = rep { fieldDeserializers = HMap.insert num fd (fieldDeserializers rep) } insRequired :: FieldNumber -> Text -> MessageRep a -> MessageRep a insRequired num nm rep = rep { requiredFields = V.snoc (requiredFields rep) (num, nm) } type SeenFields s = H.HashTable s FieldNumber () markSeen :: SeenFields s -> FieldNumber -> ST s () markSeen seen n = H.insert seen n () checkSeen :: SeenFields s -> MessageRep a -> ST s () checkSeen seenFields rep = do V.forM_ (requiredFields rep) $ \(num,nm) -> do mr <- H.lookup seenFields num when (isNothing mr) $ do fail $ "Missing required field " ++ Text.unpack nm ++ " when deserializing a " ++ Text.unpack (messageName rep) ++ " message." type GetST s = StateT B.ByteString (ST s) newtype FieldDeserializer a = FD { unFD :: forall s . SeenFields s -> WireType -> a -> GetST s a } deserializeMessage :: HasMessageRep a => B.ByteString -> a deserializeMessage = deserializeMessage' messageRep deserializeMessage' :: MessageRep a -> B.ByteString -> a deserializeMessage' rep s = runST $ do seenFields <- H.new evalStateT (populateMessage seenFields rep (initMessage rep)) s getDelimited :: HasMessageRep a => Handle -> IO a getDelimited h = do len <- alloca $ \p -> do readVarint' $ do read_cnt <- hGetBuf h p 1 when (read_cnt /= 1) $ fail "Could not read next byte." peek p bs <- B.hGet h (fromIntegral len) return $ deserializeMessage bs readFixedField :: Int -> ReadFn B.ByteString readFixedField n s | B.length s < n = error "Unexpected end of buffer." | otherwise = B.splitAt n s readLengthDelimField :: GetST s B.ByteString readLengthDelimField = do len <- doRead readVarint doRead $ readFixedField (fromIntegral len) doRead :: MonadState B.ByteString m => (B.ByteString -> (a, B.ByteString)) -> m a doRead f = do s <- get let (r, s') = f s put s' return r populateMessage :: SeenFields s -> MessageRep a -> a -> GetST s a populateMessage seenFields rep msg = do isEmpty <- gets B.null if isEmpty then do lift $ checkSeen seenFields rep return msg else do idx <- doRead readVarint when (idx >= 2^(32::Int)) $ do fail $ "Field index is out of range." let num = fromIntegral (idx `shiftR` 3) tp = fromIntegral $ idx .&. 0x7 case HMap.lookup num (fieldDeserializers rep) of Just fd -> do msg' <- unFD fd seenFields tp msg populateMessage seenFields rep msg' Nothing -> do -- Skip message case tp of -- varint type 0 -> do _ <- doRead readVarint populateMessage seenFields rep msg -- fixed64 type. 1 -> do _ <- doRead $ readFixedField 8 populateMessage seenFields rep msg -- length delim type 2 -> do _ <- readLengthDelimField populateMessage seenFields rep msg -- fixed32 type 5 -> do _ <- doRead $ readFixedField 4 populateMessage seenFields rep msg _ -> fail $ "Unsupported field type " ++ show tp ++ " before end of message." serializeMessage :: HasMessageRep a => a -> Builder serializeMessage = serializeMessage' messageRep serializeMessage' :: MessageRep a -> a -> Builder serializeMessage' rep x = V.foldr (\f s -> f x <> s) mempty (fieldSerializers rep) -- | Write a delimited message to the handle. It is recommended that the handle is -- set to binary and block buffering mode. See @hSetBinaryMode@ and @hSetBuffering@. putDelimited :: HasMessageRep a => Handle -> a -> IO () putDelimited h v = do hPutBuilder h (lengthDelimBuilder (serializeMessage v)) hFlush h emptyMessageRep :: Monoid a => Text -> MessageRep a emptyMessageRep nm = Rep { initMessage = mempty , mergeMessage = mappend , messageName = nm , fieldSerializers = V.empty , fieldDeserializers = HMap.empty , requiredFields = V.empty } type InsertFn a f = f -> a -> a setTo :: Lens' a f -> InsertFn a f setTo l = (l .~) appendTo :: Lens' a (Seq f) -> InsertFn a f appendTo l v = l %~ (Seq.|> v) maybeApplyTo :: InsertFn a f -> InsertFn a (Maybe f) maybeApplyTo g = \mv -> case mv of Nothing -> id Just v -> g v -- | This is the type for functions used to add fields to the -- message representation. type FieldDef a f = FieldNumber -> Lens' a f -> MessageRep a -> MessageRep a unexpectedType :: MonadFail m => Text -> Text -> m a unexpectedType mnm nm = do fail $ "Unexpected type when decoding field " ++ Text.unpack nm ++ " in " ++ Text.unpack mnm serializeOpt :: Eq v => v -> (v -> Builder) -> v -> Builder serializeOpt d f v | v == d = mempty | otherwise = f v encodeField :: FieldNumber -> WireType -> Builder -> Builder encodeField num tp v = fieldNum num tp <> v -- | Function for reading a varint field. {-# INLINE varintField #-} varintField :: Eq f => (f -> Builder) -- ^ Projection function for mapping from field to encoding. -> (Word64 -> Maybe f) -- ^ Injection function for mapping from varint to field value. -> Text -> Required f -> FieldDef a f varintField proj inj = \nm req num fieldLens rep -> do case req of Req -> rep & insSerializer fieldLens (encodeField num varintType . proj) & insDeserializer num (FD deserial) & insRequired num nm where mnm = messageName rep deserial seen tp msg | tp == varintType = do lift $ markSeen seen num w <- doRead readVarint return $ msg & maybeApplyTo (setTo fieldLens) (inj w) | otherwise = do unexpectedType mnm nm Opt d -> rep & insSerializer fieldLens serial & insDeserializer num (FD deserial) where mnm = messageName rep serial = serializeOpt d (encodeField num varintType . proj) deserial _ tp msg | tp == varintType = do w <- doRead readVarint return $ msg & maybeApplyTo (setTo fieldLens) (inj w) | tp == lengthDelimType = do intValues <- readLengthDelimField let mv = lastOf folded (mapMaybe inj (readUntilEnd readVarint intValues)) return $ msg & maybeApplyTo (setTo fieldLens) mv | otherwise = do unexpectedType mnm nm -- | Update field with last varint in field. updateLastFixed :: Int -> (B.ByteString -> f) -> InsertFn a f -> InsertFn a B.ByteString updateLastFixed n inj setter a x | l `rem` n /= 0 = error "Fixed field has unexpected length." | B.null a = x | otherwise = setter (inj end) x where l = B.length a end = B.drop (l - n) a -- | Function for reading a varint field. {-# INLINE fixedField #-} fixedField :: Eq f => WireType -> Int -> (f -> Builder) -> (B.ByteString -> f) -> Text -> Required f -> FieldDef a f fixedField wireType n proj inj nm req num fieldLens rep = do let encode = encodeField num wireType . proj case req of Req -> rep & insSerializer fieldLens encode & insDeserializer num (FD deserial) & insRequired num nm where mnm = messageName rep deserial seen tp msg | tp == wireType = do lift $ markSeen seen num wb <- doRead $ readFixedField n return $ msg & fieldLens .~ inj wb | otherwise = do unexpectedType mnm nm Opt d -> rep & insSerializer fieldLens (serializeOpt d encode) & insDeserializer num (FD deserial) where mnm = messageName rep deserial _ tp msg | tp == wireType = do wb <- doRead $ readFixedField n return $ msg & fieldLens .~ inj wb | tp == lengthDelimType = do f <- readLengthDelimField return $ updateLastFixed n inj (fieldLens .~) f msg | otherwise = do unexpectedType mnm nm encodeStrictLengthDelimField :: FieldNumber -> B.ByteString -> Builder encodeStrictLengthDelimField num b = encodeField num lengthDelimType $ varint64 (fromIntegral (B.length b)) <> byteString b lengthDelimBuilder :: Builder -> Builder lengthDelimBuilder b = varint64 (fromIntegral (LazyB.length s)) <> lazyByteString s where s = toLazyByteString b encodeLengthDelimField :: FieldNumber -> Builder -> Builder encodeLengthDelimField num b = do encodeField num lengthDelimType (lengthDelimBuilder b) recordFieldNum :: FieldNumber -> FieldDeserializer a -> FieldDeserializer a recordFieldNum num (FD d) = FD deserial where deserial seen tp msg = do lift $ markSeen seen num d seen tp msg deserializeLengthDelimField :: MessageRep a -> Text -> InsertFn a B.ByteString -> FieldDeserializer a deserializeLengthDelimField rep nm setter = FD deserial where mnm = messageName rep deserial _ tp msg | tp == lengthDelimType = do w <- readLengthDelimField return $ msg & setter w | otherwise = do unexpectedType mnm nm -- | Function for reading a varint field. {-# INLINE lengthDelimField #-} lengthDelimField :: Eq f => (f -> B.ByteString) -- ^ Projection function for mapping from field to encoding. -> (B.ByteString -> f) -- ^ Injection function for mapping from data to field value. -> Text -> Required f -> FieldDef a f lengthDelimField proj inj nm req num fieldLens rep = do let encode = encodeStrictLengthDelimField num . proj let decode = deserializeLengthDelimField rep nm (setTo fieldLens . inj) case req of Req -> rep & insSerializer fieldLens encode & insDeserializer num (recordFieldNum num decode) & insRequired num nm Opt d -> rep & insSerializer fieldLens (serializeOpt d encode) & insDeserializer num decode int32Field :: Text -> Required Int32 -> FieldDef a Int32 int32Field = varintField (varint32 . fromIntegral) (Just . fromIntegral) {-# INLINE int32Field #-} int64Field :: Text -> Required Int64 -> FieldDef a Int64 int64Field = varintField (varint64 . fromIntegral) (Just . fromIntegral) {-# INLINE int64Field #-} uint32Field :: Text -> Required Word32 -> FieldDef a Word32 uint32Field = varintField varint32 (Just . fromIntegral) {-# INLINE uint32Field #-} uint64Field :: Text -> Required Word64 -> FieldDef a Word64 uint64Field = varintField varint64 Just {-# INLINE uint64Field #-} sint32Field :: Text -> Required Int32 -> FieldDef a Int32 sint32Field = varintField (varint32 . zigzag32) (Just . izigzag32 . fromIntegral) {-# INLINE sint32Field #-} sint64Field :: Text -> Required Int64 -> FieldDef a Int64 sint64Field = varintField (varint64 . zigzag64) (Just . izigzag64) {-# INLINE sint64Field #-} boolField :: Text -> Required Bool -> FieldDef a Bool boolField = varintField (word8 . fromIntegral . fromEnum) (Just . (/= 0)) enumSetter :: Enum x => [x] -> Word64 -> Maybe x enumSetter legal = setter where legalSet = HSet.fromList $ fmap (fromIntegral.fromEnum) legal setter w | HSet.member w legalSet = Just (toEnum (fromIntegral w)) | otherwise = Nothing enumField :: (Enum x, Eq x) => Text -> Required x -- ^ Default value for type. -> [x] -- ^ List of all legal enum values. -> FieldDef a x enumField nm req legal = varintField (varint32 . fromIntegral . fromEnum) (enumSetter legal) nm req fixed32Field :: Text -> Required Word32 -> FieldDef a Word32 fixed32Field = fixedField fixed32Type 4 word32LE word32le fixed64Field :: Text -> Required Word64 -> FieldDef a Word64 fixed64Field = fixedField fixed64Type 8 word64LE word64le sfixed32Field :: Text -> Required Int32 -> FieldDef a Int32 sfixed32Field = fixedField fixed32Type 4 int32LE (fromIntegral . word32le) sfixed64Field :: Text -> Required Int64 -> FieldDef a Int64 sfixed64Field = fixedField fixed64Type 8 int64LE (fromIntegral . word64le) floatField :: Text -> Required Float -> FieldDef a Float floatField = fixedField fixed32Type 4 floatLE (wordToFloat . word32le) doubleField :: Text -> Required Double -> FieldDef a Double doubleField = fixedField fixed64Type 8 doubleLE (wordToDouble . word64le) bytesField :: Text -> Required B.ByteString -> FieldDef a B.ByteString bytesField = lengthDelimField id id stringField :: Text -> Required Text -> FieldDef a Text stringField = lengthDelimField Text.encodeUtf8 Text.decodeUtf8 messageField :: (Semigroup m, Monoid m) => MessageRep m -> Text -> Bool -- ^ Indicates if the message is required. -> FieldDef a m messageField field_rep nm req num fieldLens rep = rep & insSerializer fieldLens serial & insDeserializer num (if req then recordFieldNum num deserial else deserial) & (if req then insRequired num nm else id) where serial = encodeLengthDelimField num . serializeMessage' field_rep deserial = deserializeLengthDelimField rep nm (setTo fieldLens . deserializeMessage' field_rep) -- | This is the type for functions used to add fields to the -- message representation. type RepeatedFieldDef a f = FieldNumber -> Lens' a (Seq f) -> MessageRep a -> MessageRep a -- | Indicates if repeated field may be packed. data PackedStatus = Packed | Unpacked -- | Serialize a field that may be packed. serializePackedField :: FieldNumber -> WireType -- ^ Wire type for individual values. -> Seq Builder -> Builder serializePackedField num tp elts | len == 0 = mempty | len == 1 = fieldNum num tp <> (elts `Seq.index` 0) | otherwise = encodeLengthDelimField num $ Fold.fold elts where -- Get number of elements len = Seq.length elts serializeRepeatedField :: PackedStatus -> (f -> Builder) -> WireType -> FieldNumber -> Seq f -> Builder serializeRepeatedField packed proj tp num elts = case packed of Packed -> serializePackedField tp num (proj <$> elts) Unpacked -> Fold.fold ((\v -> fieldNum num tp <> proj v) <$> elts) -- | Function for reading a varint field. {-# INLINE varintRepeatedField #-} varintRepeatedField :: forall a f . Eq f => (f -> Builder) -- ^ Projection function for mapping from field to encoding. -> (Word64 -> Maybe f) -- ^ Injection function for mapping from varint to field value. -> Text -> PackedStatus -> RepeatedFieldDef a f varintRepeatedField proj inj nm packed num fieldLens rep = rep & insSerializer fieldLens serial & insDeserializer num (FD deserial) where mnm = messageName rep serial = serializeRepeatedField packed proj varintType num deserial _ tp msg | tp == varintType = do w <- doRead readVarint return $ msg & maybeApplyTo (appendTo fieldLens) (inj w) | tp == lengthDelimType = do s0 <- readLengthDelimField let intValues = mapMaybe inj $ readUntilEnd readVarint s0 return $ msg & fieldLens %~ (Seq.>< Seq.fromList intValues) | otherwise = do unexpectedType mnm nm -- | Function for reading a varint field. {-# INLINE fixedRepeatedField #-} fixedRepeatedField :: Eq f => WireType -> Int -> (f -> Builder) -> (B.ByteString -> f) -> Text -> PackedStatus -> RepeatedFieldDef a f fixedRepeatedField wireType n proj inj nm packed num fieldLens rep = rep & insSerializer fieldLens serial & insDeserializer num (FD deserial) where mnm = messageName rep serial = serializeRepeatedField packed proj wireType num deserial _ tp msg | tp == wireType = do wb <- doRead $ readFixedField n return $ msg & appendTo fieldLens (inj wb) | tp == lengthDelimType = do s0 <- readLengthDelimField let intValues = inj <$> readUntilEnd (readFixedField n) s0 return $ msg & fieldLens %~ (Seq.>< Seq.fromList intValues) | otherwise = do unexpectedType mnm nm -- | Function for reading a varint field. {-# INLINE lengthDelimRepeatedField #-} lengthDelimRepeatedField :: Eq f => (f -> B.ByteString) -- ^ Projection function for mapping from field to encoding. -> (B.ByteString -> f) -- ^ Injection function for mapping from data to field value. -> Text -> RepeatedFieldDef a f lengthDelimRepeatedField proj inj nm num fieldLens rep = rep & insSerializer fieldLens serial & insDeserializer num (FD deserial) where mnm = messageName rep serial = Fold.fold . fmap (encodeStrictLengthDelimField num . proj) deserial _ tp msg | tp == lengthDelimType = do w <- readLengthDelimField return $ msg & fieldLens %~ (Seq.|> inj w) | otherwise = do unexpectedType mnm nm int32RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Int32 int32RepeatedField = varintRepeatedField (varint32 . fromIntegral) (Just . fromIntegral) int64RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Int64 int64RepeatedField = varintRepeatedField (varint64 . fromIntegral) (Just . fromIntegral) uint32RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Word32 uint32RepeatedField = varintRepeatedField varint32 (Just . fromIntegral) uint64RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Word64 uint64RepeatedField = varintRepeatedField varint64 Just sint32RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Int32 sint32RepeatedField = varintRepeatedField (varint32 . zigzag32) (Just . izigzag32 . fromIntegral) sint64RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Int64 sint64RepeatedField = varintRepeatedField (varint64 . zigzag64) (Just . izigzag64) boolRepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Bool boolRepeatedField = varintRepeatedField (word8 . fromIntegral . fromEnum) (Just . (/= 0)) enumRepeatedField :: (Eq x, Enum x) => Text -> PackedStatus -> [x] -> RepeatedFieldDef a x enumRepeatedField nm req legal = varintRepeatedField (varint32 . fromIntegral . fromEnum) (enumSetter legal) nm req fixed32RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Word32 fixed32RepeatedField = fixedRepeatedField fixed32Type 4 word32LE word32le fixed64RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Word64 fixed64RepeatedField = fixedRepeatedField fixed32Type 8 word64LE word64le sfixed32RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Int32 sfixed32RepeatedField = fixedRepeatedField fixed32Type 4 int32LE (fromIntegral . word32le) sfixed64RepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Int64 sfixed64RepeatedField = fixedRepeatedField fixed64Type 8 int64LE (fromIntegral . word64le) floatRepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Float floatRepeatedField = fixedRepeatedField fixed32Type 4 floatLE (wordToFloat . word32le) doubleRepeatedField :: Text -> PackedStatus -> RepeatedFieldDef a Double doubleRepeatedField = fixedRepeatedField fixed64Type 8 doubleLE (wordToDouble . word64le) bytesRepeatedField :: Text -> RepeatedFieldDef a B.ByteString bytesRepeatedField = lengthDelimRepeatedField id id stringRepeatedField :: Text -> RepeatedFieldDef a Text stringRepeatedField = lengthDelimRepeatedField Text.encodeUtf8 Text.decodeUtf8 messageRepeatedField :: MessageRep m -> Text -> RepeatedFieldDef a m messageRepeatedField field_rep nm num fieldLens rep = rep & insSerializer fieldLens (Fold.fold . fmap serial) & insDeserializer num deserial where serial = encodeLengthDelimField num . serializeMessage' field_rep deserial = deserializeLengthDelimField rep nm (appendTo fieldLens . deserializeMessage' field_rep) class HasMessageRep tp where messageRep :: MessageRep tp
GaloisInc/hpb
src/Data/HPB.hs
apache-2.0
28,653
0
23
8,048
7,918
4,069
3,849
679
7
{-# LANGUAGE OverloadedStrings #-} module Actions.ResetPassword.Handler (handler) where import qualified Data.Text.Lazy as TL import Web.Scotty (params, redirect) import qualified Persistence.User as U import qualified Model.ActionKey as AC import qualified Persistence.ActionKey as AC import App (Action, PGPool, runQuery) import Auth (doLoginAction) import Actions.Responses (errorResponse) import qualified Actions.ChangePassword.Url as Actions.ChangePassword {-# ANN module ("HLint: ignore Use camelCase" :: String) #-} {-# ANN module ("HLint: ignore Redundant do" :: String) #-} handler :: PGPool -> Action handler pool = do ps <- params case lookup "key" ps of Nothing -> errorResponse "Password reset failed: incorrect key in the URL." Just key -> do mActionKey <- runQuery pool $ AC.useActionKey (TL.toStrict key) AC.ResetPassword case mActionKey of Nothing -> errorResponse "Invalid password reset key or the key has been already used." Just actionKey -> do mUser <- runQuery pool $ U.getUserById $ AC.ac_user_id actionKey case mUser of Nothing -> errorResponse "We are sorry, an internal error occured, please contact the administrator." Just user -> do doLoginAction pool user $ redirect $ TL.pack Actions.ChangePassword.url
DataStewardshipPortal/ds-wizard
DSServer/app/Actions/ResetPassword/Handler.hs
apache-2.0
1,359
0
24
291
288
155
133
28
4
-- | Specific configuration for Joey Hess's sites. Probably not useful to -- others except as an example. module Propellor.Property.SiteSpecific.JoeySites where import Propellor import qualified Propellor.Property.Apt as Apt import qualified Propellor.Property.File as File import qualified Propellor.Property.Gpg as Gpg import qualified Propellor.Property.Ssh as Ssh import qualified Propellor.Property.Git as Git import qualified Propellor.Property.Cron as Cron import qualified Propellor.Property.Service as Service import qualified Propellor.Property.User as User import qualified Propellor.Property.Obnam as Obnam import qualified Propellor.Property.Apache as Apache import qualified Propellor.Property.Postfix as Postfix import Utility.SafeCommand import Utility.FileMode import Data.List import System.Posix.Files import Data.String.Utils scrollBox :: Property HasInfo scrollBox = propertyList "scroll server" $ props & User.accountFor "scroll" & Git.cloned "scroll" "git://git.kitenet.net/scroll" (d </> "scroll") Nothing & Apt.installed ["ghc", "make", "cabal-install", "libghc-vector-dev", "libghc-bytestring-dev", "libghc-mtl-dev", "libghc-ncurses-dev", "libghc-random-dev", "libghc-monad-loops-dev", "libghc-ifelse-dev", "libghc-case-insensitive-dev", "libghc-data-default-dev"] & userScriptProperty "scroll" [ "cd " ++ d </> "scroll" , "git pull" , "cabal configure" , "make" ] & s `File.hasContent` [ "#!/bin/sh" , "set -e" , "echo Preparing to run scroll!" , "cd " ++ d , "mkdir -p tmp" , "TMPDIR= t=$(tempfile -d tmp)" , "export t" , "rm -f \"$t\"" , "mkdir \"$t\"" , "cd \"$t\"" , "echo" , "echo Press Enter to start the game." , "read me" , "SHELL=/bin/sh script --timing=timing -c " ++ g ] `onChange` (s `File.mode` (combineModes (ownerWriteMode:readModes ++ executeModes))) & g `File.hasContent` [ "#!/bin/sh" , "if ! ../../scroll/scroll; then" , "echo Scroll seems to have ended unexpectedly. Possibly a bug.." , "else" , "echo Thanks for playing scroll! https://joeyh.name/code/scroll/" , "fi" , "echo Your game was recorded, as ID:$(basename \"$t\")" , "echo if you would like to talk about how it went, email [email protected]" , "echo 'or, type comments below (finish with a dot on its own line)'" , "echo" , "echo Your comments:" , "mail -s \"scroll test $t\" [email protected]" ] `onChange` (g `File.mode` (combineModes (ownerWriteMode:readModes ++ executeModes))) & Apt.installed ["bsd-mailx"] -- prevent port forwarding etc by not letting scroll log in via ssh & Ssh.sshdConfig `File.containsLine` ("DenyUsers scroll") `onChange` Ssh.restarted & cmdProperty "chsh" ["scroll", "-s", s] & User.hasPassword "scroll" & Apt.serviceInstalledRunning "telnetd" & Apt.installed ["shellinabox"] & File.hasContent "/etc/default/shellinabox" [ "# Deployed by propellor" , "SHELLINABOX_DAEMON_START=1" , "SHELLINABOX_PORT=4242" , "SHELLINABOX_ARGS=\"--disable-ssl --no-beep --service=:scroll:scroll:" ++ d ++ ":" ++ s ++ "\"" ] `onChange` Service.restarted "shellinabox" & Service.running "shellinabox" where d = "/home/scroll" s = d </> "login.sh" g = d </> "game.sh" oldUseNetServer :: [Host] -> Property HasInfo oldUseNetServer hosts = propertyList "olduse.net server" $ props & Apt.installed ["leafnode"] & oldUseNetInstalled "oldusenet-server" & Obnam.latestVersion & oldUseNetBackup & check (not . isSymbolicLink <$> getSymbolicLinkStatus newsspool) (property "olduse.net spool in place" $ makeChange $ do removeDirectoryRecursive newsspool createSymbolicLink (datadir </> "news") newsspool ) & "/etc/news/leafnode/config" `File.hasContent` [ "# olduse.net configuration (deployed by propellor)" , "expire = 1000000" -- no expiry via texpire , "server = " -- no upstream server , "debugmode = 1" , "allowSTRANGERS = 42" -- lets anyone connect , "nopost = 1" -- no new posting (just gather them) ] & "/etc/hosts.deny" `File.lacksLine` "leafnode: ALL" & Apt.serviceInstalledRunning "openbsd-inetd" & File.notPresent "/etc/cron.daily/leafnode" & File.notPresent "/etc/cron.d/leafnode" & Cron.niceJob "oldusenet-expire" (Cron.Times "11 1 * * *") "news" newsspool expirecommand & Cron.niceJob "oldusenet-uucp" (Cron.Times "*/5 * * * *") "news" "/" uucpcommand & Apache.siteEnabled "nntp.olduse.net" nntpcfg where newsspool = "/var/spool/news" datadir = "/var/spool/oldusenet" expirecommand = intercalate ";" [ "find \\( -path ./out.going -or -path ./interesting.groups -or -path './*/.overview' \\) -prune -or -type f -ctime +60 -print | xargs --no-run-if-empty rm" , "find -type d -empty | xargs --no-run-if-empty rmdir" ] uucpcommand = "/usr/bin/uucp " ++ datadir nntpcfg = apachecfg "nntp.olduse.net" False [ " DocumentRoot " ++ datadir ++ "/" , " <Directory " ++ datadir ++ "/>" , " Options Indexes FollowSymlinks" , " AllowOverride None" , Apache.allowAll , " </Directory>" ] oldUseNetBackup = Obnam.backup datadir (Cron.Times "33 4 * * *") [ "--repository=sftp://[email protected]/~/olduse.net" , "--client-name=spool" , "--ssh-key=" ++ keyfile ] Obnam.OnlyClient `requires` Ssh.keyImported' (Just keyfile) SshRsa "root" (Context "olduse.net") `requires` Ssh.knownHost hosts "usw-s002.rsync.net" "root" keyfile = "/root/.ssh/olduse.net.key" oldUseNetShellBox :: Property HasInfo oldUseNetShellBox = propertyList "olduse.net shellbox" $ props & oldUseNetInstalled "oldusenet" & Service.running "shellinabox" oldUseNetInstalled :: Apt.Package -> Property HasInfo oldUseNetInstalled pkg = check (not <$> Apt.isInstalled pkg) $ propertyList ("olduse.net " ++ pkg) $ props & Apt.installed (words "build-essential devscripts debhelper git libncursesw5-dev libpcre3-dev pkg-config bison libicu-dev libidn11-dev libcanlock2-dev libuu-dev ghc libghc-strptime-dev libghc-hamlet-dev libghc-ifelse-dev libghc-hxt-dev libghc-utf8-string-dev libghc-missingh-dev libghc-sha-dev") `describe` "olduse.net build deps" & scriptProperty [ "rm -rf /root/tmp/oldusenet" -- idenpotency , "git clone git://olduse.net/ /root/tmp/oldusenet/source" , "cd /root/tmp/oldusenet/source/" , "dpkg-buildpackage -us -uc" , "dpkg -i ../" ++ pkg ++ "_*.deb || true" , "apt-get -fy install" -- dependencies , "rm -rf /root/tmp/oldusenet" ] `describe` "olduse.net built" kgbServer :: Property HasInfo kgbServer = propertyList desc $ props & installed & File.hasPrivContent "/etc/kgb-bot/kgb.conf" anyContext `onChange` Service.restarted "kgb-bot" where desc = "kgb.kitenet.net setup" installed = withOS desc $ \o -> case o of (Just (System (Debian Unstable) _)) -> ensureProperty $ propertyList desc [ Apt.serviceInstalledRunning "kgb-bot" , "/etc/default/kgb-bot" `File.containsLine` "BOT_ENABLED=1" `describe` "kgb bot enabled" `onChange` Service.running "kgb-bot" ] _ -> error "kgb server needs Debian unstable (for kgb-bot 1.31+)" mumbleServer :: [Host] -> Property HasInfo mumbleServer hosts = combineProperties hn $ props & Apt.serviceInstalledRunning "mumble-server" & Obnam.latestVersion & Obnam.backup "/var/lib/mumble-server" (Cron.Times "55 5 * * *") [ "--repository=sftp://[email protected]/~/" ++ hn ++ ".obnam" , "--client-name=mumble" ] Obnam.OnlyClient `requires` Ssh.keyImported SshRsa "root" (Context hn) `requires` Ssh.knownHost hosts "usw-s002.rsync.net" "root" & trivial (cmdProperty "chown" ["-R", "mumble-server:mumble-server", "/var/lib/mumble-server"]) where hn = "mumble.debian.net" -- git.kitenet.net and git.joeyh.name gitServer :: [Host] -> Property HasInfo gitServer hosts = propertyList "git.kitenet.net setup" $ props & Obnam.latestVersion & Obnam.backupEncrypted "/srv/git" (Cron.Times "33 3 * * *") [ "--repository=sftp://[email protected]/~/git.kitenet.net" , "--ssh-key=" ++ sshkey , "--client-name=wren" -- historical ] Obnam.OnlyClient (Gpg.GpgKeyId "1B169BE1") `requires` Ssh.keyImported' (Just sshkey) SshRsa "root" (Context "git.kitenet.net") `requires` Ssh.knownHost hosts "usw-s002.rsync.net" "root" `requires` Ssh.authorizedKeys "family" (Context "git.kitenet.net") `requires` User.accountFor "family" & Apt.installed ["git", "rsync", "gitweb"] & Apt.installed ["git-annex"] & Apt.installed ["kgb-client"] & File.hasPrivContentExposed "/etc/kgb-bot/kgb-client.conf" anyContext `requires` File.dirExists "/etc/kgb-bot/" & Git.daemonRunning "/srv/git" & "/etc/gitweb.conf" `File.containsLines` [ "$projectroot = '/srv/git';" , "@git_base_url_list = ('git://git.kitenet.net', 'http://git.kitenet.net/git', 'https://git.kitenet.net/git', 'ssh://git.kitenet.net/srv/git');" , "# disable snapshot download; overloads server" , "$feature{'snapshot'}{'default'} = [];" ] `describe` "gitweb configured" -- Repos push on to github. & Ssh.knownHost hosts "github.com" "joey" -- I keep the website used for gitweb checked into git.. & Git.cloned "root" "/srv/git/joey/git.kitenet.net.git" "/srv/web/git.kitenet.net" Nothing & website "git.kitenet.net" & website "git.joeyh.name" & Apache.modEnabled "cgi" where sshkey = "/root/.ssh/git.kitenet.net.key" website hn = apacheSite hn True [ " DocumentRoot /srv/web/git.kitenet.net/" , " <Directory /srv/web/git.kitenet.net/>" , " Options Indexes ExecCGI FollowSymlinks" , " AllowOverride None" , " AddHandler cgi-script .cgi" , " DirectoryIndex index.cgi" , Apache.allowAll , " </Directory>" , "" , " ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/" , " <Directory /usr/lib/cgi-bin>" , " SetHandler cgi-script" , " Options ExecCGI" , " </Directory>" ] type AnnexUUID = String -- | A website, with files coming from a git-annex repository. annexWebSite :: Git.RepoUrl -> HostName -> AnnexUUID -> [(String, Git.RepoUrl)] -> Property HasInfo annexWebSite origin hn uuid remotes = propertyList (hn ++" website using git-annex") $ props & Git.cloned "joey" origin dir Nothing `onChange` setup & alias hn & postupdatehook `File.hasContent` [ "#!/bin/sh" , "exec git update-server-info" ] `onChange` (postupdatehook `File.mode` (combineModes (ownerWriteMode:readModes ++ executeModes))) & setupapache where dir = "/srv/web/" ++ hn postupdatehook = dir </> ".git/hooks/post-update" setup = userScriptProperty "joey" setupscript setupscript = [ "cd " ++ shellEscape dir , "git annex reinit " ++ shellEscape uuid ] ++ map addremote remotes ++ [ "git annex get" , "git update-server-info" ] addremote (name, url) = "git remote add " ++ shellEscape name ++ " " ++ shellEscape url setupapache = apacheSite hn True [ " ServerAlias www."++hn , "" , " DocumentRoot /srv/web/"++hn , " <Directory /srv/web/"++hn++">" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , " </Directory>" , " <Directory /srv/web/"++hn++">" , " Options Indexes FollowSymLinks ExecCGI" , " AllowOverride None" , " AddHandler cgi-script .cgi" , " DirectoryIndex index.html index.cgi" , Apache.allowAll , " </Directory>" ] apacheSite :: HostName -> Bool -> Apache.ConfigFile -> RevertableProperty apacheSite hn withssl middle = Apache.siteEnabled hn $ apachecfg hn withssl middle apachecfg :: HostName -> Bool -> Apache.ConfigFile -> Apache.ConfigFile apachecfg hn withssl middle | withssl = vhost False ++ vhost True | otherwise = vhost False where vhost ssl = [ "<VirtualHost *:"++show port++">" , " ServerAdmin [email protected]" , " ServerName "++hn++":"++show port ] ++ mainhttpscert ssl ++ middle ++ [ "" , " ErrorLog /var/log/apache2/error.log" , " LogLevel warn" , " CustomLog /var/log/apache2/access.log combined" , " ServerSignature On" , " " , " <Directory \"/usr/share/apache2/icons\">" , " Options Indexes MultiViews" , " AllowOverride None" , Apache.allowAll , " </Directory>" , "</VirtualHost>" ] where port = if ssl then 443 else 80 :: Int mainhttpscert :: Bool -> Apache.ConfigFile mainhttpscert False = [] mainhttpscert True = [ " SSLEngine on" , " SSLCertificateFile /etc/ssl/certs/web.pem" , " SSLCertificateKeyFile /etc/ssl/private/web.pem" , " SSLCertificateChainFile /etc/ssl/certs/startssl.pem" ] gitAnnexDistributor :: Property HasInfo gitAnnexDistributor = combineProperties "git-annex distributor, including rsync server and signer" $ props & Apt.installed ["rsync"] & File.hasPrivContent "/etc/rsyncd.conf" (Context "git-annex distributor") `onChange` Service.restarted "rsync" & File.hasPrivContent "/etc/rsyncd.secrets" (Context "git-annex distributor") `onChange` Service.restarted "rsync" & "/etc/default/rsync" `File.containsLine` "RSYNC_ENABLE=true" `onChange` Service.running "rsync" & endpoint "/srv/web/downloads.kitenet.net/git-annex/autobuild" & endpoint "/srv/web/downloads.kitenet.net/git-annex/autobuild/x86_64-apple-yosemite" & endpoint "/srv/web/downloads.kitenet.net/git-annex/autobuild/windows" -- git-annex distribution signing key & Gpg.keyImported (Gpg.GpgKeyId "89C809CB") "joey" where endpoint d = combineProperties ("endpoint " ++ d) [ File.dirExists d , File.ownerGroup d "joey" "joey" ] downloads :: [Host] -> Property HasInfo downloads hosts = annexWebSite "/srv/git/downloads.git" "downloads.kitenet.net" "840760dc-08f0-11e2-8c61-576b7e66acfd" [("eubackup", "ssh://eubackup.kitenet.net/~/lib/downloads/")] `requires` Ssh.knownHost hosts "eubackup.kitenet.net" "joey" tmp :: Property HasInfo tmp = propertyList "tmp.kitenet.net" $ props & annexWebSite "/srv/git/joey/tmp.git" "tmp.kitenet.net" "26fd6e38-1226-11e2-a75f-ff007033bdba" [] & twitRss & pumpRss -- Twitter, you kill us. twitRss :: Property HasInfo twitRss = combineProperties "twitter rss" $ props & Git.cloned "joey" "git://git.kitenet.net/twitrss.git" dir Nothing & check (not <$> doesFileExist (dir </> "twitRss")) compiled & feed "http://twitter.com/search/realtime?q=git-annex" "git-annex-twitter" & feed "http://twitter.com/search/realtime?q=olduse+OR+git-annex+OR+debhelper+OR+etckeeper+OR+ikiwiki+-ashley_ikiwiki" "twittergrep" where dir = "/srv/web/tmp.kitenet.net/twitrss" crontime = Cron.Times "15 * * * *" feed url desc = Cron.job desc crontime "joey" dir $ "./twitRss " ++ shellEscape url ++ " > " ++ shellEscape ("../" ++ desc ++ ".rss") compiled = userScriptProperty "joey" [ "cd " ++ dir , "ghc --make twitRss" ] `requires` Apt.installed [ "libghc-xml-dev" , "libghc-feed-dev" , "libghc-tagsoup-dev" ] -- Work around for expired ssl cert. pumpRss :: Property NoInfo pumpRss = Cron.job "pump rss" (Cron.Times "15 * * * *") "joey" "/srv/web/tmp.kitenet.net/" "wget https://pump2rss.com/feed/[email protected] -O pump.atom.new --no-check-certificate 2>/dev/null; sed 's/ & / /g' pump.atom.new > pump.atom" ircBouncer :: Property HasInfo ircBouncer = propertyList "IRC bouncer" $ props & Apt.installed ["znc"] & User.accountFor "znc" & File.dirExists (takeDirectory conf) & File.hasPrivContent conf anyContext & File.ownerGroup conf "znc" "znc" & Cron.job "znconboot" (Cron.Times "@reboot") "znc" "~" "znc" -- ensure running if it was not already & trivial (userScriptProperty "znc" ["znc || true"]) `describe` "znc running" where conf = "/home/znc/.znc/configs/znc.conf" kiteShellBox :: Property NoInfo kiteShellBox = propertyList "kitenet.net shellinabox" [ Apt.installed ["shellinabox"] , File.hasContent "/etc/default/shellinabox" [ "# Deployed by propellor" , "SHELLINABOX_DAEMON_START=1" , "SHELLINABOX_PORT=443" , "SHELLINABOX_ARGS=\"--no-beep --service=/:SSH:kitenet.net\"" ] `onChange` Service.restarted "shellinabox" , Service.running "shellinabox" ] githubBackup :: Property HasInfo githubBackup = propertyList "github-backup box" $ props & Apt.installed ["github-backup", "moreutils"] & githubKeys & Cron.niceJob "github-backup run" (Cron.Times "30 4 * * *") "joey" "/home/joey/lib/backup" backupcmd & Cron.niceJob "gitriddance" (Cron.Times "30 4 * * *") "joey" "/home/joey/lib/backup" gitriddancecmd where backupcmd = intercalate "&&" $ [ "mkdir -p github" , "cd github" , ". $HOME/.github-keys" , "github-backup joeyh" ] gitriddancecmd = intercalate "&&" $ [ "cd github" , ". $HOME/.github-keys" ] ++ map gitriddance githubMirrors gitriddance (r, msg) = "(cd " ++ r ++ " && gitriddance " ++ shellEscape msg ++ ")" githubKeys :: Property HasInfo githubKeys = let f = "/home/joey/.github-keys" in File.hasPrivContent f anyContext `onChange` File.ownerGroup f "joey" "joey" -- these repos are only mirrored on github, I don't want -- all the proprietary features githubMirrors :: [(String, String)] githubMirrors = [ ("ikiwiki", plzuseurl "http://ikiwiki.info/todo/") , ("git-annex", plzuseurl "http://git-annex.branchable.com/todo/") , ("myrepos", plzuseurl "http://myrepos.branchable.com/todo/") , ("propellor", plzuseurl "http://propellor.branchable.com/todo/") , ("etckeeper", plzuseurl "http://etckeeper.branchable.com/todo/") ] where plzuseurl u = "please submit changes to " ++ u ++ " instead of using github pull requests" rsyncNetBackup :: [Host] -> Property NoInfo rsyncNetBackup hosts = Cron.niceJob "rsync.net copied in daily" (Cron.Times "30 5 * * *") "joey" "/home/joey/lib/backup" "mkdir -p rsync.net && rsync --delete -az [email protected]: rsync.net" `requires` Ssh.knownHost hosts "usw-s002.rsync.net" "joey" backupsBackedupFrom :: [Host] -> HostName -> FilePath -> Property NoInfo backupsBackedupFrom hosts srchost destdir = Cron.niceJob desc (Cron.Times "@reboot") "joey" "/" cmd `requires` Ssh.knownHost hosts srchost "joey" where desc = "backups copied from " ++ srchost ++ " on boot" cmd = "rsync -az --bwlimit=300K --partial --delete " ++ srchost ++ ":lib/backup/ " ++ destdir </> srchost obnamRepos :: [String] -> Property NoInfo obnamRepos rs = propertyList ("obnam repos for " ++ unwords rs) (mkbase : map mkrepo rs) where mkbase = mkdir "/home/joey/lib/backup" `requires` mkdir "/home/joey/lib" mkrepo r = mkdir ("/home/joey/lib/backup/" ++ r ++ ".obnam") mkdir d = File.dirExists d `before` File.ownerGroup d "joey" "joey" podcatcher :: Property NoInfo podcatcher = Cron.niceJob "podcatcher run hourly" (Cron.Times "55 * * * *") "joey" "/home/joey/lib/sound/podcasts" "xargs git-annex importfeed -c annex.genmetadata=true < feeds; mr --quiet update" `requires` Apt.installed ["git-annex", "myrepos"] kiteMailServer :: Property HasInfo kiteMailServer = propertyList "kitenet.net mail server" $ props & Postfix.installed & Apt.installed ["postfix-pcre"] & Apt.serviceInstalledRunning "postgrey" & Apt.serviceInstalledRunning "spamassassin" & "/etc/default/spamassassin" `File.containsLines` [ "# Propellor deployed" , "ENABLED=1" , "OPTIONS=\"--create-prefs --max-children 5 --helper-home-dir\"" , "CRON=1" , "NICE=\"--nicelevel 15\"" ] `onChange` Service.restarted "spamassassin" `describe` "spamd enabled" `requires` Apt.serviceInstalledRunning "cron" & Apt.serviceInstalledRunning "spamass-milter" -- Add -m to prevent modifying messages Subject or body. & "/etc/default/spamass-milter" `File.containsLine` "OPTIONS=\"-m -u spamass-milter -i 127.0.0.1\"" `onChange` Service.restarted "spamass-milter" `describe` "spamass-milter configured" & Apt.serviceInstalledRunning "amavisd-milter" & "/etc/default/amavisd-milter" `File.containsLines` [ "# Propellor deployed" , "MILTERSOCKET=/var/spool/postfix/amavis/amavis.sock" , "MILTERSOCKETOWNER=\"postfix:postfix\"" , "MILTERSOCKETMODE=\"0660\"" ] `onChange` Service.restarted "amavisd-milter" `describe` "amavisd-milter configured for postfix" & Apt.serviceInstalledRunning "clamav-freshclam" & dkimInstalled & Postfix.saslAuthdInstalled & Apt.installed ["maildrop"] & "/etc/maildroprc" `File.hasContent` [ "# Global maildrop filter file (deployed with propellor)" , "DEFAULT=\"$HOME/Maildir\"" , "MAILBOX=\"$DEFAULT/.\"" , "# Filter spam to a spam folder, unless .keepspam exists" , "if (/^X-Spam-Status: Yes/)" , "{" , " `test -e \"$HOME/.keepspam\"`" , " if ( $RETURNCODE != 0 )" , " to ${MAILBOX}spam" , "}" ] `describe` "maildrop configured" & "/etc/aliases" `File.hasPrivContentExposed` ctx `onChange` Postfix.newaliases & hasJoeyCAChain & hasPostfixCert ctx & "/etc/postfix/mydomain" `File.containsLines` [ "/.*\\.kitenet\\.net/\tOK" , "/ikiwiki\\.info/\tOK" , "/joeyh\\.name/\tOK" ] `onChange` Postfix.reloaded `describe` "postfix mydomain file configured" & "/etc/postfix/obscure_client_relay.pcre" `File.hasContent` -- Remove received lines for mails relayed from trusted -- clients. These can be a privacy violation, or trigger -- spam filters. [ "/^Received: from ([^.]+)\\.kitenet\\.net.*using TLS.*by kitenet\\.net \\(([^)]+)\\) with (E?SMTPS?A?) id ([A-F[:digit:]]+)(.*)/ IGNORE" -- Munge local Received line for postfix running on a -- trusted client that relays through. These can trigger -- spam filters. , "/^Received: by ([^.]+)\\.kitenet\\.net.*/ REPLACE X-Question: 42" ] `onChange` Postfix.reloaded `describe` "postfix obscure_client_relay file configured" & Postfix.mappedFile "/etc/postfix/virtual" (flip File.containsLines [ "# *@joeyh.name to joey" , "@joeyh.name\tjoey" ] ) `describe` "postfix virtual file configured" `onChange` Postfix.reloaded & Postfix.mappedFile "/etc/postfix/relay_clientcerts" (flip File.hasPrivContentExposed ctx) & Postfix.mainCfFile `File.containsLines` [ "myhostname = kitenet.net" , "mydomain = $myhostname" , "append_dot_mydomain = no" , "myorigin = kitenet.net" , "mydestination = $myhostname, localhost.$mydomain, $mydomain, kite.$mydomain., localhost, regexp:$config_directory/mydomain" , "mailbox_command = maildrop" , "virtual_alias_maps = hash:/etc/postfix/virtual" , "# Allow clients with trusted certs to relay mail through." , "relay_clientcerts = hash:/etc/postfix/relay_clientcerts" , "smtpd_relay_restrictions = permit_mynetworks,permit_tls_clientcerts,permit_sasl_authenticated,reject_unauth_destination" , "# Filter out client relay lines from headers." , "header_checks = pcre:$config_directory/obscure_client_relay.pcre" , "# Password auth for relaying (used by errol)" , "smtpd_sasl_auth_enable = yes" , "smtpd_sasl_security_options = noanonymous" , "smtpd_sasl_local_domain = kitenet.net" , "# Enable postgrey." , "smtpd_recipient_restrictions = permit_tls_clientcerts,permit_sasl_authenticated,,permit_mynetworks,reject_unauth_destination,check_policy_service inet:127.0.0.1:10023" , "# Enable spamass-milter, amavis-milter, opendkim" , "smtpd_milters = unix:/spamass/spamass.sock unix:amavis/amavis.sock inet:localhost:8891" , "# opendkim is used for outgoing mail" , "non_smtpd_milters = inet:localhost:8891" , "milter_connect_macros = j {daemon_name} v {if_name} _" , "# If a milter is broken, fall back to just accepting mail." , "milter_default_action = accept" , "# TLS setup -- server" , "smtpd_tls_CAfile = /etc/ssl/certs/joeyca.pem" , "smtpd_tls_cert_file = /etc/ssl/certs/postfix.pem" , "smtpd_tls_key_file = /etc/ssl/private/postfix.pem" , "smtpd_tls_loglevel = 1" , "smtpd_tls_received_header = yes" , "smtpd_use_tls = yes" , "smtpd_tls_ask_ccert = yes" , "smtpd_tls_session_cache_database = sdbm:/etc/postfix/smtpd_scache" , "# TLS setup -- client" , "smtp_tls_CAfile = /etc/ssl/certs/joeyca.pem" , "smtp_tls_cert_file = /etc/ssl/certs/postfix.pem" , "smtp_tls_key_file = /etc/ssl/private/postfix.pem" , "smtp_tls_loglevel = 1" , "smtp_use_tls = yes" , "smtp_tls_session_cache_database = sdbm:/etc/postfix/smtp_scache" ] `onChange` Postfix.dedupMainCf `onChange` Postfix.reloaded `describe` "postfix configured" & Apt.serviceInstalledRunning "dovecot-imapd" & Apt.serviceInstalledRunning "dovecot-pop3d" & "/etc/dovecot/conf.d/10-mail.conf" `File.containsLine` "mail_location = maildir:~/Maildir" `onChange` Service.reloaded "dovecot" `describe` "dovecot mail.conf" & "/etc/dovecot/conf.d/10-auth.conf" `File.containsLine` "!include auth-passwdfile.conf.ext" `onChange` Service.restarted "dovecot" `describe` "dovecot auth.conf" & File.hasPrivContent dovecotusers ctx `onChange` (dovecotusers `File.mode` combineModes [ownerReadMode, groupReadMode]) & File.ownerGroup dovecotusers "root" "dovecot" & Apt.installed ["mutt", "bsd-mailx", "alpine"] & pinescript `File.hasContent` [ "#!/bin/sh" , "# deployed with propellor" , "set -e" , "pass=$HOME/.pine-password" , "if [ ! -e $pass ]; then" , "\ttouch $pass" , "fi" , "chmod 600 $pass" , "exec alpine -passfile $pass \"$@\"" ] `onChange` (pinescript `File.mode` combineModes (readModes ++ executeModes)) `describe` "pine wrapper script" & "/etc/pine.conf" `File.hasContent` [ "# deployed with propellor" , "inbox-path={localhost/novalidate-cert/NoRsh}inbox" ] `describe` "pine configured to use local imap server" & Apt.serviceInstalledRunning "mailman" where ctx = Context "kitenet.net" pinescript = "/usr/local/bin/pine" dovecotusers = "/etc/dovecot/users" -- Configures postfix to relay outgoing mail to kitenet.net, with -- verification via tls cert. postfixClientRelay :: Context -> Property HasInfo postfixClientRelay ctx = Postfix.mainCfFile `File.containsLines` [ "relayhost = kitenet.net" , "smtp_tls_CAfile = /etc/ssl/certs/joeyca.pem" , "smtp_tls_cert_file = /etc/ssl/certs/postfix.pem" , "smtp_tls_key_file = /etc/ssl/private/postfix.pem" , "smtp_tls_loglevel = 0" , "smtp_use_tls = yes" ] `describe` "postfix client relay" `onChange` Postfix.dedupMainCf `onChange` Postfix.reloaded `requires` hasJoeyCAChain `requires` hasPostfixCert ctx -- Configures postfix to have the dkim milter, and no other milters. dkimMilter :: Property HasInfo dkimMilter = Postfix.mainCfFile `File.containsLines` [ "smtpd_milters = inet:localhost:8891" , "non_smtpd_milters = inet:localhost:8891" , "milter_default_action = accept" ] `describe` "postfix dkim milter" `onChange` Postfix.dedupMainCf `onChange` Postfix.reloaded `requires` dkimInstalled -- This does not configure postfix to use the dkim milter, -- nor does it set up domainkey DNS. dkimInstalled :: Property HasInfo dkimInstalled = go `onChange` Service.restarted "opendkim" where go = propertyList "opendkim installed" $ props & Apt.serviceInstalledRunning "opendkim" & File.dirExists "/etc/mail" & File.hasPrivContent "/etc/mail/dkim.key" (Context "kitenet.net") & File.ownerGroup "/etc/mail/dkim.key" "opendkim" "opendkim" & "/etc/default/opendkim" `File.containsLine` "SOCKET=\"inet:8891@localhost\"" & "/etc/opendkim.conf" `File.containsLines` [ "KeyFile /etc/mail/dkim.key" , "SubDomains yes" , "Domain *" , "Selector mail" ] -- This is the dkim public key, corresponding with /etc/mail/dkim.key -- This value can be included in a domain's additional records to make -- it use this domainkey. domainKey :: (BindDomain, Record) domainKey = (RelDomain "mail._domainkey", TXT "v=DKIM1; k=rsa; t=y; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCc+/rfzNdt5DseBBmfB3C6sVM7FgVvf4h1FeCfyfwPpVcmPdW6M2I+NtJsbRkNbEICxiP6QY2UM0uoo9TmPqLgiCCG2vtuiG6XMsS0Y/gGwqKM7ntg/7vT1Go9vcquOFFuLa5PnzpVf8hB9+PMFdS4NPTvWL2c5xxshl/RJzICnQIDAQAB") hasJoeyCAChain :: Property HasInfo hasJoeyCAChain = "/etc/ssl/certs/joeyca.pem" `File.hasPrivContentExposed` Context "joeyca.pem" hasPostfixCert :: Context -> Property HasInfo hasPostfixCert ctx = combineProperties "postfix tls cert installed" [ "/etc/ssl/certs/postfix.pem" `File.hasPrivContentExposed` ctx , "/etc/ssl/private/postfix.pem" `File.hasPrivContent` ctx ] kitenetHttps :: Property HasInfo kitenetHttps = propertyList "kitenet.net https certs" $ props & File.hasPrivContent "/etc/ssl/certs/web.pem" ctx & File.hasPrivContent "/etc/ssl/private/web.pem" ctx & File.hasPrivContent "/etc/ssl/certs/startssl.pem" ctx & Apache.modEnabled "ssl" where ctx = Context "kitenet.net" -- Legacy static web sites and redirections from kitenet.net to newer -- sites. legacyWebSites :: Property HasInfo legacyWebSites = propertyList "legacy web sites" $ props & Apt.serviceInstalledRunning "apache2" & Apache.modEnabled "rewrite" & Apache.modEnabled "cgi" & Apache.modEnabled "speling" & userDirHtml & kitenetHttps & apacheSite "kitenet.net" True -- /var/www is empty [ "DocumentRoot /var/www" , "<Directory /var/www>" , " Options Indexes FollowSymLinks MultiViews ExecCGI Includes" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/" -- for mailman cgi scripts , "<Directory /usr/lib/cgi-bin>" , " AllowOverride None" , " Options ExecCGI" , Apache.allowAll , "</Directory>" , "Alias /pipermail/ /var/lib/mailman/archives/public/" , "<Directory /var/lib/mailman/archives/public/>" , " Options Indexes MultiViews FollowSymlinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "Alias /images/ /usr/share/images/" , "<Directory /usr/share/images/>" , " Options Indexes MultiViews" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "RewriteEngine On" , "# Force hostname to kitenet.net" , "RewriteCond %{HTTP_HOST} !^kitenet\\.net [NC]" , "RewriteCond %{HTTP_HOST} !^$" , "RewriteRule ^/(.*) http://kitenet\\.net/$1 [L,R]" , "# Moved pages" , "RewriteRule /programs/debhelper http://joeyh.name/code/debhelper/ [L]" , "RewriteRule /programs/satutils http://joeyh.name/code/satutils/ [L]" , "RewriteRule /programs/filters http://joeyh.name/code/filters/ [L]" , "RewriteRule /programs/ticker http://joeyh.name/code/ticker/ [L]" , "RewriteRule /programs/pdmenu http://joeyh.name/code/pdmenu/ [L]" , "RewriteRule /programs/sleepd http://joeyh.name/code/sleepd/ [L]" , "RewriteRule /programs/Lingua::EN::Words2Nums http://joeyh.name/code/Words2Nums/ [L]" , "RewriteRule /programs/wmbattery http://joeyh.name/code/wmbattery/ [L]" , "RewriteRule /programs/dpkg-repack http://joeyh.name/code/dpkg-repack/ [L]" , "RewriteRule /programs/debconf http://joeyh.name/code/debconf/ [L]" , "RewriteRule /programs/perlmoo http://joeyh.name/code/perlmoo/ [L]" , "RewriteRule /programs/alien http://joeyh.name/code/alien/ [L]" , "RewriteRule /~joey/blog/entry/(.+)-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9]-[0-9][0-9].html http://joeyh.name/blog/entry/$1/ [L]" , "RewriteRule /~anna/.* http://waldeneffect\\.org/ [R]" , "RewriteRule /~anna/.* http://waldeneffect\\.org/ [R]" , "RewriteRule /~anna http://waldeneffect\\.org/ [R]" , "RewriteRule /simpleid/ http://openid.kitenet.net:8081/simpleid/" , "# Even the kite home page is not here any more!" , "RewriteRule ^/$ http://www.kitenet.net/ [R]" , "RewriteRule ^/index.html http://www.kitenet.net/ [R]" , "RewriteRule ^/joey http://www.kitenet.net/joey/ [R]" , "RewriteRule ^/joey/index.html http://www.kitenet.net/joey/ [R]" , "RewriteRule ^/wifi http://www.kitenet.net/wifi/ [R]" , "RewriteRule ^/wifi/index.html http://www.kitenet.net/wifi/ [R]" , "# Old ikiwiki filenames for kitenet.net wiki." , "rewritecond $1 !^/~" , "rewritecond $1 !^/doc/" , "rewritecond $1 !^/pipermail/" , "rewritecond $1 !^/cgi-bin/" , "rewritecond $1 !.*/index$" , "rewriterule (.+).html$ $1/ [r]" , "# Old ikiwiki filenames for joey's wiki." , "rewritecond $1 ^/~joey/" , "rewritecond $1 !.*/index$" , "rewriterule (.+).html$ http://kitenet.net/$1/ [L,R]" , "# ~joey to joeyh.name" , "rewriterule /~joey/(.*) http://joeyh.name/$1 [L]" , "# Old familywiki location." , "rewriterule /~family/(.*).html http://family.kitenet.net/$1 [L]" , "rewriterule /~family/(.*).rss http://family.kitenet.net/$1/index.rss [L]" , "rewriterule /~family(.*) http://family.kitenet.net$1 [L]" , "rewriterule /~kyle/bywayofscience(.*) http://bywayofscience.branchable.com$1 [L]" , "rewriterule /~kyle/family/wiki/(.*).html http://macleawiki.branchable.com/$1 [L]" , "rewriterule /~kyle/family/wiki/(.*).rss http://macleawiki.branchable.com/$1/index.rss [L]" , "rewriterule /~kyle/family/wiki(.*) http://macleawiki.branchable.com$1 [L]" ] & alias "anna.kitenet.net" & apacheSite "anna.kitenet.net" False [ "DocumentRoot /home/anna/html" , "<Directory /home/anna/html/>" , " Options Indexes ExecCGI" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "sows-ear.kitenet.net" & alias "www.sows-ear.kitenet.net" & apacheSite "sows-ear.kitenet.net" False [ "ServerAlias www.sows-ear.kitenet.net" , "DocumentRoot /srv/web/sows-ear.kitenet.net" , "<Directory /srv/web/sows-ear.kitenet.net>" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "wortroot.kitenet.net" & alias "www.wortroot.kitenet.net" & apacheSite "wortroot.kitenet.net" False [ "ServerAlias www.wortroot.kitenet.net" , "DocumentRoot /srv/web/wortroot.kitenet.net" , "<Directory /srv/web/wortroot.kitenet.net>" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "creeksidepress.com" & apacheSite "creeksidepress.com" False [ "ServerAlias www.creeksidepress.com" , "DocumentRoot /srv/web/www.creeksidepress.com" , "<Directory /srv/web/www.creeksidepress.com>" , " Options FollowSymLinks" , " AllowOverride None" , Apache.allowAll , "</Directory>" ] & alias "joey.kitenet.net" & apacheSite "joey.kitenet.net" False [ "DocumentRoot /var/www" , "<Directory /var/www/>" , " Options Indexes ExecCGI" , " AllowOverride None" , Apache.allowAll , "</Directory>" , "RewriteEngine On" , "# Old ikiwiki filenames for joey's wiki." , "rewritecond $1 !.*/index$" , "rewriterule (.+).html$ http://joeyh.name/$1/ [l]" , "rewritecond $1 !.*/index$" , "rewriterule (.+).rss$ http://joeyh.name/$1/index.rss [l]" , "# Redirect all to joeyh.name." , "rewriterule (.*) http://joeyh.name$1 [r]" ] userDirHtml :: Property HasInfo userDirHtml = File.fileProperty "apache userdir is html" (map munge) conf `onChange` Apache.reloaded `requires` (toProp $ Apache.modEnabled "userdir") where munge = replace "public_html" "html" conf = "/etc/apache2/mods-available/userdir.conf"
abailly/infra-test
src/Propellor/Property/SiteSpecific/JoeySites.hs
bsd-2-clause
34,535
406
72
5,169
6,209
3,411
2,798
751
2
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QToolTip.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:15 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QToolTip ( qToolTipFont ,qToolTipHideText ,qToolTipPalette ,qToolTipSetFont ,qToolTipSetPalette ,QqToolTipShowText(..), QqqToolTipShowText(..) ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui qToolTipFont :: (()) -> IO (QFont ()) qToolTipFont () = withQFontResult $ qtc_QToolTip_font foreign import ccall "qtc_QToolTip_font" qtc_QToolTip_font :: IO (Ptr (TQFont ())) qToolTipHideText :: (()) -> IO () qToolTipHideText () = qtc_QToolTip_hideText foreign import ccall "qtc_QToolTip_hideText" qtc_QToolTip_hideText :: IO () qToolTipPalette :: (()) -> IO (QPalette ()) qToolTipPalette () = withQPaletteResult $ qtc_QToolTip_palette foreign import ccall "qtc_QToolTip_palette" qtc_QToolTip_palette :: IO (Ptr (TQPalette ())) qToolTipSetFont :: ((QFont t1)) -> IO () qToolTipSetFont (x1) = withObjectPtr x1 $ \cobj_x1 -> qtc_QToolTip_setFont cobj_x1 foreign import ccall "qtc_QToolTip_setFont" qtc_QToolTip_setFont :: Ptr (TQFont t1) -> IO () qToolTipSetPalette :: ((QPalette t1)) -> IO () qToolTipSetPalette (x1) = withObjectPtr x1 $ \cobj_x1 -> qtc_QToolTip_setPalette cobj_x1 foreign import ccall "qtc_QToolTip_setPalette" qtc_QToolTip_setPalette :: Ptr (TQPalette t1) -> IO () class QqToolTipShowText x1 where qToolTipShowText :: x1 -> IO () class QqqToolTipShowText x1 where qqToolTipShowText :: x1 -> IO () instance QqToolTipShowText ((Point, String)) where qToolTipShowText (x1, x2) = withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> withCWString x2 $ \cstr_x2 -> qtc_QToolTip_showText_qth cpoint_x1_x cpoint_x1_y cstr_x2 foreign import ccall "qtc_QToolTip_showText_qth" qtc_QToolTip_showText_qth :: CInt -> CInt -> CWString -> IO () instance QqToolTipShowText ((Point, String, QWidget t3)) where qToolTipShowText (x1, x2, x3) = withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> withCWString x2 $ \cstr_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QToolTip_showText1_qth cpoint_x1_x cpoint_x1_y cstr_x2 cobj_x3 foreign import ccall "qtc_QToolTip_showText1_qth" qtc_QToolTip_showText1_qth :: CInt -> CInt -> CWString -> Ptr (TQWidget t3) -> IO () instance QqToolTipShowText ((Point, String, QWidget t3, Rect)) where qToolTipShowText (x1, x2, x3, x4) = withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> withCWString x2 $ \cstr_x2 -> withObjectPtr x3 $ \cobj_x3 -> withCRect x4 $ \crect_x4_x crect_x4_y crect_x4_w crect_x4_h -> qtc_QToolTip_showText2_qth cpoint_x1_x cpoint_x1_y cstr_x2 cobj_x3 crect_x4_x crect_x4_y crect_x4_w crect_x4_h foreign import ccall "qtc_QToolTip_showText2_qth" qtc_QToolTip_showText2_qth :: CInt -> CInt -> CWString -> Ptr (TQWidget t3) -> CInt -> CInt -> CInt -> CInt -> IO () instance QqqToolTipShowText ((QPoint t1, String)) where qqToolTipShowText (x1, x2) = withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> qtc_QToolTip_showText cobj_x1 cstr_x2 foreign import ccall "qtc_QToolTip_showText" qtc_QToolTip_showText :: Ptr (TQPoint t1) -> CWString -> IO () instance QqqToolTipShowText ((QPoint t1, String, QWidget t3)) where qqToolTipShowText (x1, x2, x3) = withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QToolTip_showText1 cobj_x1 cstr_x2 cobj_x3 foreign import ccall "qtc_QToolTip_showText1" qtc_QToolTip_showText1 :: Ptr (TQPoint t1) -> CWString -> Ptr (TQWidget t3) -> IO () instance QqqToolTipShowText ((QPoint t1, String, QWidget t3, QRect t4)) where qqToolTipShowText (x1, x2, x3, x4) = withObjectPtr x1 $ \cobj_x1 -> withCWString x2 $ \cstr_x2 -> withObjectPtr x3 $ \cobj_x3 -> withObjectPtr x4 $ \cobj_x4 -> qtc_QToolTip_showText2 cobj_x1 cstr_x2 cobj_x3 cobj_x4 foreign import ccall "qtc_QToolTip_showText2" qtc_QToolTip_showText2 :: Ptr (TQPoint t1) -> CWString -> Ptr (TQWidget t3) -> Ptr (TQRect t4) -> IO ()
keera-studios/hsQt
Qtc/Gui/QToolTip.hs
bsd-2-clause
4,487
0
15
726
1,286
678
608
88
1
-- -- Copyright 2014, General Dynamics C4 Systems -- -- This software may be distributed and modified according to the terms of -- the GNU General Public License version 2. Note that NO WARRANTY is provided. -- See "LICENSE_GPLv2.txt" for details. -- -- @TAG(GD_GPL) -- {-# LANGUAGE EmptyDataDecls, ForeignFunctionInterface, GeneralizedNewtypeDeriving #-} module SEL4.Machine.Hardware.ARM.QEmu where import SEL4.Machine.RegisterSet import Foreign.Ptr import Data.Bits import Data.Word(Word8) import Data.Ix import Data.Maybe import Control.Monad data CallbackData newtype IRQ = IRQ Word8 deriving (Enum, Ord, Ix, Eq, Show) instance Bounded IRQ where minBound = IRQ 0 maxBound = IRQ 31 newtype PAddr = PAddr { fromPAddr :: Word } deriving (Integral, Real, Show, Eq, Num, Bits, Ord, Enum, Bounded) physMappingOffset = 0xf0000000 ptrFromPAddr :: PAddr -> PPtr a ptrFromPAddr (PAddr addr) = PPtr $ addr + physMappingOffset addrFromPPtr :: PPtr a -> PAddr addrFromPPtr (PPtr ptr) = PAddr $ ptr - physMappingOffset pageColourBits :: Int pageColourBits = 0 -- qemu has no cache getMemoryRegions :: Ptr CallbackData -> IO [(PAddr, PAddr)] getMemoryRegions _ = return [(0, 1 `shiftL` 24)] getDeviceRegions :: Ptr CallbackData -> IO [(PAddr, PAddr)] getDeviceRegions _ = return devices where devices = [ (0x101e3000, 0x101e4000), -- second SP804; kernel uses first (0x10010000, 0x10011000) -- SMC91C111 ethernet ] timerPPtr = PPtr 0xff001000 timerAddr = PAddr 0x101e2000 timerIRQ = IRQ 4 pl190PPtr = PPtr 0xff002000 pl190Addr = PAddr 0x10140000 getKernelDevices :: Ptr CallbackData -> IO [(PAddr, PPtr Word)] getKernelDevices _ = return devices where devices = [ (timerAddr, timerPPtr), -- kernel timer (pl190Addr, pl190PPtr) -- interrupt controller ] maskInterrupt :: Ptr CallbackData -> Bool -> IRQ -> IO () maskInterrupt env mask (IRQ irq) = do let value = bit $ fromIntegral irq let pl190Reg = if mask then 0x14 else 0x10 storeWordCallback env (pl190Addr + pl190Reg) value when (irq >= 21 && irq <= 30) $ do -- these IRQs go via a a separate secondary interrupt controller, -- which can either multiplex them to IRQ 31 or pass them through -- to the PL190. We choose the latter. let vpbSICBase = PAddr 0x10003000 let vpbSICReg = PAddr $ if mask then 0x24 else 0x20 storeWordCallback env (vpbSICBase + vpbSICReg) value -- We don't need to acknowledge interrupts explicitly because we don't use -- the vectored interrupt controller. ackInterrupt :: Ptr CallbackData -> IRQ -> IO () ackInterrupt _ _ = return () foreign import ccall unsafe "qemu_run_devices" runDevicesCallback :: IO () interruptCallback :: Ptr CallbackData -> IO (Maybe IRQ) interruptCallback env = do -- No need to call back to the simulator here; we just check the PIC's -- active interrupt register. This will probably work for real ARMs too, -- as long as we're not using vectored interrupts active <- loadWordCallback env pl190Addr -- the following line is equivalent to the ARMv5 CLZ instruction. This -- means the kernel will handle higher IRQ numbers earlier, but this has -- little significance --- *any* IRQ will cause an immediate kernel entry. -- It does have a small effect on accounting of CPU time usage by the -- kernel during the IRQ handler, depending on the timer's IRQ number. return $ listToMaybe $ [ IRQ $ fromIntegral x | x <- reverse [0..31], testBit active x ] getActiveIRQ :: Ptr CallbackData -> IO (Maybe IRQ) getActiveIRQ env = do runDevicesCallback interruptCallback env -- 1kHz tick; qemu's SP804s always run at 1MHz timerFreq :: Word timerFreq = 100 timerLimit :: Word timerLimit = 1000000 `div` timerFreq configureTimer :: Ptr CallbackData -> IO IRQ configureTimer env = do -- enabled, periodic, interrupts enabled let timerCtrl = bit 7 .|. bit 6 .|. bit 5 storeWordCallback env (timerAddr+0x8) timerCtrl storeWordCallback env timerAddr timerLimit return timerIRQ resetTimer :: Ptr CallbackData -> IO () resetTimer env = storeWordCallback env (timerAddr+0xc) 0 foreign import ccall unsafe "qemu_load_word_phys" loadWordCallback :: Ptr CallbackData -> PAddr -> IO Word foreign import ccall unsafe "qemu_store_word_phys" storeWordCallback :: Ptr CallbackData -> PAddr -> Word -> IO () foreign import ccall unsafe "qemu_tlb_flush" invalidateTLBCallback :: Ptr CallbackData -> IO () foreign import ccall unsafe "qemu_tlb_flush_asid" invalidateTLB_ASIDCallback :: Ptr CallbackData -> Word8 -> IO () foreign import ccall unsafe "qemu_tlb_flush_vptr" invalidateTLB_VAASIDCallback :: Ptr CallbackData -> Word -> IO () isbCallback :: Ptr CallbackData -> IO () isbCallback _ = return () dsbCallback :: Ptr CallbackData -> IO () dsbCallback _ = return () dmbCallback :: Ptr CallbackData -> IO () dmbCallback _ = return () cacheCleanByVACallback :: Ptr CallbackData -> VPtr -> PAddr -> IO () cacheCleanByVACallback _cptr _mva _pa = return () cacheCleanByVA_PoUCallback :: Ptr CallbackData -> VPtr -> PAddr -> IO () cacheCleanByVA_PoUCallback _cptr _mva _pa = return () cacheInvalidateByVACallback :: Ptr CallbackData -> VPtr -> PAddr -> IO () cacheInvalidateByVACallback _cptr _mva _pa = return () cacheInvalidateByVA_ICallback :: Ptr CallbackData -> VPtr -> PAddr -> IO () cacheInvalidateByVA_ICallback _cptr _mva _pa = return () cacheInvalidate_I_PoUCallback :: Ptr CallbackData -> IO () cacheInvalidate_I_PoUCallback _ = return () cacheCleanInvalidateByVACallback :: Ptr CallbackData -> VPtr -> PAddr -> IO () cacheCleanInvalidateByVACallback _cptr _mva _pa = return () branchFlushCallback :: Ptr CallbackData -> VPtr -> PAddr -> IO () branchFlushCallback _cptr _mva _pa = return () cacheClean_D_PoUCallback :: Ptr CallbackData -> IO () cacheClean_D_PoUCallback _ = return () cacheCleanInvalidate_D_PoCCallback :: Ptr CallbackData -> IO () cacheCleanInvalidate_D_PoCCallback _ = return () cacheCleanInvalidate_D_PoUCallback :: Ptr CallbackData -> IO () cacheCleanInvalidate_D_PoUCallback _ = return () cacheCleanInvalidateL2RangeCallback :: Ptr CallbackData -> PAddr -> PAddr -> IO () cacheCleanInvalidateL2RangeCallback _ _ _ = return () cacheInvalidateL2RangeCallback :: Ptr CallbackData -> PAddr -> PAddr -> IO () cacheInvalidateL2RangeCallback _ _ _ = return () cacheCleanL2RangeCallback :: Ptr CallbackData -> PAddr -> PAddr -> IO () cacheCleanL2RangeCallback _ _ _ = return () -- For the ARM1136 cacheLine :: Int cacheLine = 32 cacheLineBits :: Int cacheLineBits = 5 foreign import ccall unsafe "qemu_set_asid" setHardwareASID :: Ptr CallbackData -> Word8 -> IO () foreign import ccall unsafe "qemu_set_root" setCurrentPD :: Ptr CallbackData -> PAddr -> IO () foreign import ccall unsafe "qemu_arm_get_ifsr" getIFSR :: Ptr CallbackData -> IO Word foreign import ccall unsafe "qemu_arm_get_dfsr" getDFSR :: Ptr CallbackData -> IO Word foreign import ccall unsafe "qemu_arm_get_far" getFAR :: Ptr CallbackData -> IO VPtr
NICTA/seL4
haskell/src/SEL4/Machine/Hardware/ARM/QEmu.hs
bsd-2-clause
7,150
0
14
1,360
1,870
950
920
-1
-1
{-# LANGUAGE PackageImports #-} import "DtekPortalen" Application (getApplicationDev) import Network.Wai.Handler.Warp (runSettings, defaultSettings, settingsPort) import Control.Concurrent (forkIO) import System.Directory (doesFileExist, removeFile) import System.Exit (exitSuccess) import Control.Concurrent (threadDelay) main :: IO () main = do putStrLn "Starting devel application" (port, app) <- getApplicationDev forkIO $ runSettings defaultSettings { settingsPort = port } app loop loop :: IO () loop = do threadDelay 100000 e <- doesFileExist "yesod-devel/devel-terminate" if e then terminateDevel else loop terminateDevel :: IO () terminateDevel = exitSuccess
dtekcth/DtekPortalen
src/devel.hs
bsd-2-clause
713
0
10
123
186
101
85
23
2
{-# LANGUAGE Haskell2010 #-} module Unicode2 where -- | All of the following work with a unicode character ü: -- -- * an italicized /ü/ -- -- * inline code @ü@ -- -- * a code block: -- -- > ü -- -- * a url <https://www.google.com/search?q=ü> -- -- * a link to 'ü' -- ü :: () ü = ()
haskell/haddock
html-test/src/Unicode2.hs
bsd-2-clause
307
0
5
78
33
26
7
4
1
{-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE ImplicitParams #-} -- | This module defines the representation of Subtyping and WF Constraints, and -- the code for syntax-directed constraint generation. module Language.Haskell.Liquid.Constraint.Generate ( generateConstraints ) where import Prelude hiding (error, undefined) import GHC.Stack import CoreUtils (exprType) import MkCore import Coercion import DataCon import Pair import CoreSyn import SrcLoc import Type import TyCon import PrelNames import TypeRep import Class (className) import Var import Kind import Id import IdInfo import Name import NameSet import Unify import VarSet -- import Unique import Text.PrettyPrint.HughesPJ hiding (first) import Control.Monad.State -- import Control.Applicative ((<$>), (<*>), Applicative) -- import Data.Monoid (mconcat, mempty, mappend) import Data.Maybe (fromMaybe, catMaybes, fromJust, isJust) import qualified Data.HashMap.Strict as M import qualified Data.HashSet as S import qualified Data.List as L import Data.Bifunctor import qualified Data.Foldable as F import qualified Data.Traversable as T import qualified Language.Haskell.Liquid.UX.CTags as Tg import Language.Fixpoint.Types.Visitor import Language.Haskell.Liquid.Constraint.Fresh import Language.Haskell.Liquid.Constraint.Env import Language.Haskell.Liquid.Constraint.Monad import Language.Haskell.Liquid.Constraint.Split import qualified Language.Fixpoint.Types as F import Language.Haskell.Liquid.WiredIn (dictionaryVar) import Language.Haskell.Liquid.Types.Dictionaries import qualified Language.Haskell.Liquid.GHC.SpanStack as Sp import Language.Haskell.Liquid.Types hiding (binds, Loc, loc, freeTyVars, Def) import Language.Haskell.Liquid.Types.Strata import Language.Haskell.Liquid.Types.Names import Language.Haskell.Liquid.Types.RefType import Language.Haskell.Liquid.Types.Visitors hiding (freeVars) import Language.Haskell.Liquid.Types.PredType hiding (freeTyVars) import Language.Haskell.Liquid.Types.Meet import Language.Haskell.Liquid.GHC.Misc ( isInternal, collectArguments, tickSrcSpan , hasBaseTypeVar, showPpr, isDataConId) import Language.Haskell.Liquid.Misc import Language.Fixpoint.Misc import Language.Haskell.Liquid.Types.Literals import Language.Haskell.Liquid.Constraint.Axioms import Language.Haskell.Liquid.Constraint.Types import Language.Haskell.Liquid.Constraint.Constraint -- import Debug.Trace (trace) ----------------------------------------------------------------------- ------------- Constraint Generation: Toplevel ------------------------- ----------------------------------------------------------------------- generateConstraints :: GhcInfo -> CGInfo generateConstraints info = {-# SCC "ConsGen" #-} execState act $ initCGI cfg info where act = consAct info cfg = config $ spec info consAct :: GhcInfo -> CG () consAct info = do γ' <- initEnv info sflag <- scheck <$> get tflag <- trustghc <$> get γ <- if expandProofsMode then addCombine τProof γ' else return γ' cbs' <- if expandProofsMode then mapM (expandProofs info (mkSigs γ)) $ cbs info else return $ cbs info let trustBinding x = tflag && (x `elem` derVars info || isInternal x) foldM_ (consCBTop trustBinding) γ cbs' hcs <- hsCs <$> get hws <- hsWfs <$> get scss <- sCs <$> get annot <- annotMap <$> get scs <- if sflag then concat <$> mapM splitS (hcs ++ scss) else return [] let smap = if sflag then solveStrata scs else [] let hcs' = if sflag then subsS smap hcs else hcs fcs <- concat <$> mapM splitC (subsS smap hcs') fws <- concat <$> mapM splitW hws let annot' = if sflag then subsS smap <$> annot else annot modify $ \st -> st { fEnv = fixEnv γ, fixCs = fcs , fixWfs = fws , annotMap = annot'} where expandProofsMode = autoproofs $ config $ spec info τProof = proofType $ spec info fixEnv = feEnv . fenv mkSigs γ = toListREnv (renv γ) ++ toListREnv (assms γ) ++ toListREnv (grtys γ) addCombine τ γ = do t <- trueTy combineType γ ++= ("combineProofs", combineSymbol, t) where combineType = makeCombineType τ combineVar = makeCombineVar combineType combineSymbol = F.symbol combineVar ------------------------------------------------------------------------------------ initEnv :: GhcInfo -> CG CGEnv ------------------------------------------------------------------------------------ initEnv info = do let tce = tcEmbeds sp let fVars = impVars info let dcs = filter isConLikeId ((snd <$> freeSyms sp)) let dcs' = filter isConLikeId fVars defaults <- forM fVars $ \x -> liftM (x,) (trueTy $ varType x) dcsty <- forM dcs $ makeDataConTypes dcsty' <- forM dcs' $ makeDataConTypes (hs,f0) <- refreshHoles $ grty info -- asserted refinements (for defined vars) f0'' <- refreshArgs' =<< grtyTop info -- default TOP reftype (for exported vars without spec) let f0' = if notruetypes $ config sp then [] else f0'' f1 <- refreshArgs' defaults -- default TOP reftype (for all vars) f1' <- refreshArgs' $ makedcs dcsty f2 <- refreshArgs' $ assm info -- assumed refinements (for imported vars) f3 <- refreshArgs' $ vals asmSigs sp -- assumed refinedments (with `assume`) f40 <- refreshArgs' $ vals ctors sp -- constructor refinements (for measures) (invs1, f41) <- mapSndM refreshArgs' $ makeAutoDecrDataCons dcsty (autosize sp) dcs (invs2, f42) <- mapSndM refreshArgs' $ makeAutoDecrDataCons dcsty' (autosize sp) dcs' let f4 = mergeDataConTypes (mergeDataConTypes f40 (f41 ++ f42)) (filter (isDataConId . fst) f2) sflag <- scheck <$> get let senv = if sflag then f2 else [] let tx = mapFst F.symbol . addRInv ialias . strataUnify senv . predsUnify sp let bs = (tx <$> ) <$> [f0 ++ f0', f1 ++ f1', f2, f3, f4] lts <- lits <$> get let tcb = mapSnd (rTypeSort tce) <$> concat bs let γ0 = measEnv sp (head bs) (cbs info) (tcb ++ lts) (bs!!3) hs (invs1 ++ invs2) globalize <$> foldM (++=) γ0 [("initEnv", x, y) | (x, y) <- concat $ tail bs] where sp = spec info ialias = mkRTyConIAl $ ialiases sp vals f = map (mapSnd val) . f mapSndM f (x,y) = (x,) <$> f y makedcs = map strengthenDataConType makeDataConTypes x = (x,) <$> (trueTy $ varType x) makeAutoDecrDataCons dcts specenv dcs = (simplify invs, tys) where (invs, tys) = unzip $ concatMap go tycons tycons = L.nub $ catMaybes $ map idTyCon dcs go tycon | S.member tycon specenv = zipWith (makeSizedDataCons dcts) (tyConDataCons tycon) [0..] go _ = [] idTyCon x = dataConTyCon <$> case idDetails x of {DataConWorkId d -> Just d; DataConWrapId d -> Just d; _ -> Nothing} simplify invs = dummyLoc . (`strengthen` invariant) . fmap (\_ -> mempty) <$> L.nub invs invariant = MkUReft (F.Reft (F.vv_, F.PAtom F.Ge (lenOf F.vv_) (F.ECon $ F.I 0)) ) mempty mempty lenOf x = F.mkEApp lenLocSymbol [F.EVar x] makeSizedDataCons dcts x' n = (toRSort $ ty_res trep, (x, fromRTypeRep trep{ty_res = tres})) where x = dataConWorkId x' t = fromMaybe (impossible Nothing "makeSizedDataCons: this should never happen") $ L.lookup x dcts trep = toRTypeRep t tres = ty_res trep `strengthen` MkUReft (F.Reft (F.vv_, F.PAtom F.Eq (lenOf F.vv_) computelen)) mempty mempty recarguments = filter (\(t,_) -> (toRSort t == toRSort tres)) (zip (ty_args trep) (ty_binds trep)) computelen = foldr (F.EBin F.Plus) (F.ECon $ F.I n) (lenOf . snd <$> recarguments) mergeDataConTypes :: [(Var, SpecType)] -> [(Var, SpecType)] -> [(Var, SpecType)] mergeDataConTypes xts yts = merge (L.sortBy f xts) (L.sortBy f yts) where f (x,_) (y,_) = compare x y merge [] ys = ys merge xs [] = xs merge (xt@(x, tx):xs) (yt@(y, ty):ys) | x == y = (x, mXY x tx y ty) : merge xs ys | x < y = xt : merge xs (yt : ys) | otherwise = yt : merge (xt : xs) ys mXY x tx y ty = meetVarTypes (pprint x) (getSrcSpan x, tx) (getSrcSpan y, ty) refreshHoles vts = first catMaybes . unzip . map extract <$> mapM refreshHoles' vts refreshHoles' (x,t) | noHoles t = return (Nothing, x, t) | otherwise = (Just $ F.symbol x,x,) <$> mapReftM tx t where tx r | hasHole r = refresh r | otherwise = return r extract (a,b,c) = (a,(b,c)) refreshArgs' = mapM (mapSndM refreshArgs) strataUnify :: [(Var, SpecType)] -> (Var, SpecType) -> (Var, SpecType) strataUnify senv (x, t) = (x, maybe t (mappend t) pt) where pt = fmap (\(MkUReft _ _ l) -> MkUReft mempty mempty l) <$> L.lookup x senv -- | TODO: All this *should* happen inside @Bare@ but appears -- to happen after certain are signatures are @fresh@-ed, -- which is why they are here. -- NV : still some sigs do not get TyConInfo predsUnify :: GhcSpec -> (Var, RRType RReft) -> (Var, RRType RReft) predsUnify sp = second (addTyConInfo tce tyi) -- needed to eliminate some @RPropH@ where tce = tcEmbeds sp tyi = tyconEnv sp ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- measEnv sp xts cbs lts asms hs autosizes = CGE { cgLoc = Sp.empty , renv = fromListREnv (second val <$> meas sp) [] , syenv = F.fromListSEnv $ freeSyms sp , fenv = initFEnv $ lts ++ (second (rTypeSort tce . val) <$> meas sp) , denv = dicts sp , recs = S.empty , invs = mkRTyConInv $ (invariants sp ++ autosizes) , ial = mkRTyConIAl $ ialiases sp , grtys = fromListREnv xts [] , assms = fromListREnv asms [] , emb = tce , tgEnv = Tg.makeTagEnv cbs , tgKey = Nothing , trec = Nothing , lcb = M.empty , holes = fromListHEnv hs , lcs = mempty , aenv = axiom_map $ logicMap sp } where tce = tcEmbeds sp assm = assmGrty impVars grty = assmGrty defVars assmGrty f info = [ (x, val t) | (x, t) <- sigs, x `S.member` xs ] where xs = S.fromList $ f info sigs = tySigs $ spec info grtyTop info = forM topVs $ \v -> (v,) <$> trueTy (varType v) where topVs = filter isTop $ defVars info isTop v = isExportedId v && not (v `S.member` sigVs) isExportedId = flip elemNameSet (exports $ spec info) . getName sigVs = S.fromList [v | (v,_) <- tySigs (spec info) ++ asmSigs (spec info)] initCGI cfg info = CGInfo { fEnv = F.emptySEnv , hsCs = [] , sCs = [] , hsWfs = [] , fixCs = [] , isBind = [] , fixWfs = [] , freshIndex = 0 , binds = F.emptyBindEnv , annotMap = AI M.empty , tyConInfo = tyi , tyConEmbed = tce , kuts = mempty -- F.ksEmpty , lits = coreBindLits tce info ++ (map (mapSnd F.sr_sort) $ map mkSort $ meas spc) , termExprs = M.fromList $ texprs spc , specDecr = decr spc , specLVars = lvars spc , specLazy = dictionaryVar `S.insert` lazy spc , tcheck = not $ notermination cfg , scheck = strata cfg , trustghc = trustinternals cfg , pruneRefs = not $ noPrune cfg , logErrors = [] , kvProf = emptyKVProf , recCount = 0 , bindSpans = M.empty , autoSize = autosize spc , allowHO = higherorder cfg } where tce = tcEmbeds spc spc = spec info tyi = tyconEnv spc mkSort = mapSnd (rTypeSortedReft tce . val) coreBindLits :: F.TCEmb TyCon -> GhcInfo -> [(F.Symbol, F.Sort)] coreBindLits tce info = sortNub $ [ (F.symbol x, F.strSort) | (_, Just (F.ESym x)) <- lconsts ] -- strings ++ [ (dconToSym dc, dconToSort dc) | dc <- dcons ] -- data constructors where lconsts = literalConst tce <$> literals (cbs info) dcons = filter isDCon freeVs freeVs = impVars info ++ (snd <$> freeSyms (spec info)) dconToSort = typeSort tce . expandTypeSynonyms . varType dconToSym = F.symbol . idDataCon isDCon x = isDataConId x && not (hasBaseTypeVar x) ------------------------------------------------------------------- -- | Generation: Freshness --------------------------------------- ------------------------------------------------------------------- -- | Right now, we generate NO new pvars. Rather than clutter code -- with `uRType` calls, put it in one place where the above -- invariant is /obviously/ enforced. -- Constraint generation should ONLY use @freshTy_type@ and @freshTy_expr@ freshTy_type :: KVKind -> CoreExpr -> Type -> CG SpecType freshTy_type k _ τ = freshTy_reftype k $ ofType τ freshTy_expr :: KVKind -> CoreExpr -> Type -> CG SpecType freshTy_expr k e _ = freshTy_reftype k $ exprRefType e freshTy_reftype :: KVKind -> SpecType -> CG SpecType freshTy_reftype k t = (fixTy t >>= refresh) =>> addKVars k -- | Used to generate "cut" kvars for fixpoint. Typically, KVars for recursive -- definitions, and also to update the KVar profile. addKVars :: KVKind -> SpecType -> CG () addKVars !k !t = do when (True) $ modify $ \s -> s { kvProf = updKVProf k kvars (kvProf s) } when (isKut k) $ modify $ \s -> s { kuts = mappend kvars (kuts s) } where kvars = F.KS $ S.fromList $ specTypeKVars t isKut :: KVKind -> Bool isKut RecBindE = True isKut _ = False specTypeKVars :: SpecType -> [F.KVar] specTypeKVars = foldReft (\ _ r ks -> (kvars $ ur_reft r) ++ ks) [] trueTy :: Type -> CG SpecType trueTy = ofType' >=> true ofType' :: Type -> CG SpecType ofType' = fixTy . ofType fixTy :: SpecType -> CG SpecType fixTy t = do tyi <- tyConInfo <$> get tce <- tyConEmbed <$> get return $ addTyConInfo tce tyi t refreshArgsTop :: (Var, SpecType) -> CG SpecType refreshArgsTop (x, t) = do (t', su) <- refreshArgsSub t modify $ \s -> s {termExprs = M.adjust (F.subst su <$>) x $ termExprs s} return t' refreshArgs :: SpecType -> CG SpecType refreshArgs t = fst <$> refreshArgsSub t -- NV TODO: this does not refresh args if they are wrapped in an RRTy refreshArgsSub :: SpecType -> CG (SpecType, F.Subst) refreshArgsSub t = do ts <- mapM refreshArgs ts_u xs' <- mapM (\_ -> fresh) xs let sus = F.mkSubst <$> (L.inits $ zip xs (F.EVar <$> xs')) let su = last sus let ts' = zipWith F.subst sus ts let t' = fromRTypeRep $ trep {ty_binds = xs', ty_args = ts', ty_res = F.subst su tbd} return (t', su) where trep = toRTypeRep t xs = ty_binds trep ts_u = ty_args trep tbd = ty_res trep ------------------------------------------------------------------------------- -- | TERMINATION TYPE -------------------------------------- ------------------------------------------------------------------------------- makeDecrIndex :: (Var, Template SpecType)-> CG [Int] makeDecrIndex (x, Assumed t) = do dindex <- makeDecrIndexTy x t case dindex of Left _ -> return [] Right i -> return i makeDecrIndex (x, Asserted t) = do dindex <- makeDecrIndexTy x t case dindex of Left msg -> addWarning msg >> return [] Right i -> return i makeDecrIndex _ = return [] makeDecrIndexTy x t = do spDecr <- specDecr <$> get autosz <- autoSize <$> get hint <- checkHint' autosz (L.lookup x $ spDecr) case dindex autosz of Nothing -> return $ Left msg Just i -> return $ Right $ fromMaybe [i] hint where ts = ty_args trep checkHint' = \autosz -> checkHint x ts (isDecreasing autosz cenv) dindex = \autosz -> L.findIndex (isDecreasing autosz cenv) ts msg = ErrTermin (getSrcSpan x) [pprint x] (text "No decreasing parameter") cenv = makeNumEnv ts trep = toRTypeRep $ unOCons t recType _ ((_, []), (_, [], t)) = t recType autoenv ((vs, indexc), (_, index, t)) = makeRecType autoenv t v dxt index where v = (vs !!) <$> indexc dxt = (xts !!) <$> index xts = zip (ty_binds trep) (ty_args trep) trep = toRTypeRep $ unOCons t -- checkIndex :: (Var, _, _ , _) -> _ checkIndex (x, vs, t, index) = do mapM_ (safeLogIndex msg1 vs) index mapM (safeLogIndex msg2 ts) index where loc = getSrcSpan x ts = ty_args $ toRTypeRep $ unOCons $ unTemplate t msg1 = ErrTermin loc [xd] ("No decreasing" <+> pprint index <> "-th argument on" <+> xd <+> "with" <+> (pprint vs)) msg2 = ErrTermin loc [xd] "No decreasing parameter" xd = pprint x makeRecType autoenv t vs dxs is = mergecondition t $ fromRTypeRep $ trep {ty_binds = xs', ty_args = ts'} where (xs', ts') = unzip $ replaceN (last is) (makeDecrType autoenv vdxs) xts vdxs = zip vs dxs xts = zip (ty_binds trep) (ty_args trep) trep = toRTypeRep $ unOCons t unOCons (RAllT v t) = RAllT v $ unOCons t unOCons (RAllP p t) = RAllP p $ unOCons t unOCons (RFun x tx t r) = RFun x (unOCons tx) (unOCons t) r unOCons (RRTy _ _ OCons t) = unOCons t unOCons t = t mergecondition (RAllT _ t1) (RAllT v t2) = RAllT v $ mergecondition t1 t2 mergecondition (RAllP _ t1) (RAllP p t2) = RAllP p $ mergecondition t1 t2 mergecondition (RRTy xts r OCons t1) t2 = RRTy xts r OCons (mergecondition t1 t2) mergecondition (RFun _ t11 t12 _) (RFun x2 t21 t22 r2) = RFun x2 (mergecondition t11 t21) (mergecondition t12 t22) r2 mergecondition _ t = t safeLogIndex err ls n | n >= length ls = addWarning err >> return Nothing | otherwise = return $ Just $ ls !! n checkHint _ _ _ Nothing = return Nothing checkHint x _ _ (Just ns) | L.sort ns /= ns = addWarning (ErrTermin loc [dx] (text "The hints should be increasing")) >> return Nothing where loc = getSrcSpan x dx = pprint x checkHint x ts f (Just ns) = (mapM (checkValidHint x ts f) ns) >>= (return . Just . catMaybes) checkValidHint x ts f n | n < 0 || n >= length ts = addWarning err >> return Nothing | f (ts L.!! n) = return $ Just n | otherwise = addWarning err >> return Nothing where err = ErrTermin loc [xd] (vcat [ "Invalid Hint" <+> pprint (n+1) <+> "for" <+> xd , "in" , pprint ts ]) loc = getSrcSpan x xd = pprint x -------------------------------------------------------------------------------- consCBLet :: CGEnv -> CoreBind -> CG CGEnv -------------------------------------------------------------------------------- consCBLet γ cb = do oldtcheck <- tcheck <$> get strict <- specLazy <$> get let tflag = oldtcheck let isStr = tcond cb strict -- TODO: yuck. modify $ \s -> s { tcheck = tflag && isStr } γ' <- consCB (tflag && isStr) isStr γ cb modify $ \s -> s{tcheck = oldtcheck} return γ' -------------------------------------------------------------------------------- -- | Constraint Generation: Corebind ------------------------------------------- -------------------------------------------------------------------------------- consCBTop :: (Var -> Bool) -> CGEnv -> CoreBind -> CG CGEnv -------------------------------------------------------------------------------- consCBTop trustBinding γ cb | all trustBinding xs = do ts <- mapM trueTy (varType <$> xs) foldM (\γ xt -> (γ, "derived") += xt) γ (zip xs' ts) where xs = bindersOf cb xs' = F.symbol <$> xs consCBTop _ γ cb = do oldtcheck <- tcheck <$> get strict <- specLazy <$> get let tflag = oldtcheck let isStr = tcond cb strict modify $ \s -> s { tcheck = tflag && isStr} γ' <- consCB (tflag && isStr) isStr γ cb modify $ \s -> s { tcheck = oldtcheck} return γ' tcond cb strict = not $ any (\x -> S.member x strict || isInternal x) (binds cb) where binds (NonRec x _) = [x] binds (Rec xes) = fst $ unzip xes -------------------------------------------------------------------------------- consCB :: Bool -> Bool -> CGEnv -> CoreBind -> CG CGEnv -------------------------------------------------------------------------------- -- RJ: AAAAAAARGHHH!!!!!! THIS CODE IS HORRIBLE!!!!!!!!! consCBSizedTys γ xes = do xets'' <- forM xes $ \(x, e) -> liftM (x, e,) (varTemplate γ (x, Just e)) sflag <- scheck <$> get autoenv <- autoSize <$> get let cmakeFinType = if sflag then makeFinType else id let cmakeFinTy = if sflag then makeFinTy else snd let xets = mapThd3 (fmap cmakeFinType) <$> xets'' ts' <- mapM (T.mapM refreshArgs) $ (thd3 <$> xets) let vs = zipWith collectArgs ts' es is <- mapM makeDecrIndex (zip xs ts') >>= checkSameLens let ts = cmakeFinTy <$> zip is ts' let xeets = (\vis -> [(vis, x) | x <- zip3 xs is $ map unTemplate ts]) <$> (zip vs is) (L.transpose <$> mapM checkIndex (zip4 xs vs ts is)) >>= checkEqTypes let rts = (recType autoenv <$>) <$> xeets let xts = zip xs ts γ' <- foldM extender γ xts let γs = [γ' `setTRec` (zip xs rts') | rts' <- rts] let xets' = zip3 xs es ts mapM_ (uncurry $ consBind True) (zip γs xets') return γ' where (xs, es) = unzip xes dxs = pprint <$> xs collectArgs = collectArguments . length . ty_binds . toRTypeRep . unOCons . unTemplate checkEqTypes :: [[Maybe SpecType]] -> CG [[SpecType]] checkEqTypes x = mapM (checkAll err1 toRSort) (catMaybes <$> x) checkSameLens = checkAll err2 length err1 = ErrTermin loc dxs $ text "The decreasing parameters should be of same type" err2 = ErrTermin loc dxs $ text "All Recursive functions should have the same number of decreasing parameters" loc = getSrcSpan (head xs) checkAll _ _ [] = return [] checkAll err f (x:xs) | all (==(f x)) (f <$> xs) = return (x:xs) | otherwise = addWarning err >> return [] consCBWithExprs γ xes = do xets' <- forM xes $ \(x, e) -> liftM (x, e,) (varTemplate γ (x, Just e)) texprs <- termExprs <$> get let xtes = catMaybes $ (`lookup` texprs) <$> xs sflag <- scheck <$> get let cmakeFinType = if sflag then makeFinType else id let xets = mapThd3 (fmap cmakeFinType) <$> xets' let ts = safeFromAsserted err . thd3 <$> xets ts' <- mapM refreshArgs ts let xts = zip xs (Asserted <$> ts') γ' <- foldM extender γ xts let γs = makeTermEnvs γ' xtes xes ts ts' let xets' = zip3 xs es (Asserted <$> ts') mapM_ (uncurry $ consBind True) (zip γs xets') return γ' where (xs, es) = unzip xes lookup k m | Just x <- M.lookup k m = Just (k, x) | otherwise = Nothing err = "Constant: consCBWithExprs" makeFinTy (ns, t) = fmap go t where go t = fromRTypeRep $ trep {ty_args = args'} where trep = toRTypeRep t args' = mapNs ns makeFinType $ ty_args trep makeTermEnvs γ xtes xes ts ts' = setTRec γ . zip xs <$> rts where vs = zipWith collectArgs ts es ys = (fst4 . bkArrowDeep) <$> ts ys' = (fst4 . bkArrowDeep) <$> ts' sus' = zipWith mkSub ys ys' sus = zipWith mkSub ys ((F.symbol <$>) <$> vs) ess = (\x -> (safeFromJust (err x) $ (x `L.lookup` xtes))) <$> xs tes = zipWith (\su es -> F.subst su <$> es) sus ess tes' = zipWith (\su es -> F.subst su <$> es) sus' ess rss = zipWith makeLexRefa tes' <$> (repeat <$> tes) rts = zipWith (addObligation OTerm) ts' <$> rss (xs, es) = unzip xes mkSub ys ys' = F.mkSubst [(x, F.EVar y) | (x, y) <- zip ys ys'] collectArgs = collectArguments . length . ty_binds . toRTypeRep err x = "Constant: makeTermEnvs: no terminating expression for " ++ showPpr x addObligation :: Oblig -> SpecType -> RReft -> SpecType addObligation o t r = mkArrow αs πs ls xts $ RRTy [] r o t2 where (αs, πs, ls, t1) = bkUniv t (xs, ts, rs, t2) = bkArrow t1 xts = zip3 xs ts rs consCB tflag _ γ (Rec xes) | tflag = do texprs <- termExprs <$> get modify $ \i -> i { recCount = recCount i + length xes } let xxes = catMaybes $ (`lookup` texprs) <$> xs if null xxes then consCBSizedTys γ xes else check xxes <$> consCBWithExprs γ xes where xs = fst $ unzip xes check ys r | length ys == length xs = r | otherwise = panic (Just loc) $ msg msg = "Termination expressions must be provided for all mutually recursive binders" loc = getSrcSpan (head xs) lookup k m = (k,) <$> M.lookup k m consCB _ str γ (Rec xes) | not str = do xets' <- forM xes $ \(x, e) -> liftM (x, e,) (varTemplate γ (x, Just e)) sflag <- scheck <$> get let cmakeDivType = if sflag then makeDivType else id let xets = mapThd3 (fmap cmakeDivType) <$> xets' modify $ \i -> i { recCount = recCount i + length xes } let xts = [(x, to) | (x, _, to) <- xets] γ' <- foldM extender (γ `setRecs` (fst <$> xts)) xts mapM_ (consBind True γ') xets return γ' consCB _ _ γ (Rec xes) = do xets <- forM xes $ \(x, e) -> liftM (x, e,) (varTemplate γ (x, Just e)) modify $ \i -> i { recCount = recCount i + length xes } let xts = [(x, to) | (x, _, to) <- xets] γ' <- foldM extender (γ `setRecs` (fst <$> xts)) xts mapM_ (consBind True γ') xets return γ' -- | NV: Dictionaries are not checked, because -- | class methods' preconditions are not satisfied consCB _ _ γ (NonRec x _) | isDictionary x = do t <- trueTy (varType x) extender γ (x, Assumed t) where isDictionary = isJust . dlookup (denv γ) consCB _ _ γ (NonRec x (App (Var w) (Type τ))) | Just d <- dlookup (denv γ) w = do t <- trueTy τ addW $ WfC γ t let xts = dmap (f t) d let γ' = γ{denv = dinsert (denv γ) x xts } t <- trueTy (varType x) extender γ' (x, Assumed t) where f t' (RAllT α te) = subsTyVar_meet' (α, t') te f _ _ = impossible Nothing "consCB on Dictionary: this should not happen" consCB _ _ γ (NonRec x e) = do to <- varTemplate γ (x, Nothing) to' <- consBind False γ (x, e, to) >>= (addPostTemplate γ) extender γ (x, to') -------------------------------------------------------------------------------- consBind :: Bool -> CGEnv -> (Var, CoreExpr ,Template SpecType) -> CG (Template SpecType) -------------------------------------------------------------------------------- consBind isRec γ (x, e, Asserted spect) = do let γ' = γ `setBind` x (_,πs,_,_) = bkUniv spect γπ <- foldM addPToEnv γ' πs cconsE γπ e spect when (F.symbol x `elemHEnv` holes γ) $ -- have to add the wf constraint here for HOLEs so we have the proper env addW $ WfC γπ $ fmap killSubst spect addIdA x (defAnn isRec spect) return $ Asserted spect -- Nothing consBind isRec γ (x, e, Assumed spect) = do let γ' = γ `setBind` x γπ <- foldM addPToEnv γ' πs cconsE γπ e =<< true spect addIdA x (defAnn isRec spect) return $ Asserted spect -- Nothing where πs = ty_preds $ toRTypeRep spect consBind isRec γ (x, e, Unknown) = do t <- consE (γ `setBind` x) e addIdA x (defAnn isRec t) return $ Asserted t noHoles = and . foldReft (\_ r bs -> not (hasHole r) : bs) [] killSubst :: RReft -> RReft killSubst = fmap killSubstReft killSubstReft :: F.Reft -> F.Reft killSubstReft = trans kv () () where kv = defaultVisitor { txExpr = ks } ks _ (F.PKVar k _) = F.PKVar k mempty ks _ p = p -- tx (F.Reft (s, rs)) = F.Reft (s, map f rs) -- f (F.RKvar k _) = F.RKvar k mempty -- f (F.RConc p) = F.RConc p defAnn True = AnnRDf defAnn False = AnnDef addPToEnv γ π = do γπ <- γ ++= ("addSpec1", pname π, pvarRType π) foldM (++=) γπ [("addSpec2", x, ofRSort t) | (t, x, _) <- pargs π] extender γ (x, Asserted t) = γ ++= ("extender", F.symbol x, t) extender γ (x, Assumed t) = γ ++= ("extender", F.symbol x, t) extender γ _ = return γ data Template a = Asserted a | Assumed a | Unknown deriving (Functor, F.Foldable, T.Traversable) deriving instance (Show a) => (Show (Template a)) unTemplate (Asserted t) = t unTemplate (Assumed t) = t unTemplate _ = panic Nothing "Constraint.Generate.unTemplate called on `Unknown`" addPostTemplate γ (Asserted t) = Asserted <$> addPost γ t addPostTemplate γ (Assumed t) = Assumed <$> addPost γ t addPostTemplate _ Unknown = return Unknown safeFromAsserted _ (Asserted t) = t safeFromAsserted msg _ = panic Nothing $ "safeFromAsserted:" ++ msg -- | @varTemplate@ is only called with a `Just e` argument when the `e` -- corresponds to the body of a @Rec@ binder. varTemplate :: CGEnv -> (Var, Maybe CoreExpr) -> CG (Template SpecType) varTemplate γ (x, eo) = case (eo, lookupREnv (F.symbol x) (grtys γ), lookupREnv (F.symbol x) (assms γ)) of (_, Just t, _) -> Asserted <$> refreshArgsTop (x, t) (_, _, Just t) -> Assumed <$> refreshArgsTop (x, t) (Just e, _, _) -> do t <- freshTy_expr RecBindE e (exprType e) addW (WfC γ t) Asserted <$> refreshArgsTop (x, t) (_, _, _) -> return Unknown -------------------------------------------------------------------------------- -- | Constraint Generation: Checking ------------------------------------------- -------------------------------------------------------------------------------- cconsE :: CGEnv -> Expr Var -> SpecType -> CG () -------------------------------------------------------------------------------- cconsE g e t = do -- Note: tracing goes here -- traceM $ printf "cconsE:\n expr = %s\n exprType = %s\n lqType = %s\n" (showPpr e) (showPpr (exprType e)) (showpp t) cconsE' g e t cconsE' :: CGEnv -> Expr Var -> SpecType -> CG () cconsE' γ e@(Let b@(NonRec x _) ee) t = do sp <- specLVars <$> get if (x `S.member` sp) || isDefLazyVar x then cconsLazyLet γ e t else do γ' <- consCBLet γ b cconsE γ' ee t where isDefLazyVar = L.isPrefixOf "fail" . showPpr cconsE' γ e (RAllP p t) = cconsE γ' e t'' where t' = replacePredsWithRefs su <$> t su = (uPVar p, pVartoRConc p) (css, t'') = splitConstraints t' γ' = L.foldl' addConstraints γ css cconsE' γ (Let b e) t = do γ' <- consCBLet γ b cconsE γ' e t cconsE' γ (Case e x _ cases) t = do γ' <- consCBLet γ (NonRec x e) forM_ cases $ cconsCase γ' x t nonDefAlts where nonDefAlts = [a | (a, _, _) <- cases, a /= DEFAULT] cconsE' γ (Lam α e) (RAllT _ t) | isKindVar α = cconsE γ e t cconsE' γ (Lam α e) (RAllT α' t) | isTyVar α = cconsE γ e $ subsTyVar_meet' (α', rVar α) t cconsE' γ (Lam x e) (RFun y ty t _) | not (isTyVar x) = do γ' <- (γ, "cconsE") += (F.symbol x, ty) cconsE γ' e (t `F.subst1` (y, F.EVar $ F.symbol x)) addIdA x (AnnDef ty) cconsE' γ (Tick tt e) t = cconsE (γ `setLocation` (Sp.Tick tt)) e t cconsE' γ (Cast e co) t -- See Note [Type classes with a single method] | Just f <- isClassConCo co = cconsE γ (f e) t cconsE' γ e@(Cast e' _) t = do t' <- castTy γ (exprType e) e' addC (SubC γ t' t) ("cconsE Cast: " ++ showPpr e) cconsE' γ e t = do te <- consE γ e te' <- instantiatePreds γ e te >>= addPost γ addC (SubC γ te' t) ("cconsE: " ++ showPpr e) splitConstraints (RRTy cs _ OCons t) = let (css, t') = splitConstraints t in (cs:css, t') splitConstraints (RFun x tx@(RApp c _ _ _) t r) | isClass c = let (css, t') = splitConstraints t in (css, RFun x tx t' r) splitConstraints t = ([], t) ------------------------------------------------------------------- -- | @instantiatePreds@ peels away the universally quantified @PVars@ -- of a @RType@, generates fresh @Ref@ for them and substitutes them -- in the body. ------------------------------------------------------------------- instantiatePreds γ e (RAllP π t) = do r <- freshPredRef γ e π instantiatePreds γ e $ replacePreds "consE" t [(π, r)] instantiatePreds _ _ t0 = return t0 ------------------------------------------------------------------- -- | @instantiateStrata@ generates fresh @Strata@ vars and substitutes -- them inside the body of the type. ------------------------------------------------------------------- instantiateStrata ls t = substStrata t ls <$> mapM (\_ -> fresh) ls substStrata t ls ls' = F.substa f t where f x = fromMaybe x $ L.lookup x su su = zip ls ls' ------------------------------------------------------------------- cconsLazyLet γ (Let (NonRec x ex) e) t = do tx <- trueTy (varType x) γ' <- (γ, "Let NonRec") +++= (x', ex, tx) cconsE γ' e t where x' = F.symbol x cconsLazyLet _ _ _ = panic Nothing "Constraint.Generate.cconsLazyLet called on invalid inputs" -------------------------------------------------------------------------------- -- | Type Synthesis ------------------------------------------------------------ -------------------------------------------------------------------------------- consE :: CGEnv -> Expr Var -> CG SpecType -------------------------------------------------------------------------------- -- NV this is a hack to type polymorphic axiomatized functions -- no need to check this code with flag, the axioms environment withh -- be empty if there is no axiomatization consE γ e'@(App e@(Var x) (Type τ)) | (M.member x $ aenv γ) = do RAllT α te <- checkAll ("Non-all TyApp with expr", e) <$> consE γ e t <- if isGeneric α te then freshTy_type TypeInstE e τ else trueTy τ addW $ WfC γ t t' <- refreshVV t tt <- instantiatePreds γ e' $ subsTyVar_meet' (α, t') te return $ strengthenS tt (singletonReft (M.lookup x $ aenv γ) x) {- consE γ (Lam β (e'@(App e@(Var x) (Type τ)))) | (M.member x $ aenv γ) && isTyVar β = do RAllT α te <- checkAll ("Non-all TyApp with expr", e) <$> consE γ e t <- if isGeneric α te then freshTy_type TypeInstE e τ else trueTy τ addW $ WfC γ t t' <- refreshVV t tt <- instantiatePreds γ e' $ subsTyVar_meet' (α, t') te return $ RAllT (rTyVar β) $ strengthenS tt (singletonReft (M.lookup x $ aenv γ) x) -} -- NV END HACK consE γ (Var x) = do t <- varRefType γ x addLocA (Just x) (getLocation γ) (varAnn γ x t) return t consE _ (Lit c) = refreshVV $ uRType $ literalFRefType c consE γ (App e (Type τ)) | isKind τ = consE γ e consE γ e'@(App e (Type τ)) = do RAllT α te <- checkAll ("Non-all TyApp with expr", e) <$> consE γ e t <- if isGeneric α te then freshTy_type TypeInstE e τ else trueTy τ addW $ WfC γ t t' <- refreshVV t instantiatePreds γ e' $ subsTyVar_meet' (α, t') te -- RJ: The snippet below is *too long*. Please pull stuff from the where-clause -- out to the top-level. consE γ e'@(App e a) | isDictionary a = if isJust tt then return $ fromJust tt else do ([], πs, ls, te) <- bkUniv <$> consE γ e te0 <- instantiatePreds γ e' $ foldr RAllP te πs te' <- instantiateStrata ls te0 (γ', te''') <- dropExists γ te' te'' <- dropConstraints γ te''' updateLocA {- πs -} (exprLoc e) te'' let RFun x tx t _ = checkFun ("Non-fun App with caller ", e') te'' pushConsBind $ cconsE γ' a tx addPost γ' $ maybe (checkUnbound γ' e' x t a) (F.subst1 t . (x,)) (argExpr γ a) where grepfunname (App x (Type _)) = grepfunname x grepfunname (Var x) = x grepfunname e = panic Nothing $ "grepfunname on \t" ++ showPpr e mdict w = case w of Var x -> case dlookup (denv γ) x of {Just _ -> Just x; Nothing -> Nothing} Tick _ e -> mdict e _ -> Nothing isDictionary _ = isJust (mdict a) d = fromJust (mdict a) dinfo = dlookup (denv γ) d tt = dhasinfo dinfo $ grepfunname e consE γ e'@(App e a) = do ([], πs, ls, te) <- bkUniv <$> consE γ e te0 <- instantiatePreds γ e' $ foldr RAllP te πs te' <- instantiateStrata ls te0 (γ', te''') <- dropExists γ te' te'' <- dropConstraints γ te''' updateLocA {- πs -} (exprLoc e) te'' let RFun x tx t _ = checkFun ("Non-fun App with caller ", e') te'' pushConsBind $ cconsE γ' a tx addPost γ' $ maybe (checkUnbound γ' e' x t a) (F.subst1 t . (x,)) (argExpr γ a) {- tt <- addPost γ' $ maybe (checkUnbound γ' e' x t a) (F.subst1 t . (x,)) (argExpr γ a) let rr = case (argExpr γ e, argExpr γ a) of (Just e', Just a') -> uTop $ F.Reft (F.vv_, F.PAtom F.Eq (F.EVar F.vv_) (F.EApp e' a')) _ -> mempty return $ tt `strengthen` rr -} consE γ (Lam α e) | isTyVar α = liftM (RAllT (rTyVar α)) (consE γ e) consE γ e@(Lam x e1) = do tx <- freshTy_type LamE (Var x) τx γ' <- ((γ, "consE") += (F.symbol x, tx)) t1 <- consE γ' e1 addIdA x $ AnnDef tx addW $ WfC γ tx return $ rFun (F.symbol x) tx t1 where FunTy τx _ = exprType e consE γ e@(Let _ _) = cconsFreshE LetE γ e consE γ e@(Case _ _ _ _) = cconsFreshE CaseE γ e consE γ (Tick tt e) = do t <- consE (setLocation γ (Sp.Tick tt)) e addLocA Nothing (tickSrcSpan tt) (AnnUse t) return t consE γ (Cast e co) -- See Note [Type classes with a single method] | Just f <- isClassConCo co = consE γ (f e) consE γ e@(Cast e' _) = castTy γ (exprType e) e' consE _ e@(Coercion _) = trueTy $ exprType e consE _ e@(Type t) = panic Nothing $ "consE cannot handle type " ++ showPpr (e, t) castTy _ τ (Var x) = do t <- trueTy τ return $ t `strengthen` (uTop $ F.uexprReft $ F.expr x) castTy g t (Tick _ e) = castTy g t e castTy _ _ e = panic Nothing $ "castTy cannot handle expr " ++ showPpr e isClassConCo :: Coercion -> Maybe (Expr Var -> Expr Var) -- See Note [Type classes with a single method] isClassConCo co --- | trace ("isClassConCo: " ++ showPpr (coercionKind co)) False --- = undefined | Pair t1 t2 <- coercionKind co , isClassPred t2 , (tc,ts) <- splitTyConApp t2 , [dc] <- tyConDataCons tc , [tm] <- dataConOrigArgTys dc -- tcMatchTy because we have to instantiate the class tyvars , Just _ <- tcMatchTy (mkVarSet $ tyConTyVars tc) tm t1 = Just (\e -> mkCoreConApps dc $ map Type ts ++ [e]) | otherwise = Nothing ---------------------------------------------------------------------- -- Note [Type classes with a single method] ---------------------------------------------------------------------- -- GHC 7.10 encodes type classes with a single method as newtypes and -- `cast`s between the method and class type instead of applying the -- class constructor. Just rewrite the core to what we're used to -- seeing.. -- -- specifically, we want to rewrite -- -- e `cast` ((a -> b) ~ C) -- -- to -- -- D:C e -- -- but only when -- -- D:C :: (a -> b) -> C -- | @consElimE@ is used to *synthesize* types by **existential elimination** -- instead of *checking* via a fresh template. That is, assuming -- γ |- e1 ~> t1 -- we have -- γ |- let x = e1 in e2 ~> Ex x t1 t2 -- where -- γ, x:t1 |- e2 ~> t2 -- instead of the earlier case where we generate a fresh template `t` and check -- γ, x:t1 |- e <~ t -- consElimE γ xs e -- = do t <- consE γ e -- xts <- forM xs $ \x -> (x,) <$> (γ ??= x) -- return $ rEx xts t -- | @consFreshE@ is used to *synthesize* types with a **fresh template** when -- the above existential elimination is not easy (e.g. at joins, recursive binders) cconsFreshE kvkind γ e = do t <- freshTy_type kvkind e $ exprType e addW $ WfC γ t cconsE γ e t return t checkUnbound γ e x t a | x `notElem` (F.syms t) = t | otherwise = panic (Just $ getLocation γ) msg where msg = unlines [ "checkUnbound: " ++ show x ++ " is elem of syms of " ++ show t , "In", showPpr e, "Arg = " , show a ] dropExists γ (REx x tx t) = liftM (, t) $ (γ, "dropExists") += (x, tx) dropExists γ t = return (γ, t) dropConstraints :: CGEnv -> SpecType -> CG SpecType dropConstraints γ (RFun x tx@(RApp c _ _ _) t r) | isClass c = (flip (RFun x tx)) r <$> dropConstraints γ t dropConstraints γ (RRTy cts _ OCons t) = do γ' <- foldM (\γ (x, t) -> γ `addSEnv` ("splitS", x,t)) γ xts addC (SubC γ' t1 t2) "dropConstraints" dropConstraints γ t where (xts, t1, t2) = envToSub cts dropConstraints _ t = return t ------------------------------------------------------------------------------------- cconsCase :: CGEnv -> Var -> SpecType -> [AltCon] -> (AltCon, [Var], CoreExpr) -> CG () ------------------------------------------------------------------------------------- cconsCase γ x t acs (ac, ys, ce) = do cγ <- caseEnv γ x acs ac ys cconsE cγ ce t -------------------------------------------------------------------------------- refreshTy :: SpecType -> CG SpecType -------------------------------------------------------------------------------- refreshTy t = refreshVV t >>= refreshArgs refreshVV (RAllT a t) = liftM (RAllT a) (refreshVV t) refreshVV (RAllP p t) = liftM (RAllP p) (refreshVV t) refreshVV (REx x t1 t2) = do [t1', t2'] <- mapM refreshVV [t1, t2] liftM (shiftVV (REx x t1' t2')) fresh refreshVV (RFun x t1 t2 r) = do [t1', t2'] <- mapM refreshVV [t1, t2] liftM (shiftVV (RFun x t1' t2' r)) fresh refreshVV (RAppTy t1 t2 r) = do [t1', t2'] <- mapM refreshVV [t1, t2] liftM (shiftVV (RAppTy t1' t2' r)) fresh refreshVV (RApp c ts rs r) = do ts' <- mapM refreshVV ts rs' <- mapM refreshVVRef rs liftM (shiftVV (RApp c ts' rs' r)) fresh refreshVV t = return t refreshVVRef (RProp ss (RHole r)) = return $ RProp ss (RHole r) refreshVVRef (RProp ss t) = do xs <- mapM (\_ -> fresh) (fst <$> ss) let su = F.mkSubst $ zip (fst <$> ss) (F.EVar <$> xs) liftM (RProp (zip xs (snd <$> ss)) . F.subst su) (refreshVV t) ------------------------------------------------------------------------------------- caseEnv :: CGEnv -> Var -> [AltCon] -> AltCon -> [Var] -> CG CGEnv ------------------------------------------------------------------------------------- caseEnv γ x _ (DataAlt c) ys = do let (x' : ys') = F.symbol <$> (x:ys) xt0 <- checkTyCon ("checkTycon cconsCase", x) <$> γ ??= x let xt = shiftVV xt0 x' tdc <- γ ??= ({- F.symbol -} dataConWorkId c) >>= refreshVV let (rtd, yts, _) = unfoldR tdc xt ys let r1 = dataConReft c ys' let r2 = dataConMsReft rtd ys' let xt = (xt0 `F.meet` rtd) `strengthen` (uTop (r1 `F.meet` r2)) let cbs = safeZip "cconsCase" (x':ys') (xt0:yts) cγ' <- addBinders γ x' cbs cγ <- addBinders cγ' x' [(x', xt)] return cγ caseEnv γ x acs a _ = do let x' = F.symbol x xt' <- (`strengthen` uTop (altReft γ acs a)) <$> (γ ??= x) cγ <- addBinders γ x' [(x', xt')] return cγ altReft _ _ (LitAlt l) = literalFReft l altReft γ acs DEFAULT = mconcat [notLiteralReft l | LitAlt l <- acs] where notLiteralReft = maybe mempty F.notExprReft . snd . literalConst (emb γ) altReft _ _ _ = panic Nothing "Constraint : altReft" unfoldR td (RApp _ ts rs _) ys = (t3, tvys ++ yts, ignoreOblig rt) where tbody = instantiatePvs (instantiateTys td ts) $ reverse rs (ys0, yts', _, rt) = safeBkArrow $ instantiateTys tbody tvs' yts'' = zipWith F.subst sus (yts'++[rt]) (t3,yts) = (last yts'', init yts'') sus = F.mkSubst <$> (L.inits [(x, F.EVar y) | (x, y) <- zip ys0 ys']) (αs, ys') = mapSnd (F.symbol <$>) $ L.partition isTyVar ys tvs' = rVar <$> αs tvys = ofType . varType <$> αs unfoldR _ _ _ = panic Nothing "Constraint.hs : unfoldR" instantiateTys = L.foldl' go where go (RAllT α tbody) t = subsTyVar_meet' (α, t) tbody go _ _ = panic Nothing "Constraint.instanctiateTy" instantiatePvs = L.foldl' go where go (RAllP p tbody) r = replacePreds "instantiatePv" tbody [(p, r)] go _ _ = panic Nothing "Constraint.instanctiatePv" checkTyCon _ t@(RApp _ _ _ _) = t checkTyCon x t = checkErr x t checkFun _ t@(RFun _ _ _ _) = t checkFun x t = checkErr x t checkAll _ t@(RAllT _ _) = t checkAll x t = checkErr x t checkErr (msg, e) t = panic Nothing $ msg ++ showPpr e ++ ", type: " ++ showpp t varAnn γ x t | x `S.member` recs γ = AnnLoc (getSrcSpan x) | otherwise = AnnUse t ----------------------------------------------------------------------- -- | Helpers: Creating Fresh Refinement ------------------------------- ----------------------------------------------------------------------- freshPredRef :: CGEnv -> CoreExpr -> PVar RSort -> CG SpecProp freshPredRef γ e (PV _ (PVProp τ) _ as) = do t <- freshTy_type PredInstE e (toType τ) args <- mapM (\_ -> fresh) as let targs = [(x, s) | (x, (s, y, z)) <- zip args as, (F.EVar y) == z ] γ' <- foldM (++=) γ [("freshPredRef", x, ofRSort τ) | (x, τ) <- targs] addW $ WfC γ' t return $ RProp targs t freshPredRef _ _ (PV _ PVHProp _ _) = todo Nothing "EFFECTS:freshPredRef" -------------------------------------------------------------------------------- -- | Helpers: Creating Refinement Types For Various Things --------------------- -------------------------------------------------------------------------------- argExpr :: CGEnv -> CoreExpr -> Maybe F.Expr argExpr _ (Var vy) = Just $ F.eVar vy argExpr γ (Lit c) = snd $ literalConst (emb γ) c argExpr γ (Tick _ e) = argExpr γ e argExpr _ _ = Nothing -------------------------------------------------------------------------------- (??=) :: (?callStack :: CallStack) => CGEnv -> Var -> CG SpecType -------------------------------------------------------------------------------- γ ??= x = case M.lookup x' (lcb γ) of Just e -> consE (γ -= x') e Nothing -> refreshTy tx where x' = F.symbol x tx = fromMaybe tt (γ ?= x') tt = ofType $ varType x -------------------------------------------------------------------------------- varRefType :: (?callStack :: CallStack) => CGEnv -> Var -> CG SpecType -------------------------------------------------------------------------------- varRefType γ x = do xt <- varRefType' γ x <$> (γ ??= x) return xt -- F.tracepp (printf "varRefType x = [%s]" (showpp x)) varRefType' :: CGEnv -> Var -> SpecType -> SpecType varRefType' γ x t' | Just tys <- trec γ, Just tr <- M.lookup x' tys = tr `strengthenS` xr | otherwise = t' `strengthenS` xr where xr = singletonReft (M.lookup x $ aenv γ) x x' = F.symbol x singletonReft (Just x) _ = uTop $ F.symbolReft x singletonReft Nothing v = uTop $ F.symbolReft $ F.symbol v -- | RJ: `nomeet` replaces `strengthenS` for `strengthen` in the definition -- of `varRefType`. Why does `tests/neg/strata.hs` fail EVEN if I just replace -- the `otherwise` case? The fq file holds no answers, both are sat. strengthenS :: (PPrint r, F.Reftable r) => RType c tv r -> r -> RType c tv r strengthenS (RApp c ts rs r) r' = RApp c ts rs $ topMeet r r' strengthenS (RVar a r) r' = RVar a $ topMeet r r' strengthenS (RFun b t1 t2 r) r' = RFun b t1 t2 $ topMeet r r' strengthenS (RAppTy t1 t2 r) r' = RAppTy t1 t2 $ topMeet r r' strengthenS t _ = t topMeet :: (PPrint r, F.Reftable r) => r -> r -> r topMeet r r' = {- F.tracepp msg $ -} F.top r `F.meet` r' -- where -- msg = printf "topMeet r = [%s] r' = [%s]" (showpp r) (showpp r') -- traceM $ printf "cconsE:\n expr = %s\n exprType = %s\n lqType = %s\n" (showPpr e) (showPpr (exprType e)) (showpp t) -------------------------------------------------------------------------------- -- | Cleaner Signatures For Rec-bindings --------------------------------------- -------------------------------------------------------------------------------- exprLoc :: CoreExpr -> Maybe SrcSpan exprLoc (Tick tt _) = Just $ tickSrcSpan tt exprLoc (App e a) | isType a = exprLoc e exprLoc _ = Nothing isType (Type _) = True isType a = eqType (exprType a) predType exprRefType :: CoreExpr -> SpecType exprRefType = exprRefType_ M.empty exprRefType_ :: M.HashMap Var SpecType -> CoreExpr -> SpecType exprRefType_ γ (Let b e) = exprRefType_ (bindRefType_ γ b) e exprRefType_ γ (Lam α e) | isTyVar α = RAllT (rTyVar α) (exprRefType_ γ e) exprRefType_ γ (Lam x e) = rFun (F.symbol x) (ofType $ varType x) (exprRefType_ γ e) exprRefType_ γ (Tick _ e) = exprRefType_ γ e exprRefType_ γ (Var x) = M.lookupDefault (ofType $ varType x) x γ exprRefType_ _ e = ofType $ exprType e bindRefType_ γ (Rec xes) = extendγ γ [(x, exprRefType_ γ e) | (x,e) <- xes] bindRefType_ γ (NonRec x e) = extendγ γ [(x, exprRefType_ γ e)] extendγ γ xts = foldr (\(x,t) m -> M.insert x t m) γ xts isGeneric :: RTyVar -> SpecType -> Bool isGeneric α t = all (\(c, α') -> (α'/=α) || isOrd c || isEq c ) (classConstrs t) where classConstrs t = [(c, α') | (c, ts) <- tyClasses t , t' <- ts , α' <- freeTyVars t'] isOrd = (ordClassName ==) . className isEq = (eqClassName ==) . className
ssaavedra/liquidhaskell
src/Language/Haskell/Liquid/Constraint/Generate.hs
bsd-3-clause
52,720
8
17
14,729
17,849
9,059
8,790
944
9
module Graphics.UI.Gtk.WebKit.WebFrame where {- -- * Description -- | A WebKitWebView contains a main WebKitWebFrame. A WebKitWebFrame contains the content of one -- URI. The URI and name of the frame can be retrieved, the load status and progress can be observed -- using the signals and can be controlled using the methods of the WebKitWebFrame. A WebKitWebFrame -- can have any number of children and one child can be found by using 'webFrameFindFrame'. -- * Types WebFrame, WebFrameClass, LoadStatus, -- * Constructors webFrameNew, -- * Methods webFrameGetWebView, webFrameGetName, #if WEBKIT_CHECK_VERSION (1,1,18) webFrameGetNetworkResponse, #endif webFrameGetTitle, webFrameGetUri, webFrameGetParent, webFrameGetLoadStatus, webFrameLoadUri, webFrameLoadString, webFrameLoadAlternateString, webFrameLoadRequest, webFrameStopLoading, webFrameReload, webFrameFindFrame, webFrameGetDataSource, webFrameGetHorizontalScrollbarPolicy, webFrameGetVerticalScrollbarPolicy, webFrameGetProvisionalDataSource, webFrameGetSecurityOrigin, webFramePrint, ) where import Control.Monad (liftM) import Data.ByteString (ByteString, useAsCString) import System.Glib.FFI import System.Glib.UTFString import System.Glib.GList import System.Glib.GError import Graphics.UI.Gtk.Gdk.Events import Graphics.UI.Gtk.General.Enums {#import Graphics.UI.Gtk.Abstract.Object#} (makeNewObject) {#import Graphics.UI.Gtk.WebKit.Types#} {#import System.Glib.GObject#} {#context lib="webkit" prefix ="webkit"#} -- * Enums {#enum LoadStatus {underscoreToCase}#} ------------------ -- Constructors -- | Create a new 'WebFrame' instance with the given @webview@. -- -- A 'WebFrame' contains the content of one URI. webFrameNew :: WebViewClass webview => webview -- ^ @webview@ - the given webview -> IO WebFrame webFrameNew webview = wrapNewGObject mkWebFrame $ {#call web_frame_new#} (toWebView webview) -- | Return the 'WebView' that manages the given 'WebFrame'. webFrameGetWebView :: WebFrameClass self => self -> IO WebView webFrameGetWebView webframe = makeNewObject mkWebView $ liftM castPtr $ {#call web_frame_get_web_view#} (toWebFrame webframe) -- | Return the name of the given 'WebFrame'. webFrameGetName :: (WebFrameClass self, GlibString string) => self -> IO (Maybe string) -- ^ the name string or @Nothing@ in case failed. webFrameGetName webframe = {#call web_frame_get_name#} (toWebFrame webframe) >>= maybePeek peekUTFString #if WEBKIT_CHECK_VERSION (1,1,18) -- | Returns a WebKitNetworkResponse object representing the response that was given to the request for -- the given frame, or 'Nothing' if the frame was not created by a load. -- -- * Since 1.1.18 webFrameGetNetworkResponse :: WebFrameClass self => self -> IO (Maybe NetworkResponse) webFrameGetNetworkResponse frame = maybeNull (makeNewGObject mkNetworkResponse) $ {#call webkit_web_frame_get_network_response#} (toWebFrame frame) #endif -- | Return the title of the given 'WebFrame'. webFrameGetTitle :: (WebFrameClass self, GlibString string) => self -> IO (Maybe string) -- ^ the title string or @Nothing@ in case failed. webFrameGetTitle webframe = {#call web_frame_get_title#} (toWebFrame webframe) >>= maybePeek peekUTFString -- | Return the URI of the given 'WebFrame'. webFrameGetUri :: (WebFrameClass self, GlibString string) => self -> IO (Maybe string) -- ^ the URI string or @Nothing@ in case failed. webFrameGetUri webframe = {#call web_frame_get_uri#} (toWebFrame webframe) >>= maybePeek peekUTFString -- | Return the 'WebFrame''s parent frame if it has one, -- Otherwise return Nothing. webFrameGetParent :: WebFrameClass self => self -> IO (Maybe WebFrame) -- ^ a 'WebFrame' or @Nothing@ in case failed. webFrameGetParent webframe = maybeNull (makeNewGObject mkWebFrame) $ {#call web_frame_get_parent#} (toWebFrame webframe) -- | Determines the current status of the load. -- -- frame : a WebKitWebView -- -- * Since 1.1.7 webFrameGetLoadStatus :: WebFrameClass self => self -> IO LoadStatus webFrameGetLoadStatus ls = liftM (toEnum . fromIntegral) $ {#call web_frame_get_load_status#} (toWebFrame ls) -- | Request loading of the specified URI string. webFrameLoadUri :: (WebFrameClass self, GlibString string) => self -> string -- ^ @uri@ - an URI string. -> IO () webFrameLoadUri webframe uri = withUTFString uri $ \uriPtr -> {#call web_frame_load_uri#} (toWebFrame webframe) uriPtr -- | Requests loading of the given @content@ -- with the specified @mime_type@ and @base_uri@. -- -- If @mime_type@ is @Nothing@, \"text/html\" is assumed. -- -- If want control over the encoding use `webFrameLoadByteString` webFrameLoadString :: (WebFrameClass self, GlibString string) => self -> string -- ^ @content@ - the content string to be loaded. -> (Maybe string) -- ^ @mime_type@ - the MIME type or @Nothing@. -> string -- ^ @base_uri@ - the base URI for relative locations. -> IO() webFrameLoadString webframe content mimetype baseuri = withUTFString content $ \contentPtr -> maybeWith withUTFString mimetype $ \mimetypePtr -> withUTFString baseuri $ \baseuriPtr -> {#call web_frame_load_string#} (toWebFrame webframe) contentPtr mimetypePtr nullPtr baseuriPtr -- | Requests loading of the given @content@ -- with the specified @mime_type@, @encoding@ and @base_uri@. -- -- If @mime_type@ is @Nothing@, \"text/html\" is assumed. -- -- If @encoding@ is @Nothing@, \"UTF-8\" is assumed. webFrameLoadByteString :: (WebFrameClass self, GlibString string) => self -> ByteString -- ^ @content@ - the content string to be loaded. -> (Maybe string) -- ^ @mime_type@ - the MIME type or @Nothing@. -> (Maybe string) -- ^ @encoding@ - the encoding or @Nothing@. -> string -- ^ @base_uri@ - the base URI for relative locations. -> IO() webFrameLoadByteString webframe content mimetype encoding baseuri = useAsCString content $ \contentPtr -> maybeWith withUTFString mimetype $ \mimetypePtr -> maybeWith withUTFString encoding $ \encodingPtr -> withUTFString baseuri $ \baseuriPtr -> {#call web_frame_load_string#} (toWebFrame webframe) contentPtr mimetypePtr encodingPtr baseuriPtr -- |Request loading of an alternate content for a URL that is unreachable. -- -- Using this method will preserve the back-forward list. -- The URI passed in @base_uri@ has to be an absolute URI. webFrameLoadAlternateString :: (WebFrameClass self, GlibString string) => self -> string -- ^ @content@ - the alternate content to display -- as the main page of the frame -> string -- ^ @base_uri@ - the base URI for relative locations. -> string -- ^ @unreachable_url@ - the URL for the alternate page content. -> IO() webFrameLoadAlternateString webframe content baseurl unreachableurl = withUTFString content $ \contentPtr -> withUTFString baseurl $ \baseurlPtr -> withUTFString unreachableurl $ \unreachableurlPtr -> {#call web_frame_load_alternate_string#} (toWebFrame webframe) contentPtr baseurlPtr unreachableurlPtr -- | Connects to a given URI by initiating an asynchronous client request. -- -- Creates a provisional data source that will transition to a committed data source once any data has been received. -- Use 'webFrameStopLoading' to stop the load. -- This function is typically invoked on the main frame. webFrameLoadRequest :: (WebFrameClass self, NetworkRequestClass requ) => self -> requ -> IO () webFrameLoadRequest webframe request = {#call web_frame_load_request#} (toWebFrame webframe) (toNetworkRequest request) -- | Stops and pending loads on the given data source and those of its children. webFrameStopLoading :: WebFrameClass self => self -> IO() webFrameStopLoading webframe = {#call web_frame_stop_loading#} (toWebFrame webframe) -- |Reloads the initial request. webFrameReload :: WebFrameClass self => self -> IO() webFrameReload webframe = {#call web_frame_reload#} (toWebFrame webframe) -- |Return the 'WebFrame' associated with the given name -- or @Nothing@ in case none if found -- -- For pre-defined names, return the given webframe if name is webFrameFindFrame:: (WebFrameClass self, GlibString string) => self -> string -- ^ @name@ - the name of the frame to be found. -> IO (Maybe WebFrame) webFrameFindFrame webframe name = withUTFString name $ \namePtr -> maybeNull (makeNewGObject mkWebFrame) $ {#call web_frame_find_frame#} (toWebFrame webframe) namePtr -- | Returns the committed data source. webFrameGetDataSource :: WebFrameClass self => self -> IO WebDataSource webFrameGetDataSource webframe = makeNewGObject mkWebDataSource $ {#call web_frame_get_data_source#} (toWebFrame webframe) -- | Return the policy of horizontal scrollbar. webFrameGetHorizontalScrollbarPolicy :: WebFrameClass self => self -> IO PolicyType webFrameGetHorizontalScrollbarPolicy webframe = liftM (toEnum.fromIntegral) $ {#call web_frame_get_horizontal_scrollbar_policy#} (toWebFrame webframe) -- | Return the policy of vertical scrollbar. webFrameGetVerticalScrollbarPolicy :: WebFrameClass self => self -> IO PolicyType webFrameGetVerticalScrollbarPolicy webframe = liftM (toEnum.fromIntegral) $ {#call web_frame_get_vertical_scrollbar_policy#} (toWebFrame webframe) -- | You use the 'webFrameLoadRequest' method to initiate a request that creates a provisional data source. -- The provisional data source will transition to a committed data source once any data has been received. -- Use 'webFrameGetDataSource' to get the committed data source. webFrameGetProvisionalDataSource :: WebFrameClass self => self -> IO WebDataSource webFrameGetProvisionalDataSource webframe = makeNewGObject mkWebDataSource $ {#call web_frame_get_provisional_data_source#} (toWebFrame webframe) -- | Returns the frame's security origin. webFrameGetSecurityOrigin :: WebFrameClass self => self -> IO SecurityOrigin webFrameGetSecurityOrigin webframe = makeNewGObject mkSecurityOrigin $ {#call web_frame_get_security_origin#} (toWebFrame webframe) -- |Prints the given 'WebFrame'. -- -- by presenting a print dialog to the user. webFramePrint:: WebFrameClass self => self -> IO() webFramePrint webframe = {#call web_frame_print#} (toWebFrame webframe) -}
mightybyte/reflex-dom-stubs
src/Graphics/UI/Gtk/WebKit/WebFrame.hs
bsd-3-clause
10,525
0
3
1,836
10
8
2
1
0
{-| -} module Snap.Extension.Session ( MonadSession(..) , Session ) where import Control.Monad import qualified Data.ByteString.Char8 as B import Data.ByteString (ByteString) import Data.Map (Map) import qualified Data.Map as Map import Snap.Types ------------------------------------------------------------------------------ -- | Base session on the fast and capable Map library. -- TODO: Does this have a large performance hit? type Session = Map ByteString ByteString ------------------------------------------------------------------------------ -- | The 'MonadCookieSession' class. Minimum complete definition: 'getSession' -- and 'setSession'. class MonadSnap m => MonadSession m where ---------------------------------------------------------------------------- -- | Function to get the session in your app's monad. -- -- This will return a @Map ByteString ByteString@ data type, which you can -- then use freely to read/write values. getSession :: m Session ---------------------------------------------------------------------------- -- | Set the session in your app's monad. setSession :: Session -> m () ------------------------------------------------------------------------------ -- | Get a value associated with given key from the 'Session'. getFromSession :: ByteString -> m (Maybe ByteString) getFromSession k = Map.lookup k `liftM` getSession ------------------------------------------------------------------------------ -- | Remove the given key from 'Session' deleteFromSession :: ByteString -> m () deleteFromSession k = Map.delete k `liftM` getSession >>= setSession ------------------------------------------------------------------------------ -- | Set a value in the 'Session'. setInSession :: ByteString -> ByteString -> m () setInSession k v = Map.insert k v `liftM` getSession >>= setSession ---------------------------------------------------------------------------- -- | Clear the active session. Uses 'setSession'. clearSession :: m () clearSession = setSession Map.empty ---------------------------------------------------------------------------- -- | Touch session to reset the timeout. You can chain a handler to call this -- in every authenticated route to keep prolonging the session with each -- request. touchSession :: m () touchSession = getSession >>= setSession
ozataman/snap-extension-session
src/Snap/Extension/Session.hs
bsd-3-clause
2,474
0
10
432
299
175
124
25
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} module Spec.App ( appSpecs ) where import Base import Control.Monad.IO.Class (MonadIO) import Data.Aeson hiding (json) import Data.ByteString (ByteString) import qualified Data.ByteString.Lazy as L (ByteString) import Network.HTTP.Types (methodPost, status201) import Network.Wai (Application) import Network.Wai.Test (SResponse(..)) import Test.Hspec (it) import qualified Test.Hspec as H import Test.Hspec.Wai import Test.Hspec.Wai.JSON import qualified Data.HashMap.Strict as HM shouldBe :: (Eq a, Show a, MonadIO m) => a -> a -> m () shouldBe a b = liftIO $ H.shouldBe a b postJSON :: ByteString -> AuthToken -> L.ByteString -> WaiSession SResponse postJSON path token body = request methodPost path headers body where headers = [ ("Authorization", token) , ("Content-Type", "application/json") , ("Accept", "application/json") ] toObject :: L.ByteString -> Object toObject s = case eitherDecode s of (Left err) -> error err (Right (Object o)) -> o _ -> error "Couldn't decode as object" shouldIncludeJson :: L.ByteString -> L.ByteString -> WaiSession () shouldIncludeJson haystack needle = intersection `shouldBe` needle' where needle' = toObject needle intersection = HM.intersection (toObject haystack) needle' appSpecs :: H.SpecWith Application appSpecs = do it "can create new spaces" $ do let fields = [json|{name:"New Space", description:"Desc"}|] (SResponse status _ body) <- postJSON "/spaces" "[email protected]" fields status `shouldBe` status201 body `shouldIncludeJson` fields
jamesdabbs/pi-base-2
test/Spec/App.hs
bsd-3-clause
1,776
0
12
396
494
277
217
42
3
import Control.Monad import Data.String.Utils (replace) import System.Environment (getArgs) import System.IO (hGetContents) import System.Process (system, runInteractiveCommand) import Text.Printf (printf) readCommand :: String -> IO String readCommand cmd = do (_, stdout, _, _) <- runInteractiveCommand cmd hGetContents stdout main :: IO () main = do system "mkdir -p tmp/" argv <- getArgs forM_ argv $ \fn -> do system $ "rm -rf tmp/*" system $ printf "convert -verbose -density 100 %s -quality 100 tmp/page.png" fn pngfns <- readCommand "ls -1 tmp/*.png" forM_ (zip [1..] $ words pngfns) $ \(page,pagefn) -> do infoStr <- readCommand $ printf "identify %s" pagefn let bgfn = replace "page-" "back-" pagefn retfn = replace "page-" "ret-" pagefn geomStr = words infoStr !! 2 isFlopStr | odd page = "" | otherwise = "-flop" system $ printf "convert resource/bookelement17.jpg -scale %s %s %s" geomStr isFlopStr bgfn system $ printf "convert %s %s -compose Multiply -composite %s" bgfn pagefn retfn
nushio3/pdf-vintage
main.hs
bsd-3-clause
1,108
0
21
261
328
161
167
28
1
-- 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. module Duckling.Ordinal.DE.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Ordinal.DE.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "DE Tests" [ makeCorpusTest [This Ordinal] corpus , makeNegativeCorpusTest [This Ordinal] negativeCorpus ]
rfranek/duckling
tests/Duckling/Ordinal/DE/Tests.hs
bsd-3-clause
657
0
9
103
94
58
36
12
1
{-+ This module contains experimental stuff to complete the dictionary translation by translating class declarations to record types and instance declaration to record values. Doing this while staying within the source abstract syntax is a bit clumbsy, unfortunately. The default methods in class declarations are placed in a "default instance", i.e. a record of the same type as an instance, from with the default methods are selected by the translation of instance declarations. Apart from fields corresponding to methods, the record types also contain fields corresponding to superclasses. The context reduction function refers to these functions. Most of this is not used at the moment. -} module TiClassInst2({-tcClassDecl,tcInstDecl,-}tcInstOrClassDecl'') where import List((\\)) --import HasBaseStruct(HasBaseStruct(..),hsTypeSig,hsClassDecl,hsInstDecl) import HasBaseStruct import BaseSyntax hiding (TI) --import SrcLoc(SrcLoc,srcLoc) import TI import qualified TiKEnv(lookup) import TiDkc(Dinst{-,Einst-}) import TiDinst(hsSimpleBind{-,hsSimpleBind',tcSelFns-}) import TiSolve(matches) --import MUtils import PrettyPrint {- tcClassDecl d src ctx cl fdeps ds = do let (msigs,defaults) = splitMethodSigs ds (ms,ds') <- tcClassDecl' src [cl] cl defaults msigs':>:_ <- tcLocalDecls msigs -- kind check + type conversion hsClassDecl2 d {-bs-} ms src ctx cl fdeps msigs' ds' tcInstDecl src ictx inst ds = do (ns,ds') <- tcInstDecl' src ictx inst ds modmap <- getModule let n = instName' modmap src -- return $ hsInstDecl0 n ns src ictx inst ds' hsInstDecl2 n ns src ictx inst ds' -} -------------------------------------------------------------------------------- {- hsClassDecl2 :: (Printable i,ValueId i,Eq i,TypeVar i, HasBaseStruct d2 (Dinst i e2 p2 ds2), HasBaseStruct e2 (Einst i e2 p2 ds2),HasId i e2, DeclInfo i (Dinst i e2 p2 ds2), HasId i p2, HasDef ds2 d2, --GetSigs i [Pred i] (Pred i) ds2, HasAbstr i d2,AddDeclsType i ds2, HasBaseStruct e1 (Einst i e1 p1 ds1),HasBaseStruct p1 (PI i p1), HasDef ds1 d1,TypeCheckDecl i (Dinst i e1 p1 ds1) ds2 ) => (Dinst i e1 p1 ds1) -> MethodInfo i -> SrcLoc -> [Pred i] -> Pred i -> HsFunDeps i -> ds2 -> ds2 -> TI i ds2 hsClassDecl2 d1 {-bs-} mi@(ms,_,_) src ctx cl fdeps msigs ds = do defaultInst <- hsDefaultMethods dn mi src ctx cl ds --m <- getModule let fields = [HsRecDecl src cn (supers++ [([i],unb (hsTyForall' vs (funT (c++[t])))) | HsVar i:>:Forall vs (c:=>t)<-ms])] dictdata <- return $ HsDataDecl src [] cl fields [] let dts = explicitlyTyped {-m-} [] dictdata selfns <- extendts dts $ tcSelFns [d1] []{-bs-} fields return $ addDeclsType ([],[HsVar dn:>:upscheme (funT [cl,cl])]) $ base dictdata `consDef` defaultInst `consDef` selfns where dn = defaultName cn c@(HsCon cn) = definedType cl supers = [([superName cn n],unb c)|(n,c)<-zip [1..] ctx] unb = HsUnBangedType hsTyForall' [] t = t hsTyForall' vs t = hsTyForall vs t hsDefaultMethods :: (HasDef ds2 d2,HasBaseStruct d2 (Dinst i e p ds2), HasId i e,HasId i p,Eq i,ValueId i,Printable i, HasAbstr i d2,AddDeclsType i ds2, HasBaseStruct e (Einst i e p ds2)) => i -> MethodInfo i -> SrcLoc -> [Pred i] -> Pred i -> ds2 -> TI i d2 hsDefaultMethods dn (ms,ims,_) src ctx cl ds = do darg <- dictName # fresh return $ abstract [darg] $ hsSimpleBind' src dn (body [darg]) ds where c@(HsCon cn) = definedType cl body dns = hsRecConstr cn (superDefs++methodDefs) where methodDefs = map methodDef ms superDefs = [HsField n (noDefault n)|n<-take (length ctx) superns] where superns = map (superName cn) [1..] methodDef (i@(HsVar v):>:_) = HsField v $ if i `elem` ims then apps (ident i:map var dns) else noDefault i noDefault i = hsApp (var (prelVal "error")) (hsLit$HsString$pp$src<>": no default for:"<+>i) apps = foldl1 hsApp -} -------------------------------------------------------------------------------- type MethodInfo i = ([Assump i],[HsIdentI i],[i]) tcInstDecl' = tcInstOrClassDecl'' False tcClassDecl' = tcInstOrClassDecl'' True tcInstOrClassDecl'' :: (TypeId i,Printable i,Fresh i,Printable dsin, DefinedNames i dsin,HasBaseStruct din (Dinst i e p dsin), HasDef dsin din,HasId i p,ValueId i,HasId i e, TypeCheckDecls i dsin dsout, HasDef dsout dout,HasBaseStruct dout (Dinst i e2 p2 dsout)) => Bool -> SrcLoc -> [Pred i] -> Pred i -> dsin -> TI i (MethodInfo i,dsout) tcInstOrClassDecl'' isClass src ictx inst ds0 = do let cname@(HsCon cn) = definedType inst (k,Class super0 cvs0 fundeps0 ms0) <- env kenv cname let cl0 = appT (ty cname:map tyvar (tdom cvs0)) (cl,ms,super) <- return (cl0,ms0,super0) -- names are already unique --(cl,ms,super) <- allfresh (cl0,ms0,super0) --since `matches` requires disjoint vars supdns <- if isClass then return [] --else map dictName # freshlist (length super) else return $ map (superName cn) [1..length super] let ds = toDefs (map superMethod supdns) `appendDef` ds0 ims = definedValueNames ds0 -- names of implemented methods ns:>:_ = unzipTyped ms -- names of the methods of this class supms = zipTyped (map HsVar supdns:>:map mono super) case ims \\ ns of badms@(_:_) -> fail ("Extra bindings in "++dkind++" declaration: "++pp badms) [] -> errorContext (pp$"In"<+>dkind<+>inst) $ do kenv <- getKEnv s <- (inst `matches` cl) kenv let mts = (map.fmap) (addctx kenv (apply s ictx)) (apply s (ms++supms)) ds' <- --errmap (("Method signatures:\n"++pp mSigs++"\n")++) $ --errorContext ("Methods:\n"++pp ds) $ extendts [superVar:>:superType] $ tcInstDecls mts ds return ((ms,ims,supdns),ds') where dkind = if isClass then "class" else "instance" addctx kenv ictx (Forall vs' vs (ctx:=>t)) = Forall vs' (ivs++vs) ((ictx++ctx):=>t) where ivs0 = tv (ictx,ctx,t) \\ tdom vs ivs = [v:>:kind v|v<-ivs0] kind = maybe err fst . TiKEnv.lookup kenv . HsVar err = error "Bug in TiClassInst2: missing kind for a type variable" -- mSig m@(HsVar n) = do Forall vs (ctx:=>t) <- sch m -- return $ hsTypeSig src [n] (ictx++ctx) t superMethod n = hsSimpleBind src n (ident superVar) superVar = HsVar (prelVal "super") superType = forall' [av:>:kpred] ([a]:=>a) where a = tyvar av av = tvar 1 -------------------------------------------------------------------------------- {- hsInstDecl2 :: (Eq i,ValueId i, HasDef ds2 d2,AddDeclsType i ds2, HasId i e2,HasId i p2,HasAbstr i ds2, HasBaseStruct e2 (Einst i e2 p2 ds2), HasBaseStruct d2 (Dinst i e2 p2 ds2)) => i -> MethodInfo i -> SrcLoc -> [Pred i] -> Pred i -> ds2 -> TI i ds2 hsInstDecl2 n (ms,ims,supsels) src ctx inst ds = do self:dns <- map dictName # freshlist (1+length ctx) let selfbody = body self dns return $ abstract dns $ let ds' = addDeclsType ([],[HsVar self:>:mono inst]) $ consDef selfdef ds selfdef = hsSimpleBind src self selfbody in oneDef $ hsSimpleBind' src n (var self) ds' where c@(HsCon cn) = definedType inst dn = defaultName cn body self dns = hsRecConstr cn (superDefs++methodDefs) where methodDefs = map methodDef ms superDefs = zipWith methodDef' superns (map HsVar supsels) where superns = map (superName cn) [1..] methodDef (i@(HsVar v):>:_) = HsField v $ if i `elem` ims then apps (ident i:map var dns) else useDefault i methodDef' v i = HsField v $ apps (ident i:map var dns) useDefault i = ident i `hsApp` (var dn `hsApp` (var self)) apps = foldl1 hsApp -}
forste/haReFork
tools/base/TI/TiClassInst2.hs
bsd-3-clause
7,904
27
19
1,833
860
495
365
-1
-1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, PatternGuards #-} {- Implements a proof state, some primitive tactics for manipulating proofs, and some high level commands for introducing new theorems, evaluation/checking inside the proof system, etc. --} module Idris.Core.ProofState(ProofState(..), newProof, envAtFocus, goalAtFocus, Tactic(..), Goal(..), processTactic, nowElaboratingPS, doneElaboratingAppPS, doneElaboratingArgPS, dropGiven, keepGiven) where import Idris.Core.Typecheck import Idris.Core.Evaluate import Idris.Core.TT import Idris.Core.Unify import Control.Monad.State.Strict import Control.Applicative hiding (empty) import Control.Arrow ((***)) import Data.List import Debug.Trace import Util.Pretty hiding (fill) data ProofState = PS { thname :: Name, holes :: [Name], -- holes still to be solved usedns :: [Name], -- used names, don't use again nextname :: Int, -- name supply pterm :: Term, -- current proof term ptype :: Type, -- original goal dontunify :: [Name], -- explicitly given by programmer, leave it unified :: (Name, [(Name, Term)]), notunified :: [(Name, Term)], solved :: Maybe (Name, Term), problems :: Fails, injective :: [Name], deferred :: [Name], -- names we'll need to define instances :: [Name], -- instance arguments (for type classes) previous :: Maybe ProofState, -- for undo context :: Context, plog :: String, unifylog :: Bool, done :: Bool, while_elaborating :: [FailContext] } data Goal = GD { premises :: Env, goalType :: Binder Term } data Tactic = Attack | Claim Name Raw | Reorder Name | Exact Raw | Fill Raw | MatchFill Raw | PrepFill Name [Name] | CompleteFill | Regret | Solve | StartUnify Name | EndUnify | UnifyAll | Compute | ComputeLet Name | Simplify | HNF_Compute | EvalIn Raw | CheckIn Raw | Intro (Maybe Name) | IntroTy Raw (Maybe Name) | Forall Name Raw | LetBind Name Raw Raw | ExpandLet Name Term | Rewrite Raw | Induction Name | Equiv Raw | PatVar Name | PatBind Name | Focus Name | Defer Name | DeferType Name Raw [Name] | Instance Name | SetInjective Name | MoveLast Name | MatchProblems Bool | UnifyProblems | ProofState | Undo | QED deriving Show -- Some utilites on proof and tactic states instance Show ProofState where show (PS nm [] _ _ tm _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) = show nm ++ ": no more goals" show (PS nm (h:hs) _ _ tm _ _ _ _ _ _ _ i _ _ ctxt _ _ _ _) = let OK g = goal (Just h) tm wkenv = premises g in "Other goals: " ++ show hs ++ "\n" ++ showPs wkenv (reverse wkenv) ++ "\n" ++ "-------------------------------- (" ++ show nm ++ ") -------\n " ++ show h ++ " : " ++ showG wkenv (goalType g) ++ "\n" where showPs env [] = "" showPs env ((n, Let t v):bs) = " " ++ show n ++ " : " ++ showEnv env ({- normalise ctxt env -} t) ++ " = " ++ showEnv env ({- normalise ctxt env -} v) ++ "\n" ++ showPs env bs showPs env ((n, b):bs) = " " ++ show n ++ " : " ++ showEnv env ({- normalise ctxt env -} (binderTy b)) ++ "\n" ++ showPs env bs showG ps (Guess t v) = showEnv ps ({- normalise ctxt ps -} t) ++ " =?= " ++ showEnv ps v showG ps b = showEnv ps (binderTy b) instance Pretty ProofState OutputAnnotation where pretty (PS nm [] _ _ trm _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) = pretty nm <+> colon <+> text " no more goals." pretty p@(PS nm (h:hs) _ _ tm _ _ _ _ _ _ _ i _ _ ctxt _ _ _ _) = let OK g = goal (Just h) tm in let wkEnv = premises g in text "Other goals" <+> colon <+> pretty hs <+> prettyPs wkEnv (reverse wkEnv) <+> text "---------- " <+> text "Focussing on" <> colon <+> pretty nm <+> text " ----------" <+> pretty h <+> colon <+> prettyGoal wkEnv (goalType g) where prettyGoal ps (Guess t v) = prettyEnv ps t <+> text "=?=" <+> prettyEnv ps v prettyGoal ps b = prettyEnv ps $ binderTy b prettyPs env [] = empty prettyPs env ((n, Let t v):bs) = nest nestingSize (pretty n <+> colon <+> prettyEnv env t <+> text "=" <+> prettyEnv env v <+> nest nestingSize (prettyPs env bs)) prettyPs env ((n, b):bs) = nest nestingSize (pretty n <+> colon <+> prettyEnv env (binderTy b) <+> nest nestingSize (prettyPs env bs)) same Nothing n = True same (Just x) n = x == n hole (Hole _) = True hole (Guess _ _) = True hole _ = False holeName i = sMN i "hole" qshow :: Fails -> String qshow fs = show (map (\ (x, y, _, _, _, t) -> (t, x, y)) fs) match_unify' :: Context -> Env -> TT Name -> TT Name -> StateT TState TC [(Name, TT Name)] match_unify' ctxt env topx topy = do ps <- get let while = while_elaborating ps let dont = dontunify ps let inj = injective ps traceWhen (unifylog ps) ("Matching " ++ show (topx, topy) ++ " in " ++ show env ++ "\nHoles: " ++ show (holes ps) ++ "\n" ++ "\n" ++ show (pterm ps) ++ "\n\n" ) $ case match_unify ctxt env topx topy inj (holes ps) while of OK u -> do let (h, ns) = unified ps put (ps { unified = (h, u ++ ns) }) return u Error e -> do put (ps { problems = (topx, topy, env, e, while, Match) : problems ps }) return [] -- traceWhen (unifylog ps) -- ("Matched " ++ show (topx, topy) ++ " without " ++ show dont ++ -- "\nSolved: " ++ show u -- ++ "\nCurrent problems:\n" ++ qshow (problems ps) -- -- ++ show (pterm ps) -- ++ "\n----------") $ unify' :: Context -> Env -> TT Name -> TT Name -> StateT TState TC [(Name, TT Name)] unify' ctxt env topx topy = do ps <- get let while = while_elaborating ps let dont = dontunify ps let inj = injective ps (u, fails) <- traceWhen (unifylog ps) ("Trying " ++ show (topx, topy) ++ "\nNormalised " ++ show (normalise ctxt env topx, normalise ctxt env topy) ++ " in " ++ show env ++ "\nHoles: " ++ show (holes ps) ++ "\nInjective: " ++ show (injective ps) ++ "\n") $ lift $ unify ctxt env topx topy inj (holes ps) while let notu = filter (\ (n, t) -> case t of P _ _ _ -> False _ -> n `elem` dont) u traceWhen (unifylog ps) ("Unified " ++ show (topx, topy) ++ " without " ++ show dont ++ "\nSolved: " ++ show u ++ "\nNew problems: " ++ qshow fails ++ "\nNot unified:\n" ++ show (notunified ps) ++ "\nCurrent problems:\n" ++ qshow (problems ps) -- ++ show (pterm ps) ++ "\n----------") $ do ps <- get let (h, ns) = unified ps let (ns', probs') = updateProblems (context ps) (u ++ ns) (fails ++ problems ps) (injective ps) (holes ps) let (notu', probs_notu) = mergeNotunified env (notu ++ notunified ps) put (ps { problems = probs' ++ probs_notu, unified = (h, ns'), injective = updateInj u (injective ps), notunified = notu' }) return u where updateInj ((n, a) : us) inj | (P _ n' _, _) <- unApply a, n `elem` inj = updateInj us (n':inj) | (P _ n' _, _) <- unApply a, n' `elem` inj = updateInj us (n:inj) updateInj (_ : us) inj = updateInj us inj updateInj [] inj = inj nowElaboratingPS :: FC -> Name -> Name -> ProofState -> ProofState nowElaboratingPS fc f arg ps = ps { while_elaborating = FailContext fc f arg : while_elaborating ps } dropUntil :: (a -> Bool) -> [a] -> [a] dropUntil p [] = [] dropUntil p (x:xs) | p x = xs | otherwise = dropUntil p xs doneElaboratingAppPS :: Name -> ProofState -> ProofState doneElaboratingAppPS f ps = let while = while_elaborating ps while' = dropUntil (\ (FailContext _ f' _) -> f == f') while in ps { while_elaborating = while' } doneElaboratingArgPS :: Name -> Name -> ProofState -> ProofState doneElaboratingArgPS f x ps = let while = while_elaborating ps while' = dropUntil (\ (FailContext _ f' x') -> f == f' && x == x') while in ps { while_elaborating = while' } getName :: Monad m => String -> StateT TState m Name getName tag = do ps <- get let n = nextname ps put (ps { nextname = n+1 }) return $ sMN n tag action :: Monad m => (ProofState -> ProofState) -> StateT TState m () action a = do ps <- get put (a ps) query :: Monad m => (ProofState -> r) -> StateT TState m r query q = do ps <- get return $ q ps addLog :: Monad m => String -> StateT TState m () addLog str = action (\ps -> ps { plog = plog ps ++ str ++ "\n" }) newProof :: Name -> Context -> Type -> ProofState newProof n ctxt ty = let h = holeName 0 ty' = vToP ty in PS n [h] [] 1 (Bind h (Hole ty') (P Bound h ty')) ty [] (h, []) [] Nothing [] [] [] [] Nothing ctxt "" False False [] type TState = ProofState -- [TacticAction]) type RunTactic = Context -> Env -> Term -> StateT TState TC Term type Hole = Maybe Name -- Nothing = default hole, first in list in proof state envAtFocus :: ProofState -> TC Env envAtFocus ps | not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps) return (premises g) | otherwise = fail "No holes" goalAtFocus :: ProofState -> TC (Binder Type) goalAtFocus ps | not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps) return (goalType g) | otherwise = Error . Msg $ "No goal in " ++ show (holes ps) ++ show (pterm ps) goal :: Hole -> Term -> TC Goal goal h tm = g [] tm where g env (Bind n b@(Guess _ _) sc) | same h n = return $ GD env b | otherwise = gb env b `mplus` g ((n, b):env) sc g env (Bind n b sc) | hole b && same h n = return $ GD env b | otherwise = g ((n, b):env) sc `mplus` gb env b g env (App f a) = g env f `mplus` g env a g env t = fail "Can't find hole" gb env (Let t v) = g env v `mplus` g env t gb env (Guess t v) = g env v `mplus` g env t gb env t = g env (binderTy t) tactic :: Hole -> RunTactic -> StateT TState TC () tactic h f = do ps <- get (tm', _) <- atH (context ps) [] (pterm ps) ps <- get -- might have changed while processing put (ps { pterm = tm' }) where updated o = do o' <- o return (o', True) ulift2 c env op a b = do (b', u) <- atH c env b if u then return (op a b', True) else do (a', u) <- atH c env a return (op a' b', u) -- Search the things most likely to contain the binding first! atH :: Context -> Env -> Term -> StateT TState TC (Term, Bool) atH c env binder@(Bind n b@(Guess t v) sc) | same h n = updated (f c env binder) | otherwise = do -- binder first (b', u) <- ulift2 c env Guess t v if u then return (Bind n b' sc, True) else do (sc', u) <- atH c ((n, b) : env) sc return (Bind n b' sc', u) atH c env binder@(Bind n b sc) | hole b && same h n = updated (f c env binder) | otherwise -- scope first = do (sc', u) <- atH c ((n, b) : env) sc if u then return (Bind n b sc', True) else do (b', u) <- atHb c env b return (Bind n b' sc', u) atH c env (App f a) = ulift2 c env App f a atH c env t = return (t, False) atHb c env (Let t v) = ulift2 c env Let t v atHb c env (Guess t v) = ulift2 c env Guess t v atHb c env t = do (ty', u) <- atH c env (binderTy t) return (t { binderTy = ty' }, u) computeLet :: Context -> Name -> Term -> Term computeLet ctxt n tm = cl [] tm where cl env (Bind n' (Let t v) sc) | n' == n = let v' = normalise ctxt env v in Bind n' (Let t v') sc cl env (Bind n' b sc) = Bind n' (fmap (cl env) b) (cl ((n, b):env) sc) cl env (App f a) = App (cl env f) (cl env a) cl env t = t attack :: RunTactic attack ctxt env (Bind x (Hole t) sc) = do h <- getName "hole" action (\ps -> ps { holes = h : holes ps }) return $ Bind x (Guess t (newtm h)) sc where newtm h = Bind h (Hole t) (P Bound h t) attack ctxt env _ = fail "Not an attackable hole" claim :: Name -> Raw -> RunTactic claim n ty ctxt env t = do (tyv, tyt) <- lift $ check ctxt env ty lift $ isType ctxt env tyt action (\ps -> let (g:gs) = holes ps in ps { holes = g : n : gs } ) return $ Bind n (Hole tyv) t -- (weakenTm 1 t) reorder_claims :: RunTactic reorder_claims ctxt env t = -- trace (showSep "\n" (map show (scvs t))) $ let (bs, sc) = scvs t [] newbs = reverse (sortB (reverse bs)) in traceWhen (bs /= newbs) (show bs ++ "\n ==> \n" ++ show newbs) $ return (bindAll newbs sc) where scvs (Bind n b@(Hole _) sc) acc = scvs sc ((n, b):acc) scvs sc acc = (reverse acc, sc) sortB :: [(Name, Binder (TT Name))] -> [(Name, Binder (TT Name))] sortB [] = [] sortB (x:xs) | all (noOcc x) xs = x : sortB xs | otherwise = sortB (insertB x xs) insertB x [] = [x] insertB x (y:ys) | all (noOcc x) (y:ys) = x : y : ys | otherwise = y : insertB x ys noOcc (n, _) (_, Let t v) = noOccurrence n t && noOccurrence n v noOcc (n, _) (_, Guess t v) = noOccurrence n t && noOccurrence n v noOcc (n, _) (_, b) = noOccurrence n (binderTy b) focus :: Name -> RunTactic focus n ctxt env t = do action (\ps -> let hs = holes ps in if n `elem` hs then ps { holes = n : (hs \\ [n]) } else ps) ps <- get return t movelast :: Name -> RunTactic movelast n ctxt env t = do action (\ps -> let hs = holes ps in if n `elem` hs then ps { holes = (hs \\ [n]) ++ [n] } else ps) return t instanceArg :: Name -> RunTactic instanceArg n ctxt env (Bind x (Hole t) sc) = do action (\ps -> let hs = holes ps is = instances ps in ps { holes = (hs \\ [x]) ++ [x], instances = x:is }) return (Bind x (Hole t) sc) setinj :: Name -> RunTactic setinj n ctxt env (Bind x b sc) = do action (\ps -> let is = injective ps in ps { injective = n : is }) return (Bind x b sc) defer :: Name -> RunTactic defer n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' = do action (\ps -> let hs = holes ps in ps { holes = hs \\ [x] }) return (Bind n (GHole (length env) (mkTy (reverse env) t)) (mkApp (P Ref n ty) (map getP (reverse env)))) where mkTy [] t = t mkTy ((n,b) : bs) t = Bind n (Pi (binderTy b)) (mkTy bs t) getP (n, b) = P Bound n (binderTy b) -- as defer, but build the type and application explicitly deferType :: Name -> Raw -> [Name] -> RunTactic deferType n fty_in args ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' = do (fty, _) <- lift $ check ctxt env fty_in action (\ps -> let hs = holes ps ds = deferred ps in ps { holes = hs \\ [x], deferred = n : ds }) return (Bind n (GHole 0 fty) (mkApp (P Ref n ty) (map getP args))) where getP n = case lookup n env of Just b -> P Bound n (binderTy b) Nothing -> error ("deferType can't find " ++ show n) regret :: RunTactic regret ctxt env (Bind x (Hole t) sc) | noOccurrence x sc = do action (\ps -> let hs = holes ps in ps { holes = hs \\ [x] }) return sc regret ctxt env (Bind x (Hole t) _) = fail $ show x ++ " : " ++ show t ++ " is not solved..." exact :: Raw -> RunTactic exact guess ctxt env (Bind x (Hole ty) sc) = do (val, valty) <- lift $ check ctxt env guess lift $ converts ctxt env valty ty return $ Bind x (Guess ty val) sc exact _ _ _ _ = fail "Can't fill here." -- As exact, but attempts to solve other goals by unification fill :: Raw -> RunTactic fill guess ctxt env (Bind x (Hole ty) sc) = do (val, valty) <- lift $ check ctxt env guess -- let valtyn = normalise ctxt env valty -- let tyn = normalise ctxt env ty ns <- unify' ctxt env valty ty ps <- get let (uh, uns) = unified ps -- put (ps { unified = (uh, uns ++ ns) }) -- addLog (show (uh, uns ++ ns)) return $ Bind x (Guess ty val) sc fill _ _ _ _ = fail "Can't fill here." -- As fill, but attempts to solve other goals by matching match_fill :: Raw -> RunTactic match_fill guess ctxt env (Bind x (Hole ty) sc) = do (val, valty) <- lift $ check ctxt env guess -- let valtyn = normalise ctxt env valty -- let tyn = normalise ctxt env ty ns <- match_unify' ctxt env valty ty ps <- get let (uh, uns) = unified ps -- put (ps { unified = (uh, uns ++ ns) }) -- addLog (show (uh, uns ++ ns)) return $ Bind x (Guess ty val) sc match_fill _ _ _ _ = fail "Can't fill here." prep_fill :: Name -> [Name] -> RunTactic prep_fill f as ctxt env (Bind x (Hole ty) sc) = do let val = mkApp (P Ref f Erased) (map (\n -> P Ref n Erased) as) return $ Bind x (Guess ty val) sc prep_fill f as ctxt env t = fail $ "Can't prepare fill at " ++ show t complete_fill :: RunTactic complete_fill ctxt env (Bind x (Guess ty val) sc) = do let guess = forget val (val', valty) <- lift $ check ctxt env guess ns <- unify' ctxt env valty ty ps <- get let (uh, uns) = unified ps -- put (ps { unified = (uh, uns ++ ns) }) return $ Bind x (Guess ty val) sc complete_fill ctxt env t = fail $ "Can't complete fill at " ++ show t -- When solving something in the 'dont unify' set, we should check -- that the guess we are solving it with unifies with the thing unification -- found for it, if anything. solve :: RunTactic solve ctxt env (Bind x (Guess ty val) sc) = do ps <- get let (uh, uns) = unified ps case lookup x (notunified ps) of Just tm -> -- trace ("NEED MATCH: " ++ show (tm, val)) $ match_unify' ctxt env tm val _ -> return [] action (\ps -> ps { holes = holes ps \\ [x], solved = Just (x, val), notunified = updateNotunified [(x,val)] (notunified ps), instances = instances ps \\ [x] }) let tm' = subst x val sc in return tm' solve _ _ h@(Bind x t sc) = do ps <- get case findType x sc of Just t -> lift $ tfail (CantInferType (show t)) _ -> fail $ "Not a guess " ++ show h ++ "\n" ++ show (holes ps, pterm ps) where findType x (Bind n (Let t v) sc) = findType x v `mplus` findType x sc findType x (Bind n t sc) | P _ x' _ <- binderTy t, x == x' = Just n | otherwise = findType x sc findType x _ = Nothing introTy :: Raw -> Maybe Name -> RunTactic introTy ty mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do let n = case mn of Just name -> name Nothing -> x let t' = case t of x@(Bind y (Pi s) _) -> x _ -> hnf ctxt env t (tyv, tyt) <- lift $ check ctxt env ty -- ns <- lift $ unify ctxt env tyv t' case t' of Bind y (Pi s) t -> let t' = subst y (P Bound n s) t in do ns <- unify' ctxt env s tyv ps <- get let (uh, uns) = unified ps -- put (ps { unified = (uh, uns ++ ns) }) return $ Bind n (Lam tyv) (Bind x (Hole t') (P Bound x t')) _ -> lift $ tfail $ CantIntroduce t' introTy ty n ctxt env _ = fail "Can't introduce here." intro :: Maybe Name -> RunTactic intro mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do let n = case mn of Just name -> name Nothing -> x let t' = case t of x@(Bind y (Pi s) _) -> x _ -> hnf ctxt env t case t' of Bind y (Pi s) t -> -- trace ("in type " ++ show t') $ let t' = subst y (P Bound n s) t in return $ Bind n (Lam s) (Bind x (Hole t') (P Bound x t')) _ -> lift $ tfail $ CantIntroduce t' intro n ctxt env _ = fail "Can't introduce here." forall :: Name -> Raw -> RunTactic forall n ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do (tyv, tyt) <- lift $ check ctxt env ty unify' ctxt env tyt (TType (UVar 0)) unify' ctxt env t (TType (UVar 0)) return $ Bind n (Pi tyv) (Bind x (Hole t) (P Bound x t)) forall n ty ctxt env _ = fail "Can't pi bind here" patvar :: Name -> RunTactic patvar n ctxt env (Bind x (Hole t) sc) = do action (\ps -> ps { holes = holes ps \\ [x], notunified = updateNotunified [(x,P Bound n t)] (notunified ps), injective = addInj n x (injective ps) }) return $ Bind n (PVar t) (subst x (P Bound n t) sc) where addInj n x ps | x `elem` ps = n : ps | otherwise = ps patvar n ctxt env tm = fail $ "Can't add pattern var at " ++ show tm letbind :: Name -> Raw -> Raw -> RunTactic letbind n ty val ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do (tyv, tyt) <- lift $ check ctxt env ty (valv, valt) <- lift $ check ctxt env val lift $ isType ctxt env tyt return $ Bind n (Let tyv valv) (Bind x (Hole t) (P Bound x t)) letbind n ty val ctxt env _ = fail "Can't let bind here" expandLet :: Name -> Term -> RunTactic expandLet n v ctxt env tm = return $ subst n v tm rewrite :: Raw -> RunTactic rewrite tm ctxt env (Bind x (Hole t) xp@(P _ x' _)) | x == x' = do (tmv, tmt) <- lift $ check ctxt env tm let tmt' = normalise ctxt env tmt case unApply tmt' of (P _ (UN q) _, [lt,rt,l,r]) | q == txt "=" -> do let p = Bind rname (Lam lt) (mkP (P Bound rname lt) r l t) let newt = mkP l r l t let sc = forget $ (Bind x (Hole newt) (mkApp (P Ref (sUN "replace") (TType (UVal 0))) [lt, l, r, p, tmv, xp])) (scv, sct) <- lift $ check ctxt env sc return scv _ -> lift $ tfail (NotEquality tmv tmt') where rname = sMN 0 "replaced" rewrite _ _ _ _ = fail "Can't rewrite here" -- To make the P for rewrite, replace syntactic occurrences of l in ty with -- an x, and put \x : lt in front mkP :: TT Name -> TT Name -> TT Name -> TT Name -> TT Name mkP lt l r ty | l == ty = lt mkP lt l r (App f a) = let f' = if (r /= f) then mkP lt l r f else f a' = if (r /= a) then mkP lt l r a else a in App f' a' mkP lt l r (Bind n b sc) = let b' = mkPB b sc' = if (r /= sc) then mkP lt l r sc else sc in Bind n b' sc' where mkPB (Let t v) = let t' = if (r /= t) then mkP lt l r t else t v' = if (r /= v) then mkP lt l r v else v in Let t' v' mkPB b = let ty = binderTy b ty' = if (r /= ty) then mkP lt l r ty else ty in b { binderTy = ty' } mkP lt l r x = x induction :: Name -> RunTactic induction nm ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do (tmv, tmt) <- lift $ check ctxt env (Var nm) let tmt' = normalise ctxt env tmt case unApply tmt' of (P _ tnm _, tyargs) -> do case lookupTy (SN (ElimN tnm)) ctxt of [elimTy] -> do param_pos <- case lookupMetaInformation tnm ctxt of [DataMI param_pos] -> return param_pos m | length tyargs > 0 -> fail $ "Invalid meta information for " ++ show tnm ++ " where the metainformation is " ++ show m ++ " and definition is" ++ show (lookupDef tnm ctxt) _ -> return [] let (params, indicies) = splitTyArgs param_pos tyargs let args = getArgTys elimTy let pmargs = take (length params) args let args' = drop (length params) args let propTy = head args' let restargs = init $ tail args' let consargs = take (length restargs - length indicies) $ restargs let indxargs = drop (length restargs - length indicies) $ restargs let scr = last $ tail args' let indxnames = makeIndexNames indicies prop <- replaceIndicies indxnames indicies $ Bind nm (Lam tmt') t consargs' <- query (\ps -> map (flip (uniqueNameCtxt (context ps)) (holes ps ++ allTTNames (pterm ps)) *** uniqueBindersCtxt (context ps) (holes ps ++ allTTNames (pterm ps))) consargs) let res = flip (foldr substV) params $ (substV prop $ bindConsArgs consargs' (mkApp (P Ref (SN (ElimN tnm)) (TType (UVal 0))) (params ++ [prop] ++ map makeConsArg consargs' ++ indicies ++ [tmv]))) action (\ps -> ps {holes = holes ps \\ [x]}) mapM_ addConsHole (reverse consargs') let res' = forget $ res (scv, sct) <- lift $ check ctxt env res' let scv' = specialise ctxt env [] scv return scv' [] -> fail $ "Induction needs an eliminator for " ++ show tnm xs -> fail $ "Multiple definitions found when searching for the eliminator of " ++ show tnm _ -> fail "Unkown type for induction" where scname = sMN 0 "scarg" makeConsArg (nm, ty) = P Bound nm ty bindConsArgs ((nm, ty):args) v = Bind nm (Hole ty) $ bindConsArgs args v bindConsArgs [] v = v addConsHole (nm, ty) = action (\ps -> ps { holes = nm : holes ps }) splitTyArgs param_pos tyargs = let (params, indicies) = partition (flip elem param_pos . fst) . zip [0..] $ tyargs in (map snd params, map snd indicies) makeIndexNames = foldr (\_ nms -> (uniqueNameCtxt ctxt (sMN 0 "idx") nms):nms) [] replaceIndicies idnms idxs prop = foldM (\t (idnm, idx) -> do (idxv, idxt) <- lift $ check ctxt env (forget idx) let var = P Bound idnm idxt return $ Bind idnm (Lam idxt) (mkP var idxv var t)) prop $ zip idnms idxs induction tm ctxt env _ = do fail "Can't do induction here" equiv :: Raw -> RunTactic equiv tm ctxt env (Bind x (Hole t) sc) = do (tmv, tmt) <- lift $ check ctxt env tm lift $ converts ctxt env tmv t return $ Bind x (Hole tmv) sc equiv tm ctxt env _ = fail "Can't equiv here" patbind :: Name -> RunTactic patbind n ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do let t' = case t of x@(Bind y (PVTy s) t) -> x _ -> hnf ctxt env t case t' of Bind y (PVTy s) t -> let t' = subst y (P Bound n s) t in return $ Bind n (PVar s) (Bind x (Hole t') (P Bound x t')) _ -> fail "Nothing to pattern bind" patbind n ctxt env _ = fail "Can't pattern bind here" compute :: RunTactic compute ctxt env (Bind x (Hole ty) sc) = do return $ Bind x (Hole (normalise ctxt env ty)) sc compute ctxt env t = return t hnf_compute :: RunTactic hnf_compute ctxt env (Bind x (Hole ty) sc) = do let ty' = hnf ctxt env ty in -- trace ("HNF " ++ show (ty, ty')) $ return $ Bind x (Hole ty') sc hnf_compute ctxt env t = return t -- reduce let bindings only simplify :: RunTactic simplify ctxt env (Bind x (Hole ty) sc) = do return $ Bind x (Hole (specialise ctxt env [] ty)) sc simplify ctxt env t = return t check_in :: Raw -> RunTactic check_in t ctxt env tm = do (val, valty) <- lift $ check ctxt env t addLog (showEnv env val ++ " : " ++ showEnv env valty) return tm eval_in :: Raw -> RunTactic eval_in t ctxt env tm = do (val, valty) <- lift $ check ctxt env t let val' = normalise ctxt env val let valty' = normalise ctxt env valty addLog (showEnv env val ++ " : " ++ showEnv env valty ++ -- " in " ++ show env ++ " ==>\n " ++ showEnv env val' ++ " : " ++ showEnv env valty') return tm start_unify :: Name -> RunTactic start_unify n ctxt env tm = do -- action (\ps -> ps { unified = (n, []) }) return tm tmap f (a, b, c) = (f a, b, c) solve_unified :: RunTactic solve_unified ctxt env tm = do ps <- get let (_, ns) = unified ps let unify = dropGiven (dontunify ps) ns (holes ps) action (\ps -> ps { holes = holes ps \\ map fst unify }) action (\ps -> ps { pterm = updateSolved unify (pterm ps) }) return (updateSolved unify tm) dropGiven du [] hs = [] dropGiven du ((n, P Bound t ty) : us) hs | n `elem` du && not (t `elem` du) && n `elem` hs && t `elem` hs = (t, P Bound n ty) : dropGiven du us hs dropGiven du (u@(n, _) : us) hs | n `elem` du = dropGiven du us hs -- dropGiven du (u@(_, P a n ty) : us) | n `elem` du = dropGiven du us dropGiven du (u : us) hs = u : dropGiven du us hs keepGiven du [] hs = [] keepGiven du ((n, P Bound t ty) : us) hs | n `elem` du && not (t `elem` du) && n `elem` hs && t `elem` hs = keepGiven du us hs keepGiven du (u@(n, _) : us) hs | n `elem` du = u : keepGiven du us hs keepGiven du (u : us) hs = keepGiven du us hs updateSolved :: [(Name, Term)] -> Term -> Term updateSolved xs x = updateSolved' xs x updateSolved' [] x = x updateSolved' xs (Bind n (Hole ty) t) | Just v <- lookup n xs = case xs of [_] -> psubst n v t _ -> psubst n v (updateSolved' xs t) updateSolved' xs (Bind n b t) | otherwise = Bind n (fmap (updateSolved' xs) b) (updateSolved' xs t) updateSolved' xs (App f a) = App (updateSolved' xs f) (updateSolved' xs a) updateSolved' xs (P _ n@(MN _ _) _) | Just v <- lookup n xs = v updateSolved' xs t = t updateEnv [] e = e updateEnv ns [] = [] updateEnv ns ((n, b) : env) = (n, fmap (updateSolved ns) b) : updateEnv ns env updateError [] err = err updateError ns (CantUnify b l r e xs sc) = CantUnify b (updateSolved ns l) (updateSolved ns r) (updateError ns e) xs sc updateError ns e = e solveInProblems x val [] = [] solveInProblems x val ((l, r, env, err) : ps) = ((psubst x val l, psubst x val r, updateEnv [(x, val)] env, err) : solveInProblems x val ps) mergeNotunified :: Env -> [(Name, Term)] -> ([(Name, Term)], Fails) mergeNotunified env ns = mnu ns [] [] where mnu [] ns_acc ps_acc = (reverse ns_acc, reverse ps_acc) mnu ((n, t):ns) ns_acc ps_acc | Just t' <- lookup n ns, t /= t' = mnu ns ((n,t') : ns_acc) ((t,t',env,Msg "", [],Unify) : ps_acc) | otherwise = mnu ns ((n,t) : ns_acc) ps_acc updateNotunified [] nu = nu updateNotunified ns nu = up nu where up [] = [] up ((n, t) : nus) = let t' = updateSolved ns t in ((n, t') : up nus) updateProblems :: Context -> [(Name, TT Name)] -> Fails -> [Name] -> [Name] -> ([(Name, TT Name)], Fails) updateProblems ctxt [] ps inj holes = ([], ps) updateProblems ctxt ns ps inj holes = up ns ps where up ns [] = (ns, []) up ns ((x, y, env, err, while, um) : ps) = let x' = updateSolved ns x y' = updateSolved ns y err' = updateError ns err env' = updateEnv ns env in -- trace ("Updating " ++ show (x',y')) $ case unify ctxt env' x' y' inj holes while of OK (v, []) -> -- trace ("Added " ++ show v ++ " from " ++ show (x', y')) $ up (ns ++ v) ps e -> -- trace ("Failed " ++ show e) $ let (ns', ps') = up ns ps in (ns', (x',y',env',err', while, um) : ps') -- attempt to solve remaining problems with match_unify matchProblems all ns ctxt ps inj holes = up ns ps where up ns [] = (ns, []) up ns ((x, y, env, err, while, um) : ps) | all || um == Match = let x' = updateSolved ns x y' = updateSolved ns y err' = updateError ns err env' = updateEnv ns env in case match_unify ctxt env' x' y' inj holes while of OK v -> -- trace ("Added " ++ show v ++ " from " ++ show (x', y')) $ up (ns ++ v) ps _ -> let (ns', ps') = up ns ps in (ns', (x', y', env', err', while, um) : ps') up ns (p : ps) = let (ns', ps') = up ns ps in (ns', p : ps') processTactic :: Tactic -> ProofState -> TC (ProofState, String) processTactic QED ps = case holes ps of [] -> do let tm = {- normalise (context ps) [] -} (pterm ps) (tm', ty', _) <- recheck (context ps) [] (forget tm) tm return (ps { done = True, pterm = tm' }, "Proof complete: " ++ showEnv [] tm') _ -> fail "Still holes to fill." processTactic ProofState ps = return (ps, showEnv [] (pterm ps)) processTactic Undo ps = case previous ps of Nothing -> Error . Msg $ "Nothing to undo." Just pold -> return (pold, "") processTactic EndUnify ps = let (h, ns_in) = unified ps ns = dropGiven (dontunify ps) ns_in (holes ps) ns' = map (\ (n, t) -> (n, updateSolved ns t)) ns (ns'', probs') = updateProblems (context ps) ns' (problems ps) (injective ps) (holes ps) tm' = updateSolved ns'' (pterm ps) in return (ps { pterm = tm', unified = (h, []), problems = probs', notunified = updateNotunified ns'' (notunified ps), holes = holes ps \\ map fst ns'' }, "") processTactic UnifyAll ps = let tm' = updateSolved (notunified ps) (pterm ps) in return (ps { pterm = tm', notunified = [], holes = holes ps \\ map fst (notunified ps) }, "") processTactic (Reorder n) ps = do ps' <- execStateT (tactic (Just n) reorder_claims) ps return (ps' { previous = Just ps, plog = "" }, plog ps') processTactic (ComputeLet n) ps = return (ps { pterm = computeLet (context ps) n (pterm ps) }, "") processTactic UnifyProblems ps = let (ns', probs') = updateProblems (context ps) [] (problems ps) (injective ps) (holes ps) pterm' = updateSolved ns' (pterm ps) in return (ps { pterm = pterm', solved = Nothing, problems = probs', previous = Just ps, plog = "", notunified = updateNotunified ns' (notunified ps), holes = holes ps \\ (map fst ns') }, plog ps) processTactic (MatchProblems all) ps = let (ns', probs') = matchProblems all [] (context ps) (problems ps) (injective ps) (holes ps) (ns'', probs'') = matchProblems all ns' (context ps) probs' (injective ps) (holes ps) pterm' = updateSolved ns'' (pterm ps) in return (ps { pterm = pterm', solved = Nothing, problems = probs'', previous = Just ps, plog = "", notunified = updateNotunified ns'' (notunified ps), holes = holes ps \\ (map fst ns'') }, plog ps) processTactic t ps = case holes ps of [] -> fail "Nothing to fill in." (h:_) -> do ps' <- execStateT (process t h) ps let (ns', probs') = case solved ps' of Just s -> traceWhen (unifylog ps') ("SOLVED " ++ show s) $ updateProblems (context ps') [s] (problems ps') (injective ps') (holes ps') _ -> ([], problems ps') -- rechecking problems may find more solutions, so -- apply them here let pterm'' = updateSolved ns' (pterm ps') return (ps' { pterm = pterm'', solved = Nothing, problems = probs', notunified = updateNotunified ns' (notunified ps'), previous = Just ps, plog = "", holes = holes ps' \\ (map fst ns')}, plog ps') process :: Tactic -> Name -> StateT TState TC () process EndUnify _ = do ps <- get let (h, _) = unified ps tactic (Just h) solve_unified process t h = tactic (Just h) (mktac t) where mktac Attack = attack mktac (Claim n r) = claim n r mktac (Exact r) = exact r mktac (Fill r) = fill r mktac (MatchFill r) = match_fill r mktac (PrepFill n ns) = prep_fill n ns mktac CompleteFill = complete_fill mktac Regret = regret mktac Solve = solve mktac (StartUnify n) = start_unify n mktac Compute = compute mktac Simplify = Idris.Core.ProofState.simplify mktac HNF_Compute = hnf_compute mktac (Intro n) = intro n mktac (IntroTy ty n) = introTy ty n mktac (Forall n t) = forall n t mktac (LetBind n t v) = letbind n t v mktac (ExpandLet n b) = expandLet n b mktac (Rewrite t) = rewrite t mktac (Induction t) = induction t mktac (Equiv t) = equiv t mktac (PatVar n) = patvar n mktac (PatBind n) = patbind n mktac (CheckIn r) = check_in r mktac (EvalIn r) = eval_in r mktac (Focus n) = focus n mktac (Defer n) = defer n mktac (DeferType n t a) = deferType n t a mktac (Instance n) = instanceArg n mktac (SetInjective n) = setinj n mktac (MoveLast n) = movelast n
DanielWaterworth/Idris-dev
src/Idris/Core/ProofState.hs
bsd-3-clause
42,302
0
32
17,208
16,244
8,162
8,082
843
31
module Code02 where import Data.List (sort) -- Sample Data sample :: String sample = "GENERATING" -- Specification msc0 :: Ord a => [a] -> Int msc0 xs = maximum [scount z zs | z:zs <- tails xs] scount :: Ord a => a -> [a] -> Int scount x xs = length (filter (x <) xs) tails :: [a] -> [[a]] tails [] = [] tails xxs@(_:xs) = xxs : tails xs -- table msc1 :: Ord a => [a] -> Int msc1 = maximum . map snd . table1 table1 :: Ord a => [a] -> [(a, Int)] table1 = tableSpec1 tableSpec1 :: Ord a => [a] -> [(a, Int)] tableSpec1 xs = [(z,scount z zs) | z:zs <- tails xs] -- join join2 :: Ord a => [(a, Int)] -> [(a, Int)] -> [(a, Int)] join2 txs tys = [(z,c+tcount2 z tys)|(z,c) <- txs] ++ tys tcount2 :: Ord a => a -> [(a, b)] -> Int tcount2 z tys = scount z (map fst tys) tableSpec2 :: Ord a => [a] -> [(a, Int)] tableSpec2 = tableSpec1 -- sorted table tableSpec3 :: Ord a => [a] -> [(a,Int)] tableSpec3 xs = sort [(z,scount z zs) | z:zs <- tails xs] table3 :: Ord a => [a] -> [(a,Int)] table3 [x] = [(x,0)] table3 xs = join3 (table3 ys) (table3 zs) where m = length xs `div` 2 (ys,zs) = splitAt m xs join3 :: Ord a => [(a, Int)] -> [(a, Int)] -> [(a, Int)] join3 txs tys = [(x,c + tcount3 x tys) | (x,c) <- txs] /\/\ tys where [] /\/\ tbs = tbs tas /\/\ [] = tas tas@(a:as) /\/\ tbs@(b:bs) | fst a < fst b = a : (as /\/\ tbs) | otherwise = b : (tas /\/\ bs) tcount3 :: Ord a => a -> [(a,Int)] -> Int tcount3 z tys = length (dropWhile ((z >=) . fst) tys) -- merge and count tableSpec4 :: Ord a => [a] -> [(a,Int)] tableSpec4 = tableSpec3 table4 :: Ord a => [a] -> [(a,Int)] table4 [x] = [(x,0)] table4 xs = join4 (table4 ys) (table4 zs) where m = length xs `div` 2 (ys,zs) = splitAt m xs join4 :: Ord a => [(a, Int)] -> [(a, Int)] -> [(a, Int)] join4 [] tys = tys join4 txs [] = txs join4 txs@((x,c):txs') tys@((y,d):tys') | x < y = (x,c + length tys) : join4 txs' tys | otherwise = (y,d) : join4 txs tys' -- Final implementation msc :: Ord a => [a] -> Int msc = maximum . map snd . table table :: Ord a => [a] -> [(a, Int)] table [x] = [(x,0)] table xs = join (m-n) (table ys) (table zs) where m = length xs n = m `div` 2 (ys,zs) = splitAt n xs join :: Ord a => Int -> [(a, Int)] -> [(a, Int)] -> [(a, Int)] join 0 txs [] = txs join _ [] tys = tys join n txs@((x,c):txs') tys@((y,d):tys') | x < y = (x,c+n) : join n txs' tys | x >= y = (y,d) : join (n-1) txs tys'
sampou-org/pfad
Code/Code02.hs
bsd-3-clause
2,799
0
11
964
1,586
863
723
66
3
-- | module Graphics.RecordGL ( module Graphics.RecordGL.Vertex , module Graphics.RecordGL.Uniforms) where import Graphics.RecordGL.Uniforms import Graphics.RecordGL.Vertex
rabipelais/record-gl
src/Graphics/RecordGL.hs
bsd-3-clause
220
0
5
62
35
24
11
4
0
module Common ( module Control.Applicative , module Control.Arrow , module Control.Monad , module Text.ParserCombinators.Parsec ) where import Control.Applicative hiding ((<|>), many, optional, Const) import Control.Arrow import Control.Monad import Text.ParserCombinators.Parsec hiding (State, parse, choice)
facebookarchive/lex-pass
src/Common.hs
bsd-3-clause
337
0
5
60
81
54
27
10
0
module Ottar.Transform.Ottar (ottar2Ottar, fmtOttar, extOttar) where import Text.PrettyPrint.Leijen as PP import Ottar.Model fmtOttar = "ottar" extOttar = ".ottar" ottar2Ottar :: SecComms -> Doc ottar2Ottar prtcl = vsep $ map prettyStep prtcl prettyStep :: SecComm -> Doc prettyStep (SecComm i f t ms) = text f <+> text "->" <+> text t <+> colon <+> prettyAsciiMSGs ms prettyAsciiMSGs :: Messages -> Doc prettyAsciiMSGs ms = hsep $ punctuate comma $ map prettyAsciiMSG ms prettyAsciiMSG :: Message -> Doc prettyAsciiMSG (Identity i) = prettyAtom "ID" i prettyAsciiMSG (Nonce n) = prettyAtom "N" n prettyAsciiMSG (Key v t o) = prettyAtom (show t) o prettyAsciiMSG (Op _ k ms) = prettyOps k ms prettyAsciiMSG (Message c) = dquotes $ text c -- ------------------------------------------------------- [ Pretty Operations ] prettyOps :: Message -> Messages -> Doc prettyOps (Key v t o) ms = braces (prettyAsciiMSGs ms) <> text "_" <> prettyAtom (show t) o -- -------------------------------------------------------------------- [ Misc ] prettyAtom :: String -> String -> Doc prettyAtom k v = text k <> parens (text v)
jfdm/ottar
src/Ottar/Transform/Ottar.hs
bsd-3-clause
1,309
0
9
367
382
193
189
27
1
import Network import qualified Network.Websocket as WS config = WS.Config { WS.configPort = 9876, WS.configOrigins = Nothing, WS.configDomains = Nothing, WS.configOnOpen = onOpen, WS.configOnMessage = onMessage, WS.configOnClose = onClose } main = withSocketsDo $ WS.startServer config onOpen ws = do putStrLn "Connection opened" onMessage ws msg = do putStrLn $ "Received message: " ++ msg WS.send ws msg onClose ws = do putStrLn "Connection closed"
michaelmelanson/network-websocket
examples/echo.hs
bsd-3-clause
565
0
8
178
142
76
66
17
1
module Main where import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.Framework.Providers.HUnit import ParserProperties(prop_parse_identifier) import ParserTests(test_parse_empty_main_class) tests :: [Test] tests = [testGroup "Parser tests" [testProperty "prop_parse_identifier" prop_parse_identifier, testCase "test_parse_empty_main_class" test_parse_empty_main_class ] ] main :: IO() main = defaultMain tests
helino/espresso
test/espresso/Test.hs
bsd-3-clause
486
0
8
85
94
55
39
12
1
module ArithSpec (spec) where import Test.Hspec import Control.Funky import qualified Control.Funky.Compiler.Instances as C import Data.Tensor.TypeLevel hiding ((!)) imm :: a -> Thunk a imm x = Thunk x Vec una :: (a -> a) -> Int -> Thunk a una f x = Thunk f $ vec1 x bin :: (a -> a -> a) -> Int -> Int -> Thunk a bin f x y = Thunk f $ vec2 y x machine1 :: Executable Double machine1 = fromList [ imm 6 , imm 7 , bin (*) 0 1] machine2 :: Executable Int machine2 = fromList [ imm 6 , imm 7 , bin (-) (-1) 1 , bin (+) 0 500 , bin (*) 2 3 , una negate 4] machine3 :: Program Double machine3 = fromList [ Imm 6 , Imm 7 , Nop , Add (vec2 0 1)] forceCompile :: Show a => [PartialCompiler a] -> Program a -> Executable a forceCompile pcs prog = case runCompilers pcs prog of Right ret -> ret Left msg -> error msg spec :: Spec spec = do describe "Funky Machine" $ do it "gives answer to everything" $ do let ret = toList $ run machine1 (ret !! 2) `shouldBe` 42 it "gives the default where out of index" $ do (toList $ run machine2) `shouldBe` [6,7,-7,6,-42,42] describe "Funky Compiler" $ do it "should compile and execute" $ do (toList $ run $ forceCompile [C.num, C.imm, C.def] machine3) `shouldBe` [6,7,0,13 :: Double]
nushio3/funky
test/ArithSpec.hs
bsd-3-clause
1,356
0
18
387
588
307
281
46
2
{-# LANGUAGE PackageImports #-} import Control.Monad import "monads-tf" Control.Monad.Trans import Data.Pipe import Data.Pipe.List import System.Environment import qualified Data.ByteString as BS import XmlCreate main :: IO () main = do fn : _ <- getArgs cnt <- BS.readFile fn mu <- runPipe $ fromList [cnt] =$= xmlEvent =$= filterJust -- =$= (xmlBegin >>= xmlNode) =$= xmlPipe =$= puts case mu of Just _ -> return () _ -> error "bad in main" xmlPipe :: Monad m => Pipe XmlEvent XmlNode m () xmlPipe = do c <- xmlBegin >>= xmlNode when c $ xmlPipe puts :: Show a => (Monad m, MonadIO m) => Pipe a () m () puts = await >>= maybe (return ()) (\bs -> liftIO (print bs) >> puts) filterJust :: Monad m => Pipe (Maybe a) a m () filterJust = do mmx <- await case mmx of Just (Just x) -> yield x >> filterJust Just _ -> error "filterJust" -- filterJust _ -> return ()
YoshikuniJujo/forest
subprojects/xml-pipe/test.hs
bsd-3-clause
894
0
14
195
369
184
185
-1
-1
{-# LANGUAGE RecursiveDo #-} {-# LANGUAGE FlexibleContexts #-} module Main where import Diagrams.Prelude as D import Diagrams.Backend.Reflex as DR import Reflex as R import Reflex.Dom as R main :: IO () main = mainWidget app app :: MonadWidget t m => m () app = mdo -- svgDyn :: Dynamic t (m (DiaEv Any)) let svgDyn = fmap (reflexDia $ def & sizeSpec .~ dims2D 500 1000) diaDyn -- pos :: Event (V2 Double) pos <- switchPromptly never <$> fmap diaMousemovePos =<< dyn svgDyn -- diaDyn :: Dynamic (Diagram B) diaDyn <- holdDyn (mkDia . p2 $ (0, -1000)) (mkDia <$> pos) return () -- TODO generalize and move into diagrams-lib constrain :: (InSpace v n a, Enveloped a, HasBasis v, Num n, Ord (v n)) => a -> Point v n -> Point v n constrain a p = maybe p c $ getCorners box where c (l,h) = max l (min h p) box = boundingBox a mkDia :: P2 Double -> Diagram B mkDia p = arr <> c <> back where arr = arrowBetween' (def & arrowHead .~ dart & arrowTail .~ quill ) origin p' c = moveTo p' $ D.text "Hello" # fc green p' = constrain back p back = vcat [ square 1000 # fc cyan, square 1000 # fc yellow ]
diagrams/diagrams-reflex
example/src/Follow.hs
bsd-3-clause
1,144
0
14
273
440
225
215
28
1
{-# LANGUAGE DeriveDataTypeable #-} module Main ( main ) where import Control.Concurrent (threadDelay) import Control.Monad (forM_, when) import Data.Word (Word8) import Foreign (Ptr) import Foreign.Ptr (plusPtr) import Foreign.Storable (peek) import GHC.IO.Exception (IOErrorType(Interrupted), ioe_type) import Graphics.V4L2 import System.Console.CmdArgs import System.Directory (renameFile) import System.Exit (exitFailure) import System.IO.Error (tryIOError) import System.IO (hPutStrLn, stderr) import qualified Codec.Picture as CP import qualified Codec.Picture.Png as Png import qualified Data.Vector.Storable as SV data CmdLineOpts = CmdLineOpts { videoDevice:: FilePath , outPng:: FilePath , delaySeconds :: Int , verbose:: Bool } deriving (Show, Data, Typeable) cmdLineOpts :: CmdLineOpts cmdLineOpts = CmdLineOpts { videoDevice = "/dev/video0" &= help "/dev/video0" , outPng = "frame.png" &= help "frame.png" , delaySeconds = 5 &= help "5 :: delay (in seconds) before grabbing next frame" , verbose = False &= explicit &= name "verbose" &= help "run in a verbose mode" } &= program "v4l2-webcam-frame-grabber" &= help "Grabs a video frame and saves it to a png file every delayseconds seconds" main :: IO () main = do opts <- cmdArgs cmdLineOpts :: IO CmdLineOpts let delayMicros = (delaySeconds opts) * 1000000 forM_ [(0 :: Int) ..] $ \i -> do grabFrame opts i threadDelay delayMicros grabFrame :: CmdLineOpts -> Int -> IO () grabFrame opts i = do let tmpFile = (outPng opts) ++ ".tmp" e <- tryIOError $ withDevice (videoDevice opts) $ \d -> do f <- setFormat d Capture . (\f->f{ imagePixelFormat = PixelRGB24 }) =<< getFormat d Capture checkFormat f when (verbose opts) $ do info $ "Frame number (" ++ (show i) ++ ") size: " ++ show (imageWidth f) ++ "x" ++ show (imageHeight f) ++ " pixels (" ++ show (imageSize f) ++ " bytes)" withFrame d f $ \p n -> do if n == imageSize f then do img <- toImage (imageWidth f) (imageHeight f) p Png.writePng tmpFile img renameFile tmpFile (outPng opts) else warn $ "Incomplete frame (" ++ show n ++ " bytes, expected " ++ show (imageSize f) ++ " bytes)" case e of Left f | ioe_type f == Interrupted -> return () | otherwise -> ioError f Right () -> return () toImage :: Int -> Int -> Ptr Word8 -> IO (CP.Image CP.PixelRGB8) toImage w h p = do pixels <- SV.generateM (w*h*3) (peek . plusPtr p) return $ CP.Image w h pixels checkFormat :: ImageFormat -> IO () checkFormat f = do when (imagePixelFormat f /= PixelRGB24) $ err "could not set RGB24 pixel format" when (imageBytesPerLine f /= imageWidth f * 3) $ err "cannot handle extra padding" when (imageSize f /= imageBytesPerLine f * imageHeight f) $ err "cannot handle image size" err :: String -> IO a err msg = (hPutStrLn stderr $ "**ERROR: [v4l2-webcam-frame-grabber] " ++ msg) >> exitFailure warn :: String -> IO () warn msg = hPutStrLn stderr $ "++ WARN: [v4l2-webcam-frame-grabber] " ++ msg info :: String -> IO () info msg = hPutStrLn stderr $ " INFO: [v4l2-webcam-frame-grabber] " ++ msg
andreyk0/v4l2-webcam-frame-grabber
v4l2-webcam-frame-grabber/Main.hs
bsd-3-clause
3,279
0
24
775
1,096
555
541
75
3
------------------------------------------------------------------------------ -- | Holds D3 level primitives. -- TODO break me up as necessary! ------------------------------------------------------------------------------ {-# LANGUAGE ExtendedDefaultRules #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Graphics.HSD3.Theme ( module Graphics.HSD3.Theme.Base , module Graphics.HSD3.Theme.Prelude , rainbowTheme , banaaniTheme ) where ------------------------------------------------------------------------------ import Control.Monad ------------------------------------------------------------------------------ import Graphics.HSD3.D3 import Graphics.HSD3.Theme.Base import Graphics.HSD3.Theme.Prelude ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | Rainbow rainbowTheme :: Theme a rainbowTheme = def { themeSt = def { foreColor = Box $ cycl group [ Hex "#096975", Hex "#7DB31B", Hex "#CFCF0C", Hex "#EA552D", Hex "#DB2556" ], backColor = Box $ Hex "LightBlue" } } ------------------------------------------------------------------------------ -- | Colorful Banaani -- http://www.colourlovers.com/palette/1606220/colorful_banaani banaaniTheme :: Theme a banaaniTheme = def { defs = void $ do void $ gradient Vertical "fourth" (RGB 223 214 191) (RGB 193 185 165) void $ gradient Vertical "fifth" (RGB 150 186 175) (RGB 131 162 153) void $ gradient Vertical "first" (RGB 150 186 175) (RGB 131 162 153) void $ gradient Vertical "second" (RGB 230 101 67) (RGB 200 88 58) void $ gradient Vertical "third" (RGB 196 47 52) (RGB 171 41 46), themeSt = def { foreColor = Box $ cycl index [URL "first", URL "second", URL "third"], backColor = Box $ cycl index [URL "fourth"], strokeColor = Box $ cycl index [RGB 131 162 153, RGB 200 88 58, RGB 171 41 46], strokeWidth = Box (1 :: Integer) } }
Soostone/hs-d3
src/Graphics/HSD3/Theme.hs
bsd-3-clause
2,146
0
13
464
478
260
218
34
1
{-# OPTIONS_GHC -fno-warn-deprecated-flags #-} {-# LANGUAGE CPP,ScopedTypeVariables,PatternSignatures #-} module CatchExceptions(catchExceptions) where import Prelude hiding (catch) import Control.Exception import System.IO.Unsafe #if __GLASGOW_HASKELL__ >= 610 type AnyException = SomeException #else type AnyException = Exception #endif catchExceptions :: Eq a => a -> Maybe a catchExceptions x = unsafePerformIO $ do catch (evaluate (x == x) >> return (Just x)) (\(_ :: AnyException) -> return Nothing)
jystic/QuickSpec
qs1/CatchExceptions.hs
bsd-3-clause
525
0
13
82
123
69
54
12
1
{-# LANGUAGE RecordWildCards, PatternGuards, ScopedTypeVariables #-} module Text.HTML.TagSoup.Implementation where import Text.HTML.TagSoup.Type import Text.HTML.TagSoup.Options import Text.StringLike as Str import Numeric (readHex) import Data.Char (chr, ord) import Data.Ix import Control.Exception(assert) import Control.Arrow --------------------------------------------------------------------- -- BOTTOM LAYER data Out = Char Char | Tag -- < | TagShut -- </ | AttName | AttVal | TagEnd -- > | TagEndClose -- /> | Comment -- <!-- | CommentEnd -- --> | EntityName -- & | EntityNum -- &# | EntityHex -- &#x | EntityEnd Bool -- Attributed followed by ; for True, missing ; for False | Warn String | Pos Position deriving (Show,Eq) errSeen x = Warn $ "Unexpected " ++ show x errWant x = Warn $ "Expected " ++ show x data S = S {s :: S ,tl :: S ,hd :: Char ,eof :: Bool ,next :: String -> Maybe S ,pos :: [Out] -> [Out] } expand :: Position -> String -> S expand p text = res where res = S{s = res ,tl = expand (positionChar p (head text)) (tail text) ,hd = if null text then '\0' else head text ,eof = null text ,next = next p text ,pos = (Pos p:) } next p (t:ext) (s:tr) | t == s = next (positionChar p t) ext tr next p text [] = Just $ expand p text next _ _ _ = Nothing infixr & class Outable a where (&) :: a -> [Out] -> [Out] instance Outable Char where (&) = ampChar instance Outable Out where (&) = ampOut ampChar x y = Char x : y ampOut x y = x : y state :: String -> S state s = expand nullPosition s --------------------------------------------------------------------- -- TOP LAYER output :: forall str . StringLike str => ParseOptions str -> [Out] -> [Tag str] output ParseOptions{..} x = (if optTagTextMerge then tagTextMerge else id) $ go ((nullPosition,[]),x) where -- main choice loop go :: ((Position,[Tag str]),[Out]) -> [Tag str] go ((p,ws),xs) | p `seq` False = [] -- otherwise p is a space leak when optTagPosition == False go ((p,ws),xs) | not $ null ws = (if optTagWarning then (reverse ws++) else id) $ go ((p,[]),xs) go ((p,ws),Pos p2:xs) = go ((p2,ws),xs) go x | isChar x = pos x $ TagText a : go y where (y,a) = charsStr x go x | isTag x = pos x $ TagOpen a b : (if isTagEndClose z then pos x $ TagClose a : go (next z) else go (skip isTagEnd z)) where (y,a) = charsStr $ next x (z,b) = atts y go x | isTagShut x = pos x $ (TagClose a:) $ (if not (null b) then warn x "Unexpected attributes in close tag" else id) $ if isTagEndClose z then warn x "Unexpected self-closing in close tag" $ go (next z) else go (skip isTagEnd z) where (y,a) = charsStr $ next x (z,b) = atts y go x | isComment x = pos x $ TagComment a : go (skip isCommentEnd y) where (y,a) = charsStr $ next x go x | isEntityName x = poss x ((if optTagWarning then id else filter (not . isTagWarning)) $ optEntityData (a, getEntityEnd y)) ++ go (skip isEntityEnd y) where (y,a) = charsStr $ next x go x | isEntityNumHex x = pos x $ TagText (fromChar $ entityChr x a) : go (skip isEntityEnd y) where (y,a) = chars $ next x go x | Just a <- fromWarn x = if optTagWarning then pos x $ TagWarning (fromString a) : go (next x) else go (next x) go x | isEof x = [] atts :: ((Position,[Tag str]),[Out]) -> ( ((Position,[Tag str]),[Out]) , [(str,str)] ) atts x | isAttName x = second ((a,b):) $ atts z where (y,a) = charsStr (next x) (z,b) = if isAttVal y then charsEntsStr (next y) else (y, empty) atts x | isAttVal x = second ((empty,a):) $ atts y where (y,a) = charsEntsStr (next x) atts x = (x, []) -- chars chars x = charss False x charsStr x = (id *** fromString) $ chars x charsEntsStr x = (id *** fromString) $ charss True x -- loop round collecting characters, if the b is set including entity charss :: Bool -> ((Position,[Tag str]),[Out]) -> ( ((Position,[Tag str]),[Out]) , String) charss t x | Just a <- fromChr x = (y, a:b) where (y,b) = charss t (next x) charss t x | t, isEntityName x = second (toString n ++) $ charss t $ addWarns m z where (y,a) = charsStr $ next x b = getEntityEnd y z = skip isEntityEnd y (n,m) = optEntityAttrib (a,b) charss t x | t, isEntityNumHex x = second (entityChr x a:) $ charss t z where (y,a) = chars $ next x z = skip isEntityEnd y charss t ((_,w),Pos p:xs) = charss t ((p,w),xs) charss t x | Just a <- fromWarn x = charss t $ (if optTagWarning then addWarns [TagWarning $ fromString a] else id) $ next x charss t x = (x, []) -- utility functions next x = second (drop 1) x skip f x = assert (isEof x || f x) (next x) addWarns ws x@((p,w),y) = ((p, reverse (poss x ws) ++ w), y) pos ((p,_),_) rest = if optTagPosition then tagPosition p : rest else rest warn x s rest = if optTagWarning then pos x $ TagWarning (fromString s) : rest else rest poss x = concatMap (\w -> pos x [w]) entityChr x s | isEntityNum x = chr_ $ read s | isEntityHex x = chr_ $ fst $ head $ readHex s where chr_ x | inRange (toInteger $ ord minBound, toInteger $ ord maxBound) x = chr $ fromInteger x | otherwise = '?' isEof (_,[]) = True; isEof _ = False isChar (_,Char{}:_) = True; isChar _ = False isTag (_,Tag{}:_) = True; isTag _ = False isTagShut (_,TagShut{}:_) = True; isTagShut _ = False isAttName (_,AttName{}:_) = True; isAttName _ = False isAttVal (_,AttVal{}:_) = True; isAttVal _ = False isTagEnd (_,TagEnd{}:_) = True; isTagEnd _ = False isTagEndClose (_,TagEndClose{}:_) = True; isTagEndClose _ = False isComment (_,Comment{}:_) = True; isComment _ = False isCommentEnd (_,CommentEnd{}:_) = True; isCommentEnd _ = False isEntityName (_,EntityName{}:_) = True; isEntityName _ = False isEntityNumHex (_,EntityNum{}:_) = True; isEntityNumHex (_,EntityHex{}:_) = True; isEntityNumHex _ = False isEntityNum (_,EntityNum{}:_) = True; isEntityNum _ = False isEntityHex (_,EntityHex{}:_) = True; isEntityHex _ = False isEntityEnd (_,EntityEnd{}:_) = True; isEntityEnd _ = False isWarn (_,Warn{}:_) = True; isWarn _ = False fromChr (_,Char x:_) = Just x ; fromChr _ = Nothing fromWarn (_,Warn x:_) = Just x ; fromWarn _ = Nothing getEntityEnd (_,EntityEnd b:_) = b -- Merge all adjacent TagText bits tagTextMerge :: StringLike str => [Tag str] -> [Tag str] tagTextMerge (TagText x:xs) = TagText (strConcat (x:a)) : tagTextMerge b where (a,b) = f xs -- additional brackets on 3 lines to work around HSE 1.3.2 bugs with pattern fixities f (TagText x:xs) = (x:a,b) where (a,b) = f xs f (TagPosition{}:(x@TagText{}:xs)) = f $ x : xs f x = g x id x g o op (p@TagPosition{}:(w@TagWarning{}:xs)) = g o (op . (p:) . (w:)) xs g o op (w@TagWarning{}:xs) = g o (op . (w:)) xs g o op (p@TagPosition{}:(x@TagText{}:xs)) = f $ p : x : op xs g o op (x@TagText{}:xs) = f $ x : op xs g o op _ = ([], o) tagTextMerge (x:xs) = x : tagTextMerge xs tagTextMerge [] = []
ChristopherKing42/tagsoup
Text/HTML/TagSoup/Implementation.hs
bsd-3-clause
7,703
0
16
2,304
3,584
1,892
1,692
146
29
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, TypeFamilies #-} -- TODO: needs profiling to improve performance. {- real 4m6.950s user 4m5.785s sys 0m1.039s -} import qualified Common.Polynomial.Polynomial as P import Common.NumMod.MkNumMod import Common.Numbers.Primes (primes) import Common.Numbers.Numbers (fastpow) mkNumMod True 1004535809 type Zn = Int1004535809 newtype Poly = Poly (P.Polynomial Zn) instance Num Poly where Poly p1 + Poly p2 = Poly $ p1 + p2 Poly p1 - Poly p2 = Poly $ p1 - p2 Poly p1 * Poly p2 = Poly $ P.fromList $ take 20001 . P.toList $ p1 * p2 fromInteger = Poly . fromInteger poly :: Poly poly = Poly . P.fromList $ map toZn $ 1 : zipWith (-) (tail primeList) primeList where primeList = take 20001 primes toZn = fromInteger . toInteger main = print $ p P.! 20000 where Poly p = poly `fastpow` (20000 :: Int)
foreverbell/project-euler-solutions
src/537.hs
bsd-3-clause
919
0
11
217
287
151
136
19
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Main where import System.FilePath import System.Directory import Control.Applicative import Control.Monad import Template readTemplate templateFile = parseTemplate <$> readFile templateFile writeTemplate file vars multi template = writeFile file (renderTemplate template vars multi) -- print a loud error if the conversion is losing information divSafe :: Int -> Int -> Int divSafe a b | r == 0 = d | otherwise = error ("cannot safely convert values: trying to divide " ++ show a ++ " by " ++ show b ++ " remainder: " ++ show r) where (d,r) = a `divMod` b newtype Bits = Bits Int deriving (Show,Eq,Num) newtype Bytes = Bytes Int deriving (Show,Eq,Num) bitsToBytes :: Bits -> Bytes bitsToBytes (Bits b) = Bytes (b `divSafe` 8) class SizedNum a where showBytes :: a -> String showBits :: a -> String showW64 :: a -> String instance SizedNum Bytes where showBits (Bytes b) = show (b * 8) showBytes (Bytes b) = show b showW64 (Bytes b) = show (b `divSafe` 8) instance SizedNum Bits where showBits (Bits b) = show b showBytes (Bits b) = show (b `divSafe` 8) showW64 (Bits b) = show (b `divSafe` 64) data GenHashModule = GenHashModule { ghmModuleName :: String , ghmHeaderFile :: String , ghmHashName :: String , ghmContextSize :: Bytes , ghmCustomizable :: HashCustom } data Prop = VarCtx (Bits -> Bytes) data HashCustom = HashSimple Bits -- digest size in bits Bytes -- block length in bytes | HashMulti [Prop] [(Bits, Bytes)] -- list of (digest output size in *bits*, block size in bytes) hashModules = -- module header hash ctx dg blk [ GenHashModule "Blake2s" "blake2.h" "blake2s" 136 (HashMulti [] [(160, 64), (224,64), (256,64)]) , GenHashModule "Blake2sp" "blake2.h" "blake2sp" 1752 (HashMulti [] [(224,64), (256,64)]) , GenHashModule "Blake2b" "blake2.h" "blake2b" 248 (HashMulti [] [(160, 128), (224, 128), (256, 128), (384, 128), (512,128)]) , GenHashModule "Blake2bp" "blake2.h" "blake2bp" 1768 (HashMulti [] [(512,128)]) , GenHashModule "MD2" "md2.h" "md2" 96 (HashSimple 128 16) , GenHashModule "MD4" "md4.h" "md4" 96 (HashSimple 128 64) , GenHashModule "MD5" "md5.h" "md5" 96 (HashSimple 128 64) , GenHashModule "SHA1" "sha1.h" "sha1" 96 (HashSimple 160 64) , GenHashModule "SHA224" "sha256.h" "sha224" 192 (HashSimple 224 64) , GenHashModule "SHA256" "sha256.h" "sha256" 192 (HashSimple 256 64) , GenHashModule "SHA384" "sha512.h" "sha384" 256 (HashSimple 384 128) , GenHashModule "SHA512" "sha512.h" "sha512" 256 (HashSimple 512 128) , GenHashModule "SHA512t" "sha512.h" "sha512t" 256 (HashMulti [] [(224,128),(256,128)]) , GenHashModule "Keccak" "keccak.h" "keccak" 352 (HashMulti [VarCtx sha3CtxSize] [(224,144),(256,136),(384,104),(512,72)]) , GenHashModule "SHA3" "sha3.h" "sha3" 352 (HashMulti [VarCtx sha3CtxSize] [(224,144),(256,136),(384,104),(512,72)]) , GenHashModule "RIPEMD160" "ripemd.h" "ripemd160" 128 (HashSimple 160 64) , GenHashModule "Skein256" "skein256.h" "skein256" 96 (HashMulti [] [(224,32),(256,32)]) , GenHashModule "Skein512" "skein512.h" "skein512" 160 (HashMulti [] [(224,64),(256,64),(384,64),(512,64)]) , GenHashModule "Tiger" "tiger.h" "tiger" 96 (HashSimple 192 64) , GenHashModule "Whirlpool" "whirlpool.h" "whirlpool" 168 (HashSimple 512 64) ] sha3CtxSize :: Bits -> Bytes sha3CtxSize bitLen = 4 + 4 + 8 * 25 -- generic context + sha3BlockSize bitLen -- variable buffer sha3BlockSize :: Bits -> Bytes sha3BlockSize bitLen = 200 - 2 * bitsToBytes bitLen renderHashModules genOpts = do hashTemplate <- readTemplate "template/hash.hs" hashLenTemplate <- readTemplate "template/hash-len.hs" forM_ hashModules $ \ghm -> do let baseVars = [ ("MODULENAME" , ghmModuleName ghm) , ("HEADER_FILE" , ghmHeaderFile ghm) , ("HASHNAME" , ghmHashName ghm) , ("CTX_SIZE_BYTES" , showBytes (ghmContextSize ghm)) , ("CTX_SIZE_WORD64" , showW64 (ghmContextSize ghm)) ] :: Attrs let mainDir = "Crypto/Hash" mainName = mainDir </> (ghmModuleName ghm ++ ".hs") createDirectoryIfMissing True mainDir let (tpl, addVars, multiVars) = case ghmCustomizable ghm of HashSimple digestSize blockLength -> (hashTemplate, [ ("DIGEST_SIZE_BITS" , showBits digestSize) , ("DIGEST_SIZE_BYTES", showBytes digestSize) , ("BLOCK_SIZE_BYTES" , showBytes blockLength) ] , [] ) HashMulti props customSizes -> let customCtxSize = let getVarCtx _ (VarCtx p) = Just p getVarCtx x _ = x in case foldl getVarCtx Nothing props of Nothing -> \_ -> [ ("CUSTOM_CTX_SIZE_BYTES" , showBytes (ghmContextSize ghm)) , ("CUSTOM_CTX_SIZE_WORD64" , showW64 (ghmContextSize ghm)) ] Just prop -> \outputSize -> [ ("CUSTOM_CTX_SIZE_BYTES" , showBytes $ prop outputSize) , ("CUSTOM_CTX_SIZE_WORD64" , showW64 $ prop outputSize) ] in (hashLenTemplate, [], [ ("CUSTOMIZABLE", map (\(outputSizeBits, customBlockSize) -> [ ("CUSTOM_BITSIZE", showBits outputSizeBits) , ("CUSTOM_DIGEST_SIZE_BITS", showBits outputSizeBits) , ("CUSTOM_DIGEST_SIZE_BYTES", showBytes outputSizeBits) , ("CUSTOM_BLOCK_SIZE_BYTES", showBytes customBlockSize) ] ++ customCtxSize outputSizeBits) customSizes ) ] ) writeTemplate mainName (baseVars ++ addVars) multiVars tpl main = do renderHashModules ()
tekul/cryptonite
gen/Gen.hs
bsd-3-clause
6,865
0
31
2,466
1,842
999
843
112
4
{-# LANGUAGE OverloadedStrings #-} module HPACKEncode ( run , EncodeStrategy(..) , defaultEncodeStrategy , CompressionAlgo(..) ) where import Control.Monad (when) import Data.ByteString (ByteString) import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString.Char8 as C8 import Data.Char import Data.Maybe (fromMaybe) import Network.HPACK import Network.HPACK.Table import JSON data Conf = Conf { debug :: Bool , enc :: DynamicTable -> HeaderList -> IO ByteString } run :: Bool -> EncodeStrategy -> Test -> IO [ByteString] run _ _ (Test _ []) = return [] run d stgy (Test _ ccs@(c:_)) = do let siz = fromMaybe 4096 $ size c withDynamicTableForEncoding siz $ \dyntbl -> do let conf = Conf { debug = d, enc = encodeHeader stgy 4096 } testLoop conf ccs dyntbl [] testLoop :: Conf -> [Case] -> DynamicTable -> [ByteString] -> IO [ByteString] testLoop _ [] _ hexs = return $ reverse hexs testLoop conf (c:cs) dyntbl hxs = do hx <- test conf c dyntbl testLoop conf cs dyntbl (C8.map toLower hx : hxs) test :: Conf -> Case -> DynamicTable -> IO ByteString test conf c dyntbl = do out <- enc conf dyntbl hs let hex' = B16.encode out when (debug conf) $ do putStrLn "---- Output context" printDynamicTable dyntbl putStrLn "--------------------------------" return hex' where hs = headers c
kazu-yamamoto/http2
test-hpack/HPACKEncode.hs
bsd-3-clause
1,477
0
16
388
509
264
245
47
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} -- | Resolving a build plan for a set of packages in a given Stackage -- snapshot. module Stack.BuildPlan ( BuildPlanException (..) , MiniBuildPlan(..) , MiniPackageInfo(..) , Snapshots (..) , getSnapshots , loadMiniBuildPlan , resolveBuildPlan , findBuildPlan , ToolMap , getToolMap , shadowMiniBuildPlan , parseCustomMiniBuildPlan ) where import Control.Applicative import Control.Exception (assert) import Control.Monad (liftM, forM) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (asks) import Control.Monad.State.Strict (State, execState, get, modify, put) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Crypto.Hash.SHA256 as SHA256 import Data.Aeson.Extended (FromJSON (..), withObject, withText, (.:), (.:?), (.!=)) import Data.Binary.VersionTagged (taggedDecodeOrLoad) import Data.ByteString (ByteString) import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import Data.Either (partitionEithers) import qualified Data.Foldable as F import qualified Data.HashMap.Strict as HM import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.List (intercalate) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe, mapMaybe) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time (Day) import qualified Data.Traversable as Tr import Data.Typeable (Typeable) import Data.Yaml (decodeEither', decodeFileEither) import Distribution.PackageDescription (GenericPackageDescription, flagDefault, flagManual, flagName, genPackageFlags, executables, exeName, library, libBuildInfo, buildable) import qualified Distribution.Package as C import qualified Distribution.PackageDescription as C import qualified Distribution.Version as C import Distribution.Text (display) import Network.HTTP.Download import Network.HTTP.Types (Status(..)) import Network.HTTP.Client (checkStatus) import Path import Path.IO import Prelude -- Fix AMP warning import Stack.Constants import Stack.Fetch import Stack.Package import Stack.Types import Stack.Types.StackT import System.Directory (canonicalizePath) import qualified System.FilePath as FP data BuildPlanException = UnknownPackages (Path Abs File) -- stack.yaml file (Map PackageName (Maybe Version, (Set PackageName))) -- truly unknown (Map PackageName (Set PackageIdentifier)) -- shadowed | SnapshotNotFound SnapName deriving (Typeable) instance Exception BuildPlanException instance Show BuildPlanException where show (SnapshotNotFound snapName) = unlines [ "SnapshotNotFound " ++ snapName' , "Non existing resolver: " ++ snapName' ++ "." , "For a complete list of available snapshots see https://www.stackage.org/snapshots" ] where snapName' = show $ renderSnapName snapName show (UnknownPackages stackYaml unknown shadowed) = unlines $ unknown' ++ shadowed' where unknown' :: [String] unknown' | Map.null unknown = [] | otherwise = concat [ ["The following packages do not exist in the build plan:"] , map go (Map.toList unknown) , case mapMaybe goRecommend $ Map.toList unknown of [] -> [] rec -> ("Recommended action: modify the extra-deps field of " ++ toFilePath stackYaml ++ " to include the following:") : (rec ++ ["Note: further dependencies may need to be added"]) , case mapMaybe getNoKnown $ Map.toList unknown of [] -> [] noKnown -> [ "There are no known versions of the following packages:" , intercalate ", " $ map packageNameString noKnown ] ] where go (dep, (_, users)) | Set.null users = packageNameString dep go (dep, (_, users)) = concat [ packageNameString dep , " (used by " , intercalate ", " $ map packageNameString $ Set.toList users , ")" ] goRecommend (name, (Just version, _)) = Just $ "- " ++ packageIdentifierString (PackageIdentifier name version) goRecommend (_, (Nothing, _)) = Nothing getNoKnown (name, (Nothing, _)) = Just name getNoKnown (_, (Just _, _)) = Nothing shadowed' :: [String] shadowed' | Map.null shadowed = [] | otherwise = concat [ ["The following packages are shadowed by local packages:"] , map go (Map.toList shadowed) , ["Recommended action: modify the extra-deps field of " ++ toFilePath stackYaml ++ " to include the following:"] , extraDeps , ["Note: further dependencies may need to be added"] ] where go (dep, users) | Set.null users = concat [ packageNameString dep , " (internal stack error: this should never be null)" ] go (dep, users) = concat [ packageNameString dep , " (used by " , intercalate ", " $ map (packageNameString . packageIdentifierName) $ Set.toList users , ")" ] extraDeps = map (\ident -> "- " ++ packageIdentifierString ident) $ Set.toList $ Set.unions $ Map.elems shadowed -- | Determine the necessary packages to install to have the given set of -- packages available. -- -- This function will not provide test suite and benchmark dependencies. -- -- This may fail if a target package is not present in the @BuildPlan@. resolveBuildPlan :: (MonadThrow m, MonadIO m, MonadReader env m, HasBuildConfig env, MonadLogger m, HasHttpManager env, MonadBaseControl IO m,MonadCatch m) => MiniBuildPlan -> (PackageName -> Bool) -- ^ is it shadowed by a local package? -> Map PackageName (Set PackageName) -- ^ required packages, and users of it -> m ( Map PackageName (Version, Map FlagName Bool) , Map PackageName (Set PackageName) ) resolveBuildPlan mbp isShadowed packages | Map.null (rsUnknown rs) && Map.null (rsShadowed rs) = return (rsToInstall rs, rsUsedBy rs) | otherwise = do bconfig <- asks getBuildConfig let maxVer = Map.fromListWith max $ map toTuple $ Map.keys (bcPackageCaches bconfig) unknown = flip Map.mapWithKey (rsUnknown rs) $ \ident x -> (Map.lookup ident maxVer, x) throwM $ UnknownPackages (bcStackYaml bconfig) unknown (rsShadowed rs) where rs = getDeps mbp isShadowed packages data ResolveState = ResolveState { rsVisited :: Map PackageName (Set PackageName) -- ^ set of shadowed dependencies , rsUnknown :: Map PackageName (Set PackageName) , rsShadowed :: Map PackageName (Set PackageIdentifier) , rsToInstall :: Map PackageName (Version, Map FlagName Bool) , rsUsedBy :: Map PackageName (Set PackageName) } toMiniBuildPlan :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m) => CompilerVersion -- ^ Compiler version -> Map PackageName Version -- ^ cores -> Map PackageName (Version, Map FlagName Bool) -- ^ non-core packages -> m MiniBuildPlan toMiniBuildPlan compilerVersion corePackages packages = do $logInfo "Caching build plan" -- Determine the dependencies of all of the packages in the build plan. We -- handle core packages specially, because some of them will not be in the -- package index. For those, we allow missing packages to exist, and then -- remove those from the list of dependencies, since there's no way we'll -- ever reinstall them anyway. (cores, missingCores) <- addDeps True compilerVersion $ fmap (, Map.empty) corePackages (extras, missing) <- addDeps False compilerVersion packages assert (Set.null missing) $ return MiniBuildPlan { mbpCompilerVersion = compilerVersion , mbpPackages = Map.unions [ fmap (removeMissingDeps (Map.keysSet cores)) cores , extras , Map.fromList $ map goCore $ Set.toList missingCores ] } where goCore (PackageIdentifier name version) = (name, MiniPackageInfo { mpiVersion = version , mpiFlags = Map.empty , mpiPackageDeps = Set.empty , mpiToolDeps = Set.empty , mpiExes = Set.empty , mpiHasLibrary = True }) removeMissingDeps cores mpi = mpi { mpiPackageDeps = Set.intersection cores (mpiPackageDeps mpi) } -- | Add in the resolved dependencies from the package index addDeps :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m) => Bool -- ^ allow missing -> CompilerVersion -- ^ Compiler version -> Map PackageName (Version, Map FlagName Bool) -> m (Map PackageName MiniPackageInfo, Set PackageIdentifier) addDeps allowMissing compilerVersion toCalc = do menv <- getMinimalEnvOverride platform <- asks $ configPlatform . getConfig (resolvedMap, missingIdents) <- if allowMissing then do (missingNames, missingIdents, m) <- resolvePackagesAllowMissing menv (Map.keysSet idents0) Set.empty assert (Set.null missingNames) $ return (m, missingIdents) else do m <- resolvePackages menv (Map.keysSet idents0) Set.empty return (m, Set.empty) let byIndex = Map.fromListWith (++) $ flip map (Map.toList resolvedMap) $ \(ident, rp) -> (indexName $ rpIndex rp, [( ident , rpCache rp , maybe Map.empty snd $ Map.lookup (packageIdentifierName ident) toCalc )]) res <- forM (Map.toList byIndex) $ \(indexName', pkgs) -> withCabalFiles indexName' pkgs $ \ident flags cabalBS -> do (_warnings,gpd) <- readPackageUnresolvedBS Nothing cabalBS let packageConfig = PackageConfig { packageConfigEnableTests = False , packageConfigEnableBenchmarks = False , packageConfigFlags = flags , packageConfigCompilerVersion = compilerVersion , packageConfigPlatform = platform } name = packageIdentifierName ident pd = resolvePackageDescription packageConfig gpd exes = Set.fromList $ map (ExeName . S8.pack . exeName) $ executables pd notMe = Set.filter (/= name) . Map.keysSet return (name, MiniPackageInfo { mpiVersion = packageIdentifierVersion ident , mpiFlags = flags , mpiPackageDeps = notMe $ packageDependencies pd , mpiToolDeps = Map.keysSet $ packageToolDependencies pd , mpiExes = exes , mpiHasLibrary = maybe False (buildable . libBuildInfo) (library pd) }) return (Map.fromList $ concat res, missingIdents) where idents0 = Map.fromList $ map (\(n, (v, f)) -> (PackageIdentifier n v, Left f)) $ Map.toList toCalc -- | Resolve all packages necessary to install for getDeps :: MiniBuildPlan -> (PackageName -> Bool) -- ^ is it shadowed by a local package? -> Map PackageName (Set PackageName) -> ResolveState getDeps mbp isShadowed packages = execState (mapM_ (uncurry goName) $ Map.toList packages) ResolveState { rsVisited = Map.empty , rsUnknown = Map.empty , rsShadowed = Map.empty , rsToInstall = Map.empty , rsUsedBy = Map.empty } where toolMap = getToolMap mbp -- | Returns a set of shadowed packages we depend on. goName :: PackageName -> Set PackageName -> State ResolveState (Set PackageName) goName name users = do -- Even though we could check rsVisited first and short-circuit things -- earlier, lookup in mbpPackages first so that we can produce more -- usable error information on missing dependencies rs <- get put rs { rsUsedBy = Map.insertWith Set.union name users $ rsUsedBy rs } case Map.lookup name $ mbpPackages mbp of Nothing -> do modify $ \rs' -> rs' { rsUnknown = Map.insertWith Set.union name users $ rsUnknown rs' } return Set.empty Just mpi -> case Map.lookup name (rsVisited rs) of Just shadowed -> return shadowed Nothing -> do put rs { rsVisited = Map.insert name Set.empty $ rsVisited rs } let depsForTools = Set.unions $ mapMaybe (flip Map.lookup toolMap) (Set.toList $ mpiToolDeps mpi) let deps = Set.filter (/= name) (mpiPackageDeps mpi <> depsForTools) shadowed <- fmap F.fold $ Tr.forM (Set.toList deps) $ \dep -> if isShadowed dep then do modify $ \rs' -> rs' { rsShadowed = Map.insertWith Set.union dep (Set.singleton $ PackageIdentifier name (mpiVersion mpi)) (rsShadowed rs') } return $ Set.singleton dep else do shadowed <- goName dep (Set.singleton name) let m = Map.fromSet (\_ -> Set.singleton $ PackageIdentifier name (mpiVersion mpi)) shadowed modify $ \rs' -> rs' { rsShadowed = Map.unionWith Set.union m $ rsShadowed rs' } return shadowed modify $ \rs' -> rs' { rsToInstall = Map.insert name (mpiVersion mpi, mpiFlags mpi) $ rsToInstall rs' , rsVisited = Map.insert name shadowed $ rsVisited rs' } return shadowed -- | Look up with packages provide which tools. type ToolMap = Map ByteString (Set PackageName) -- | Map from tool name to package providing it getToolMap :: MiniBuildPlan -> Map ByteString (Set PackageName) getToolMap mbp = Map.unionsWith Set.union {- We no longer do this, following discussion at: https://github.com/commercialhaskell/stack/issues/308#issuecomment-112076704 -- First grab all of the package names, for times where a build tool is -- identified by package name $ Map.fromList (map (packageNameByteString &&& Set.singleton) (Map.keys ps)) -} -- And then get all of the explicit executable names $ concatMap goPair (Map.toList ps) where ps = mbpPackages mbp goPair (pname, mpi) = map (flip Map.singleton (Set.singleton pname) . unExeName) $ Set.toList $ mpiExes mpi -- | Download the 'Snapshots' value from stackage.org. getSnapshots :: (MonadThrow m, MonadIO m, MonadReader env m, HasHttpManager env, HasStackRoot env, HasConfig env) => m Snapshots getSnapshots = askLatestSnapshotUrl >>= parseUrl . T.unpack >>= downloadJSON -- | Most recent Nightly and newest LTS version per major release. data Snapshots = Snapshots { snapshotsNightly :: !Day , snapshotsLts :: !(IntMap Int) } deriving Show instance FromJSON Snapshots where parseJSON = withObject "Snapshots" $ \o -> Snapshots <$> (o .: "nightly" >>= parseNightly) <*> (fmap IntMap.unions $ mapM parseLTS $ map snd $ filter (isLTS . fst) $ HM.toList o) where parseNightly t = case parseSnapName t of Left e -> fail $ show e Right (LTS _ _) -> fail "Unexpected LTS value" Right (Nightly d) -> return d isLTS = ("lts-" `T.isPrefixOf`) parseLTS = withText "LTS" $ \t -> case parseSnapName t of Left e -> fail $ show e Right (LTS x y) -> return $ IntMap.singleton x y Right (Nightly _) -> fail "Unexpected nightly value" -- | Load up a 'MiniBuildPlan', preferably from cache loadMiniBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, HasGHCVariant env, MonadBaseControl IO m, MonadCatch m) => SnapName -> m MiniBuildPlan loadMiniBuildPlan name = do path <- configMiniBuildPlanCache name taggedDecodeOrLoad path $ liftM buildPlanFixes $ do bp <- loadBuildPlan name toMiniBuildPlan (siCompilerVersion $ bpSystemInfo bp) (siCorePackages $ bpSystemInfo bp) (fmap goPP $ bpPackages bp) where goPP pp = ( ppVersion pp , pcFlagOverrides $ ppConstraints pp ) -- | Some hard-coded fixes for build plans, hopefully to be irrelevant over -- time. buildPlanFixes :: MiniBuildPlan -> MiniBuildPlan buildPlanFixes mbp = mbp { mbpPackages = Map.fromList $ map go $ Map.toList $ mbpPackages mbp } where go (name, mpi) = (name, mpi { mpiFlags = goF (packageNameString name) (mpiFlags mpi) }) goF "persistent-sqlite" = Map.insert $(mkFlagName "systemlib") False goF "yaml" = Map.insert $(mkFlagName "system-libyaml") False goF _ = id -- | Load the 'BuildPlan' for the given snapshot. Will load from a local copy -- if available, otherwise downloading from Github. loadBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasStackRoot env) => SnapName -> m BuildPlan loadBuildPlan name = do env <- ask let stackage = getStackRoot env file' <- parseRelFile $ T.unpack file let fp = stackage </> $(mkRelDir "build-plan") </> file' $logDebug $ "Decoding build plan from: " <> T.pack (toFilePath fp) eres <- liftIO $ decodeFileEither $ toFilePath fp case eres of Right bp -> return bp Left e -> do $logDebug $ "Decoding build plan from file failed: " <> T.pack (show e) createTree (parent fp) req <- parseUrl $ T.unpack url $logSticky $ "Downloading " <> renderSnapName name <> " build plan ..." $logDebug $ "Downloading build plan from: " <> url _ <- download req { checkStatus = handle404 } fp $logStickyDone $ "Downloaded " <> renderSnapName name <> " build plan." liftIO (decodeFileEither $ toFilePath fp) >>= either throwM return where file = renderSnapName name <> ".yaml" reponame = case name of LTS _ _ -> "lts-haskell" Nightly _ -> "stackage-nightly" url = rawGithubUrl "fpco" reponame "master" file handle404 (Status 404 _) _ _ = Just $ SomeException $ SnapshotNotFound name handle404 _ _ _ = Nothing -- | Find the set of @FlagName@s necessary to get the given -- @GenericPackageDescription@ to compile against the given @BuildPlan@. Will -- only modify non-manual flags, and will prefer default values for flags. -- Returns @Nothing@ if no combination exists. checkBuildPlan :: (MonadLogger m, MonadThrow m, MonadIO m, MonadReader env m, HasConfig env, MonadCatch m) => Map PackageName Version -- ^ locally available packages -> MiniBuildPlan -> GenericPackageDescription -> m (Either DepErrors (Map PackageName (Map FlagName Bool))) checkBuildPlan locals mbp gpd = do platform <- asks (configPlatform . getConfig) return $ loop platform flagOptions where packages = Map.union locals $ fmap mpiVersion $ mbpPackages mbp loop _ [] = assert False $ Left Map.empty loop platform (flags:rest) | Map.null errs = Right $ if Map.null flags then Map.empty else Map.singleton (packageName pkg) flags | null rest = Left errs | otherwise = loop platform rest where errs = checkDeps (packageName pkg) (packageDeps pkg) packages pkg = resolvePackage pkgConfig gpd pkgConfig = PackageConfig { packageConfigEnableTests = True , packageConfigEnableBenchmarks = True , packageConfigFlags = flags , packageConfigCompilerVersion = compilerVersion , packageConfigPlatform = platform } compilerVersion = mbpCompilerVersion mbp flagName' = fromCabalFlagName . flagName -- Avoid exponential complexity in flag combinations making us sad pandas. -- See: https://github.com/commercialhaskell/stack/issues/543 maxFlagOptions = 128 flagOptions = take maxFlagOptions $ map Map.fromList $ mapM getOptions $ genPackageFlags gpd getOptions f | flagManual f = [(flagName' f, flagDefault f)] | flagDefault f = [ (flagName' f, True) , (flagName' f, False) ] | otherwise = [ (flagName' f, False) , (flagName' f, True) ] -- | Checks if the given package dependencies can be satisfied by the given set -- of packages. Will fail if a package is either missing or has a version -- outside of the version range. checkDeps :: PackageName -- ^ package using dependencies, for constructing DepErrors -> Map PackageName VersionRange -> Map PackageName Version -> DepErrors checkDeps myName deps packages = Map.unionsWith mappend $ map go $ Map.toList deps where go :: (PackageName, VersionRange) -> DepErrors go (name, range) = case Map.lookup name packages of Nothing -> Map.singleton name DepError { deVersion = Nothing , deNeededBy = Map.singleton myName range } Just v | withinRange v range -> Map.empty | otherwise -> Map.singleton name DepError { deVersion = Just v , deNeededBy = Map.singleton myName range } type DepErrors = Map PackageName DepError data DepError = DepError { deVersion :: !(Maybe Version) , deNeededBy :: !(Map PackageName VersionRange) } instance Monoid DepError where mempty = DepError Nothing Map.empty mappend (DepError a x) (DepError b y) = DepError (maybe a Just b) (Map.unionWith C.intersectVersionRanges x y) -- | Find a snapshot and set of flags that is compatible with the given -- 'GenericPackageDescription'. Returns 'Nothing' if no such snapshot is found. findBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, HasGHCVariant env, MonadBaseControl IO m) => [GenericPackageDescription] -> [SnapName] -> m (Maybe (SnapName, Map PackageName (Map FlagName Bool))) findBuildPlan gpds0 = loop where loop [] = return Nothing loop (name:names') = do mbp <- loadMiniBuildPlan name $logInfo $ "Checking against build plan " <> renderSnapName name res <- mapM (checkBuildPlan localNames mbp) gpds0 case partitionEithers res of ([], flags) -> return $ Just (name, Map.unions flags) (errs, _) -> do $logInfo "" $logInfo "* Build plan did not match your requirements:" displayDepErrors $ Map.unionsWith mappend errs $logInfo "" loop names' localNames = Map.fromList $ map (fromCabalIdent . C.package . C.packageDescription) gpds0 fromCabalIdent (C.PackageIdentifier name version) = (fromCabalPackageName name, fromCabalVersion version) displayDepErrors :: MonadLogger m => DepErrors -> m () displayDepErrors errs = F.forM_ (Map.toList errs) $ \(depName, DepError mversion neededBy) -> do $logInfo $ T.concat [ " " , T.pack $ packageNameString depName , case mversion of Nothing -> " not found" Just version -> T.concat [ " version " , T.pack $ versionString version , " found" ] ] F.forM_ (Map.toList neededBy) $ \(user, range) -> $logInfo $ T.concat [ " - " , T.pack $ packageNameString user , " requires " , T.pack $ display range ] $logInfo "" shadowMiniBuildPlan :: MiniBuildPlan -> Set PackageName -> (MiniBuildPlan, Map PackageName MiniPackageInfo) shadowMiniBuildPlan (MiniBuildPlan cv pkgs0) shadowed = (MiniBuildPlan cv $ Map.fromList met, Map.fromList unmet) where pkgs1 = Map.difference pkgs0 $ Map.fromSet (\_ -> ()) shadowed depsMet = flip execState Map.empty $ mapM_ (check Set.empty) (Map.keys pkgs1) check visited name | name `Set.member` visited = error $ "shadowMiniBuildPlan: cycle detected, your MiniBuildPlan is broken: " ++ show (visited, name) | otherwise = do m <- get case Map.lookup name m of Just x -> return x Nothing -> case Map.lookup name pkgs1 of Nothing | name `Set.member` shadowed -> return False -- In this case, we have to assume that we're -- constructing a build plan on a different OS or -- architecture, and therefore different packages -- are being chosen. The common example of this is -- the Win32 package. | otherwise -> return True Just mpi -> do let visited' = Set.insert name visited ress <- mapM (check visited') (Set.toList $ mpiPackageDeps mpi) let res = and ress modify $ \m' -> Map.insert name res m' return res (met, unmet) = partitionEithers $ map toEither $ Map.toList pkgs1 toEither pair@(name, _) = wrapper pair where wrapper = case Map.lookup name depsMet of Just True -> Left Just False -> Right Nothing -> assert False Right parseCustomMiniBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m) => Path Abs File -- ^ stack.yaml file location -> T.Text -> m MiniBuildPlan parseCustomMiniBuildPlan stackYamlFP url0 = do yamlFP <- getYamlFP url0 yamlBS <- liftIO $ S.readFile $ toFilePath yamlFP let yamlHash = S8.unpack $ B16.encode $ SHA256.hash yamlBS binaryFilename <- parseRelFile $ yamlHash ++ ".bin" customPlanDir <- getCustomPlanDir let binaryFP = customPlanDir </> $(mkRelDir "bin") </> binaryFilename taggedDecodeOrLoad binaryFP $ do cs <- either throwM return $ decodeEither' yamlBS let addFlags :: PackageIdentifier -> (PackageName, (Version, Map FlagName Bool)) addFlags (PackageIdentifier name ver) = (name, (ver, fromMaybe Map.empty $ Map.lookup name $ csFlags cs)) toMiniBuildPlan (csCompilerVersion cs) Map.empty (Map.fromList $ map addFlags $ Set.toList $ csPackages cs) where getCustomPlanDir = do root <- asks $ configStackRoot . getConfig return $ root </> $(mkRelDir "custom-plan") -- Get the path to the YAML file getYamlFP url = case parseUrl $ T.unpack url of Just req -> getYamlFPFromReq url req Nothing -> getYamlFPFromFile url getYamlFPFromReq url req = do let hashStr = S8.unpack $ B16.encode $ SHA256.hash $ encodeUtf8 url hashFP <- parseRelFile $ hashStr ++ ".yaml" customPlanDir <- getCustomPlanDir let cacheFP = customPlanDir </> $(mkRelDir "yaml") </> hashFP _ <- download req cacheFP return cacheFP getYamlFPFromFile url = do fp <- liftIO $ canonicalizePath $ toFilePath (parent stackYamlFP) FP.</> T.unpack (fromMaybe url $ T.stripPrefix "file://" url <|> T.stripPrefix "file:" url) parseAbsFile fp data CustomSnapshot = CustomSnapshot { csCompilerVersion :: !CompilerVersion , csPackages :: !(Set PackageIdentifier) , csFlags :: !(Map PackageName (Map FlagName Bool)) } instance FromJSON CustomSnapshot where parseJSON = withObject "CustomSnapshot" $ \o -> CustomSnapshot <$> ((o .: "compiler") >>= \t -> case parseCompilerVersion t of Nothing -> fail $ "Invalid compiler: " ++ T.unpack t Just compilerVersion -> return compilerVersion) <*> o .: "packages" <*> o .:? "flags" .!= Map.empty
vigoo/stack
src/Stack/BuildPlan.hs
bsd-3-clause
31,198
0
32
10,550
7,462
3,828
3,634
586
5
{-# LANGUAGE TemplateHaskell #-} ------------------------------------------------------------------------------ -- | This module defines our application's state type and an alias for its -- handler monad. module Application where ------------------------------------------------------------------------------ import Data.Lens.Template import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Heist import Snap.Snaplet.OAuth import Snap.Snaplet.Session ------------------------------------------------------------------------------ data App = App { _heist :: Snaplet (Heist App) , _sess :: Snaplet SessionManager , _auth :: Snaplet (AuthManager App) , _oauth :: Snaplet OAuthSnaplet } makeLens ''App instance HasHeist App where heistLens = subSnaplet heist instance HasOAuth App where oauthLens = oauth ------------------------------------------------------------------------------ type AppHandler = Handler App App
HaskellCNOrg/snaplet-oauth
example/src/Application.hs
bsd-3-clause
1,023
0
11
190
151
88
63
19
0
{-# LANGUAGE OverloadedStrings #-} module Network.FTP.Utils where import qualified Prelude import BasicPrelude import qualified Filesystem.Path as Path import qualified Filesystem.Path.CurrentOS as Path import qualified Data.Text.Encoding as T -- | drop root dropHeadingPathSeparator :: FilePath -> FilePath dropHeadingPathSeparator p = fromMaybe p $ Path.stripPrefix "/" p -- | encode file path. encode :: FilePath -> ByteString encode = T.encodeUtf8 . either id id . Path.toText -- | decode file path. decode :: ByteString -> FilePath decode = Path.fromText . T.decodeUtf8
yihuang/haskell-ftp
Network/FTP/Utils.hs
bsd-3-clause
579
0
7
83
128
77
51
13
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} module Database.Persist.Sql.Run where import Database.Persist.Class.PersistStore import Database.Persist.Sql.Types import Database.Persist.Sql.Raw import Control.Monad.Trans.Control import Data.Pool as P import Control.Monad.Trans.Reader hiding (local) import Control.Monad.Trans.Resource import Control.Monad.Logger import Control.Monad.Base import Control.Exception.Lifted (onException, bracket) import Control.Monad.IO.Class import Control.Exception (mask) import System.Timeout (timeout) import Data.IORef (readIORef, writeIORef, newIORef) import qualified Data.Map as Map import Control.Monad (liftM) -- | Get a connection from the pool, run the given action, and then return the -- connection to the pool. -- -- Note: This function previously timed out after 2 seconds, but this behavior -- was buggy and caused more problems than it solved. Since version 2.1.2, it -- performs no timeout checks. runSqlPool :: (MonadBaseControl IO m, IsSqlBackend backend) => ReaderT backend m a -> Pool backend -> m a runSqlPool r pconn = withResource pconn $ runSqlConn r -- | Like 'withResource', but times out the operation if resource -- allocation does not complete within the given timeout period. -- -- Since 2.0.0 withResourceTimeout :: forall a m b. (MonadBaseControl IO m) => Int -- ^ Timeout period in microseconds -> Pool a -> (a -> m b) -> m (Maybe b) {-# SPECIALIZE withResourceTimeout :: Int -> Pool a -> (a -> IO b) -> IO (Maybe b) #-} withResourceTimeout ms pool act = control $ \runInIO -> mask $ \restore -> do mres <- timeout ms $ takeResource pool case mres of Nothing -> runInIO $ return (Nothing :: Maybe b) Just (resource, local) -> do ret <- restore (runInIO (liftM Just $ act resource)) `onException` destroyResource pool local resource putResource local resource return ret {-# INLINABLE withResourceTimeout #-} runSqlConn :: (MonadBaseControl IO m, IsSqlBackend backend) => ReaderT backend m a -> backend -> m a runSqlConn r conn = control $ \runInIO -> mask $ \restore -> do let conn' = persistBackend conn getter = getStmtConn conn' restore $ connBegin conn' getter x <- onException (restore $ runInIO $ runReaderT r conn) (restore $ connRollback conn' getter) restore $ connCommit conn' getter return x runSqlPersistM :: (IsSqlBackend backend) => ReaderT backend (NoLoggingT (ResourceT IO)) a -> backend -> IO a runSqlPersistM x conn = runResourceT $ runNoLoggingT $ runSqlConn x conn runSqlPersistMPool :: (IsSqlBackend backend) => ReaderT backend (NoLoggingT (ResourceT IO)) a -> Pool backend -> IO a runSqlPersistMPool x pool = runResourceT $ runNoLoggingT $ runSqlPool x pool liftSqlPersistMPool :: (MonadIO m, IsSqlBackend backend) => ReaderT backend (NoLoggingT (ResourceT IO)) a -> Pool backend -> m a liftSqlPersistMPool x pool = liftIO (runSqlPersistMPool x pool) withSqlPool :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, IsSqlBackend backend) => (LogFunc -> IO backend) -- ^ create a new connection -> Int -- ^ connection count -> (Pool backend -> m a) -> m a withSqlPool mkConn connCount f = bracket (createSqlPool mkConn connCount) (liftIO . destroyAllResources) f createSqlPool :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, IsSqlBackend backend) => (LogFunc -> IO backend) -> Int -> m (Pool backend) createSqlPool mkConn size = do logFunc <- askLogFunc liftIO $ createPool (mkConn logFunc) close' 1 20 size -- NOTE: This function is a terrible, ugly hack. It would be much better to -- just clean up monad-logger. -- -- FIXME: in a future release, switch over to the new askLoggerIO function -- added in monad-logger 0.3.10. That function was not available at the time -- this code was written. askLogFunc :: forall m. (MonadBaseControl IO m, MonadLogger m) => m LogFunc askLogFunc = do ref <- liftBase $ newIORef undefined liftBaseWith $ \run -> writeIORef ref run runInBase <- liftBase $ readIORef ref return $ \a b c d -> do _ <- runInBase (monadLoggerLog a b c d) return () withSqlConn :: (MonadIO m, MonadBaseControl IO m, MonadLogger m, IsSqlBackend backend) => (LogFunc -> IO backend) -> (backend -> m a) -> m a withSqlConn open f = do logFunc <- askLogFunc bracket (liftIO $ open logFunc) (liftIO . close') f close' :: (IsSqlBackend backend) => backend -> IO () close' conn = do readIORef (connStmtMap $ persistBackend conn) >>= mapM_ stmtFinalize . Map.elems connClose $ persistBackend conn
pseudonom/persistent
persistent/Database/Persist/Sql/Run.hs
mit
4,774
0
23
980
1,326
685
641
97
2
module Main where import qualified App.Game as App main :: IO() main = App.run
korczis/skull-haskell
src/Apps/Playground/Playground.hs
mit
81
0
6
16
29
18
11
4
1
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables, TemplateHaskell #-} {-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} module Web.JWTTests ( main , defaultTestGroup ) where import Control.Applicative import Test.Tasty import Test.Tasty.TH import Test.Tasty.HUnit import Test.Tasty.QuickCheck import qualified Test.QuickCheck as QC import qualified Data.Map as Map import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.Aeson.Types import Data.Maybe import Data.String (fromString, IsString) import Data.Time import Web.JWT defaultTestGroup :: TestTree defaultTestGroup = $(testGroupGenerator) main :: IO () main = defaultMain defaultTestGroup case_stringOrURIString = do let str = "foo bar baz 2312j!@&^#^*!(*@" sou = stringOrURI str Just str @=? fmap (T.pack . show) sou case_stringOrURI= do let str = "http://[email protected]:8900/foo/bar?baz=t;" sou = stringOrURI str Just str @=? fmap (T.pack . show) sou case_intDateDeriveOrd = do let i1 = intDate 1231231231 -- Tue 6 Jan 2009 19:40:31 AEDT i2 = intDate 1231232231 -- Tue 6 Jan 2009 19:57:11 AEDT LT @=? i1 `compare` i2 case_decodeJWT = do -- Generated with ruby-jwt let input = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U" mJwt = decode input True @=? isJust mJwt True @=? isJust (fmap signature mJwt) let (Just unverified) = mJwt Just HS256 @=? alg (header unverified) Just "payload" @=? Map.lookup "some" (unregisteredClaims $ claims unverified) case_verify = do -- Generated with ruby-jwt let input = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U" mVerified = verify (secret "secret") =<< decode input True @=? isJust mVerified case_decodeAndVerifyJWT = do -- Generated with ruby-jwt let input = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2U" mJwt = decodeAndVerifySignature (secret "secret") input True @=? isJust mJwt let (Just verified) = mJwt Just HS256 @=? alg (header verified) Just "payload" @=? Map.lookup "some" (unregisteredClaims $ claims verified) -- It must be impossible to get a VerifiedJWT if alg is "none" case_decodeAndVerifyJWTAlgoNone = do {- - Header: { "alg": "none", "typ": "JWT" } Payload: { "iss": "https://jwt-idp.example.com", "sub": "mailto:[email protected]", "nbf": 1425980755, "exp": 1425984355, "iat": 1425980755, "jti": "id123456", "typ": "https://example.com/register" } -} let input = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJodHRwczovL2p3dC1pZHAuZXhhbXBsZS5jb20iLCJzdWIiOiJtYWlsdG86bWlrZUBleGFtcGxlLmNvbSIsIm5iZiI6MTQyNTk4MDc1NSwiZXhwIjoxNDI1OTg0MzU1LCJpYXQiOjE0MjU5ODA3NTUsImp0aSI6ImlkMTIzNDU2IiwidHlwIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9yZWdpc3RlciJ9." mJwt = decodeAndVerifySignature (secret "secretkey") input False @=? isJust mJwt case_decodeAndVerifyJWTFailing = do -- Generated with ruby-jwt, modified to be invalid let input = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9.Joh1R2dYzkRvDkqv3sygm5YyK8Gi4ShZqbhK2gxcs2u" mJwt = decodeAndVerifySignature (secret "secret") input False @=? isJust mJwt case_decodeInvalidInput = do let inputs = ["", "a.", "a.b"] result = map decode inputs True @=? all isNothing result case_decodeAndVerifySignatureInvalidInput = do let inputs = ["", "a.", "a.b"] result = map (decodeAndVerifySignature (secret "secret")) inputs True @=? all isNothing result case_encodeJWTNoMac = do let cs = def { iss = stringOrURI "Foo" , unregisteredClaims = Map.fromList [("http://example.com/is_root", Bool True)] } jwt = encodeUnsigned cs -- Verify the shape of the JWT, ensure the shape of the triple of -- <header>.<claims>.<signature> let (h:c:s:_) = T.splitOn "." jwt False @=? T.null h False @=? T.null c True @=? T.null s case_encodeDecodeJWTNoMac = do let cs = def { iss = stringOrURI "Foo" , unregisteredClaims = Map.fromList [("http://example.com/is_root", Bool True)] } mJwt = decode $ encodeUnsigned cs True @=? isJust mJwt let (Just unverified) = mJwt cs @=? claims unverified case_encodeDecodeJWT = do let now = 1394573404 cs = def { iss = stringOrURI "Foo" , iat = intDate now , unregisteredClaims = Map.fromList [("http://example.com/is_root", Bool True)] } key = secret "secret-key" mJwt = decode $ encodeSigned HS256 key cs let (Just claims') = fmap claims mJwt cs @=? claims' Just now @=? fmap secondsSinceEpoch (iat claims') case_tokenIssuer = do let iss' = stringOrURI "Foo" cs = def { iss = iss' , unregisteredClaims = Map.fromList [("http://example.com/is_root", Bool True)] } key = secret "secret-key" t = encodeSigned HS256 key cs iss' @=? tokenIssuer t case_encodeDecodeJWTClaimsSetCustomClaims = do let now = 1234 cs = def { iss = stringOrURI "Foo" , iat = intDate now , unregisteredClaims = Map.fromList [("http://example.com/is_root", Bool True)] } let secret' = secret "secret" jwt = decodeAndVerifySignature secret' $ encodeSigned HS256 secret' cs Just cs @=? fmap claims jwt case_encodeDecodeJWTClaimsSetWithSingleAud = do let now = 1234 cs = def { iss = stringOrURI "Foo" , aud = Left <$> stringOrURI "single-audience" , iat = intDate now } let secret' = secret "secret" jwt = decodeAndVerifySignature secret' $ encodeSigned HS256 secret' cs Just cs @=? fmap claims jwt case_encodeDecodeJWTClaimsSetWithMultipleAud = do let now = 1234 cs = def { iss = stringOrURI "Foo" , aud = Right <$> (:[]) <$> stringOrURI "audience" , iat = intDate now } let secret' = secret "secret" jwt = decodeAndVerifySignature secret' $ encodeSigned HS256 secret' cs Just cs @=? fmap claims jwt prop_stringOrURIProp = f where f :: StringOrURI -> Bool f sou = let s = stringOrURI $ T.pack $ show sou in Just sou == s prop_stringOrURIToText= f where f :: T.Text -> Bool f t = let mSou = stringOrURI t in case mSou of Just sou -> stringOrURIToText sou == t Nothing -> True prop_encode_decode_prop = f where f :: JWTClaimsSet -> Bool f claims' = let Just unverified = (decode $ encodeSigned HS256 (secret "secret") claims') in claims unverified == claims' prop_encode_decode_verify_signature_prop = f where f :: JWTClaimsSet -> Bool f claims' = let key = secret "secret" Just verified = (decodeAndVerifySignature key $ encodeSigned HS256 key claims') in claims verified == claims' instance Arbitrary JWTClaimsSet where arbitrary = JWTClaimsSet <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary ClaimsMap where arbitrary = return Map.empty instance Arbitrary IntDate where arbitrary = fmap (f . intDate) (arbitrary :: QC.Gen NominalDiffTime) where f = fromMaybe (fromJust $ intDate 1) instance Arbitrary NominalDiffTime where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac instance Arbitrary StringOrURI where arbitrary = fmap (f . stringOrURI) (arbitrary :: QC.Gen T.Text) where f = fromMaybe (fromJust $ stringOrURI "http://example.com") instance Arbitrary T.Text where arbitrary = fromString <$> (arbitrary :: QC.Gen String) instance Arbitrary TL.Text where arbitrary = fromString <$> (arbitrary :: QC.Gen String)
bitemyapp/haskell-jwt
tests/src/Web/JWTTests.hs
mit
8,537
0
15
2,387
1,989
1,003
986
177
2
-- Memcached interface. -- Copyright (C) 2005 Evan Martin <[email protected]> module Network.Memcache.Protocol ( Server, connect,disconnect,stats -- server-specific commands ) where -- TODO: -- - use exceptions where appropriate for protocol errors -- - expiration time in store import Network.Memcache import qualified Network import Network.Memcache.Key import Network.Memcache.Serializable import System.IO import qualified Data.ByteString as B import Data.ByteString (ByteString) -- | Gather results from action until condition is true. ioUntil :: (a -> Bool) -> IO a -> IO [a] ioUntil stop io = do val <- io if stop val then return [] else do more <- ioUntil stop io return (val:more) -- | Put out a line with \r\n terminator. hPutNetLn :: Handle -> String -> IO () hPutNetLn h str = hPutStr h (str ++ "\r\n") -- | Put out a line with \r\n terminator. hBSPutNetLn :: Handle -> ByteString -> IO () hBSPutNetLn h str = B.hPutStr h str >> hPutStr h "\r\n" -- | Get a line, stripping \r\n terminator. hGetNetLn :: Handle -> IO [Char] hGetNetLn h = fmap init (hGetLine h) -- init gets rid of \r -- | Put out a command (words with terminator) and flush. hPutCommand :: Handle -> [String] -> IO () hPutCommand h strs = hPutNetLn h (unwords strs) >> hFlush h newtype Server = Server { sHandle :: Handle } -- connect :: String -> Network.Socket.PortNumber -> IO Server connect :: Network.HostName -> Network.PortNumber -> IO Server connect host port = do handle <- Network.connectTo host (Network.PortNumber port) return (Server handle) disconnect :: Server -> IO () disconnect = hClose . sHandle stats :: Server -> IO [(String, String)] stats (Server handle) = do hPutCommand handle ["stats"] statistics <- ioUntil (== "END") (hGetNetLn handle) return $ map (tupelize . stripSTAT) statistics where stripSTAT ('S':'T':'A':'T':' ':x) = x stripSTAT x = x tupelize line = case words line of (key:rest) -> (key, unwords rest) [] -> (line, "") store :: (Key k, Serializable s) => String -> Server -> k -> s -> IO Bool store action (Server handle) key val = do let flags = (0::Int) let exptime = (0::Int) let valstr = serialize val let bytes = B.length valstr let cmd = unwords [action, toKey key, show flags, show exptime, show bytes] hPutNetLn handle cmd hBSPutNetLn handle valstr hFlush handle response <- hGetNetLn handle return (response == "STORED") getOneValue :: Handle -> IO (Maybe ByteString) getOneValue handle = do s <- hGetNetLn handle case words s of ["VALUE", _, _, sbytes] -> do let count = read sbytes val <- B.hGet handle count return $ Just val _ -> return Nothing incDec :: (Key k) => String -> Server -> k -> Int -> IO (Maybe Int) incDec cmd (Server handle) key delta = do hPutCommand handle [cmd, toKey key, show delta] response <- hGetNetLn handle case response of "NOT_FOUND" -> return Nothing x -> return $ Just (read x) instance Memcache Server where set = store "set" add = store "add" replace = store "replace" get (Server handle) key = do hPutCommand handle ["get", toKey key] val <- getOneValue handle case val of Nothing -> return Nothing Just val -> do hGetNetLn handle hGetNetLn handle return $ deserialize val delete (Server handle) key delta = do hPutCommand handle ["delete", toKey key, show delta] response <- hGetNetLn handle return (response == "DELETED") incr = incDec "incr" decr = incDec "decr" -- vim: set ts=2 sw=2 et :
olegkat/haskell-memcached
Network/Memcache/Protocol.hs
mit
3,675
0
15
889
1,252
624
628
88
3
module BrowserX.Webkit (browser) where import Graphics.UI.Gtk import Graphics.UI.Gtk.WebKit.WebView import Graphics.UI.Gtk.WebKit.WebFrame import BrowserX.Network -- | Internal browser fucntion. browser settings url = do initGUI window <- windowNew set window [windowTitle := "Browser-X"] windowSetDefaultSize window 900 600 windowSetPosition window WinPosCenter -- Create WebKit view. webView <- webViewNew webViewSetMaintainsBackForwardList webView True -- Create window boxes. winBox <- vBoxNew False 0 topBox <- hBoxNew False 0 -- Create address bar. addressBar <- entryNew -- Create toolbar. home <- actionNew "HOME" "Home" (Just "") (Just stockHome) back <- actionNew "BACK" "Back" (Just "") (Just stockGoBack) forw <- actionNew "FORW" "Forward" (Just "") (Just stockGoForward) relo <- actionNew "RELO" "Reload" (Just "") (Just stockRedo) save <- actionNew "SAVE" "Save" (Just "") (Just stockSave) exit <- actionNew "EXIT" "Exit" (Just "") (Just stockQuit) agr <- actionGroupNew "AGR" mapM_ (\act -> actionGroupAddActionWithAccel agr act Nothing)[home,back,forw,relo,save,exit] ui <- uiManagerNew uiManagerAddUiFromString ui uiDecl uiManagerInsertActionGroup ui agr 0 maybeToolbar <- uiManagerGetWidget ui "/ui/toolbar" let toolbar = case maybeToolbar of (Just x) -> x Nothing -> error "Cannot get toolbar" onActionActivate home (loadView webView addressBar settings "http://google.com") onActionActivate exit (widgetDestroy window) onActionActivate back (webViewGoBack webView) onActionActivate forw (webViewGoForward webView) onActionActivate relo (webViewReload webView) onActionActivate save (savedialog addressBar) -- Create scroll window. scrollWin <- scrolledWindowNew Nothing Nothing -- Load uri. do let furl = checkProtocol url loadView webView addressBar settings furl -- Open uri when user press `return` at address bar. onEntryActivate addressBar $ do uri <- entryGetText addressBar -- get uri from address bar let furi = checkProtocol uri loadView webView addressBar settings furi -- Add current uri to address bar when load start. webView `on` loadStarted $ \frame -> do currentUri <- webFrameGetUri frame case currentUri of Just uri -> let furi = checkProtocol uri in entrySetText addressBar furi Nothing -> return () -- Open all link in current window. webView `on` createWebView $ \frame -> do newUri <- webFrameGetUri frame case newUri of Just uri -> do let furi = checkProtocol uri loadView webView addressBar settings furi Nothing -> return () return webView -- Connect and show. boxPackStart topBox addressBar PackGrow 0 boxPackStart topBox toolbar PackGrow 0 boxPackStart winBox topBox PackNatural 0 boxPackStart winBox scrollWin PackGrow 0 window `containerAdd` winBox scrollWin `containerAdd` webView window `onDestroy` mainQuit widgetShowAll window mainGUI loadView webView addressBar settings url = do content <- fetchURL settings url entrySetText addressBar url webViewLoadHtmlString webView content url uiDecl= "<ui>\ \ <toolbar>\ \ <toolitem action=\"HOME\" />\ \ <separator />\ \ <toolitem action=\"BACK\" />\ \ <toolitem action=\"FORW\" />\ \ <separator />\ \ <toolitem action=\"RELO\" />\ \ <separator />\ \ <toolitem action=\"SAVE\" />\ \ <separator />\ \ <toolitem action=\"EXIT\" />\ \ </toolbar>\ \ </ui>" savedialog addressBar = do url <- entryGetText addressBar fchdal <- fileChooserDialogNew (Just "Save As..") Nothing FileChooserActionSave [("Cancel", ResponseCancel), ("Save", ResponseAccept)] fileChooserSetDoOverwriteConfirmation fchdal True widgetShow fchdal response <- dialogRun fchdal case response of ResponseCancel -> putStrLn "You cancelled." ResponseAccept -> do nwf <- fileChooserGetFilename fchdal case nwf of Nothing -> putStrLn "Nothing" Just path -> downloadfile url path ResponseDeleteEvent -> putStrLn "You closed the dialog window." widgetDestroy fchdal
igniting/browser-x
BrowserX/Webkit.hs
gpl-3.0
4,758
0
19
1,438
1,063
493
570
90
4
module Main where import Data.Int (Int16, Int32, Int64, Int8) import Data.Word (Word16, Word32, Word64, Word8) import Foreign.C.String (CString, withCString) import Foreign.C.Types (CInt (..), CSize (..)) import Foreign.Ptr (FunPtr, Ptr) -------------------------------------------------------------------------------- -- `tox.h` SHOULD *NOT* BE EDITED MANUALLY – any changes should be made to * -- `tox.api.h`, located in `toxcore/`. For instructions on how to * -- generate `tox.h` from `tox.api.h` please refer to `docs/apidsl.md` * -------------------------------------------------------------------------------- -- | \page core Public core API for Tox clients. -- -- Every function that can fail takes a function-specific error code pointer -- that can be used to diagnose problems with the Tox state or the function -- arguments. The error code pointer can be NULL, which does not influence the -- function's behaviour, but can be done if the reason for failure is irrelevant -- to the client. -- -- The exception to this rule are simple allocation functions whose only failure -- mode is allocation failure. They return NULL in that case, and do not set an -- error code. -- -- Every error code type has an OK value to which functions will set their error -- code value on success. Clients can keep their error code uninitialised before -- passing it to a function. The library guarantees that after returning, the -- value pointed to by the error code pointer has been initialised. -- -- Functions with pointer parameters often have a NULL error code, meaning they -- could not perform any operation, because one of the required parameters was -- NULL. Some functions operate correctly or are defined as effectless on NULL. -- -- Some functions additionally return a value outside their -- return type domain, or a bool containing true on success and false on -- failure. -- -- All functions that take a Tox instance pointer will cause undefined behaviour -- when passed a NULL Tox pointer. -- -- All integer values are expected in host byte order. -- -- Functions with parameters with enum types cause unspecified behaviour if the -- enumeration value is outside the valid range of the type. If possible, the -- function will try to use a sane default, but there will be no error code, -- and one possible action for the function to take is to have no effect. -- -- Integer constants and the memory layout of publicly exposed structs are not -- part of the ABI.-- | \subsection events Events and callbacks -- -- Events are handled by callbacks. One callback can be registered per event. -- All events have a callback function type named `tox_{event}_cb` and a -- function to register it named `tox_callback_{event}`. Passing a NULL -- callback will result in no callback being registered for that event. Only -- one callback per event can be registered, so if a client needs multiple -- event listeners, it needs to implement the dispatch functionality itself. -- -- The last argument to a callback is the user data pointer. It is passed from -- ${tox_iterate} to each callback in sequence. -- -- The user data pointer is never stored or dereferenced by any library code, so -- can be any pointer, including NULL. Callbacks must all operate on the same -- object type. In the apidsl code (tox.in.h), this is denoted with `any`. The -- `any` in ${tox_iterate} must be the same `any` as in all callbacks. In C, -- lacking parametric polymorphism, this is a pointer to void. -- -- Old style callbacks that are registered together with a user data pointer -- receive that pointer as argument when they are called. They can each have -- their own user data pointer of their own type.-- | \subsection threading Threading implications -- -- It is possible to run multiple concurrent threads with a Tox instance for -- each thread. It is also possible to run all Tox instances in the same thread. -- A common way to run Tox (multiple or single instance) is to have one thread -- running a simple ${tox_iterate} loop, sleeping for ${tox_iteration_interval} -- milliseconds on each iteration. -- -- If you want to access a single Tox instance from multiple threads, access -- to the instance must be synchronised. While multiple threads can concurrently -- access multiple different Tox instances, no more than one API function can -- operate on a single instance at any given time. -- -- Functions that write to variable length byte arrays will always have a size -- function associated with them. The result of this size function is only valid -- until another mutating function (one that takes a pointer to non-const Tox) -- is called. Thus, clients must ensure that no other thread calls a mutating -- function between the call to the size function and the call to the retrieval -- function. -- -- E.g. to get the current nickname, one would write -- -- \code -- ${CSize} length = ${tox_self_get_name_size}(tox); -- ${Word8} *name = malloc(length); -- if (!name) abort(); -- ${tox_self_get_name}(tox, name); -- \endcode -- -- If any other thread calls ${tox_self_set_name} while this thread is allocating -- memory, the length may have become invalid, and the call to -- ${tox_self_get_name} may cause undefined behaviour.-- | -- The Tox instance type. All the state associated with a connection is held -- within the instance. Multiple instances can exist and operate concurrently. -- The maximum number of Tox instances that can exist on a single network -- device is limited. Note that this is not just a per-process limit, since the -- limiting factor is the number of usable ports on a device. --struct Tox -------------------------------------------------------------------------------- -- -- :: API version -- -------------------------------------------------------------------------------- -- | -- The major version number. Incremented when the API or ABI changes in an -- incompatible way. -- -- The function variants of these constants return the version number of the -- library. They can be used to display the Tox library version or to check -- whether the client is compatible with the dynamically linked version of Tox. --const TOX_VERSION_MAJOR = 0 --foreign import ccall tox_version_major :: {- result :: -} Word32 -- | -- The minor version number. Incremented when functionality is added without -- breaking the API or ABI. Set to 0 when the major version number is -- incremented. --const TOX_VERSION_MINOR = 0 --foreign import ccall tox_version_minor :: {- result :: -} Word32 -- | -- The patch or revision number. Incremented when bugfixes are applied without -- changing any functionality or API or ABI. --const TOX_VERSION_PATCH = 5 --foreign import ccall tox_version_patch :: {- result :: -} Word32 -- | -- A macro to check at preprocessing time whether the client code is compatible -- with the installed version of Tox. #define TOX_VERSION_IS_API_COMPATIBLE(MAJOR, MINOR, PATCH) \ (TOX_VERSION_MAJOR == MAJOR && \ (TOX_VERSION_MINOR > MINOR || \ (TOX_VERSION_MINOR == MINOR && \ TOX_VERSION_PATCH >= PATCH))) -- | -- A macro to make compilation fail if the client code is not compatible with -- the installed version of Tox. #define TOX_VERSION_REQUIRE(MAJOR, MINOR, PATCH) \ typedef char tox_required_version[TOX_IS_COMPATIBLE(MAJOR, MINOR, PATCH) ? 1 : -1] -- | -- Return whether the compiled library version is compatible with the passed -- version numbers. --foreign import ccall tox_version_is_compatible :: {- major :: -} Word32 -> {- minor :: -} Word32 -> {- patch :: -} Word32 -> {- result :: -} Bool -- | -- A convenience macro to call tox_version_is_compatible with the currently -- compiling API version. #define TOX_VERSION_IS_ABI_COMPATIBLE() \ tox_version_is_compatible(TOX_VERSION_MAJOR, TOX_VERSION_MINOR, TOX_VERSION_PATCH) -------------------------------------------------------------------------------- -- -- :: Numeric constants -- -- The values of these are not part of the ABI. Prefer to use the function -- versions of them for code that should remain compatible with future versions -- of toxcore. -- -------------------------------------------------------------------------------- -- | -- The size of a Tox Public Key in bytes. --const TOX_PUBLIC_KEY_SIZE = 32 --foreign import ccall tox_public_key_size :: {- result :: -} Word32 -- | -- The size of a Tox Secret Key in bytes. --const TOX_SECRET_KEY_SIZE = 32 --foreign import ccall tox_secret_key_size :: {- result :: -} Word32 -- | -- The size of a Tox address in bytes. Tox addresses are in the format -- [Public Key (${TOX_PUBLIC_KEY_SIZE} bytes)][nospam (4 bytes)][checksum (2 bytes)]. -- -- The checksum is computed over the Public Key and the nospam value. The first -- byte is an XOR of all the even bytes (0, 2, 4, ...), the second byte is an -- XOR of all the odd bytes (1, 3, 5, ...) of the Public Key and nospam. --const TOX_ADDRESS_SIZE = (TOX_PUBLIC_KEY_SIZE + sizeof(Word32) + sizeof(Word16)) --foreign import ccall tox_address_size :: {- result :: -} Word32 -- | -- Maximum length of a nickname in bytes. --const TOX_MAX_NAME_LENGTH = 128 --foreign import ccall tox_max_name_length :: {- result :: -} Word32 -- | -- Maximum length of a status message in bytes. --const TOX_MAX_STATUS_MESSAGE_LENGTH = 1007 --foreign import ccall tox_max_status_message_length :: {- result :: -} Word32 -- | -- Maximum length of a friend request message in bytes. --const TOX_MAX_FRIEND_REQUEST_LENGTH = 1016 --foreign import ccall tox_max_friend_request_length :: {- result :: -} Word32 -- | -- Maximum length of a single message after which it should be split. --const TOX_MAX_MESSAGE_LENGTH = 1372 --foreign import ccall tox_max_message_length :: {- result :: -} Word32 -- | -- Maximum size of custom packets. TODO(iphydf): should be LENGTH? --const TOX_MAX_CUSTOM_PACKET_SIZE = 1373 --foreign import ccall tox_max_custom_packet_size :: {- result :: -} Word32 -- | -- The number of bytes in a hash generated by ${tox_hash}. --const TOX_HASH_LENGTH = 32 --foreign import ccall tox_hash_length :: {- result :: -} Word32 -- | -- The number of bytes in a file id. --const TOX_FILE_ID_LENGTH = 32 --foreign import ccall tox_file_id_length :: {- result :: -} Word32 -- | -- Maximum file name length for file transfers. --const TOX_MAX_FILENAME_LENGTH = 255 --foreign import ccall tox_max_filename_length :: {- result :: -} Word32 -------------------------------------------------------------------------------- -- -- :: Global enumerations -- -------------------------------------------------------------------------------- -- | -- Represents the possible statuses a client can have. data TOX_USER_STATUS = TOX_USER_STATUS_NONE -- ^ -- User is online and available. | TOX_USER_STATUS_AWAY -- ^ -- User is away. Clients can set this e.g. after a user defined -- inactivity time. | TOX_USER_STATUS_BUSY -- ^ -- User is busy. Signals to other clients that this client does not -- currently wish to communicate. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Represents message types for ${tox_friend_send_message} and conference -- messages. data TOX_MESSAGE_TYPE = TOX_MESSAGE_TYPE_NORMAL -- ^ -- Normal text message. Similar to PRIVMSG on IRC. | TOX_MESSAGE_TYPE_ACTION -- ^ -- A message describing an user action. This is similar to /me (CTCP ACTION) -- on IRC. deriving (Eq, Ord, Enum, Bounded, Read, Show) data TOX_ERR_ALLOC = TOX_ERR_ALLOC_OK -- ^ -- The function returned successfully. | TOX_ERR_ALLOC_MALLOC -- ^ -- The function failed to allocate enough memory for the data structure. deriving (Eq, Ord, Enum, Bounded, Read, Show) -------------------------------------------------------------------------------- -- -- :: Loading/saving of internal state -- -------------------------------------------------------------------------------- -- | -- Calculates the number of bytes required to store the tox instance with -- ${tox_get_savedata}. This function cannot fail. The result is always greater than 0. -- -- @see threading for concurrency implications. --foreign import ccall tox_get_savedata_size :: {- tox :: -} Ptr Tox -> {- result :: -} CSize -- | -- Store all information associated with the tox instance to a byte array. -- -- @param savedata A memory region large enough to store the tox instance -- data. Call ${tox_get_savedata_size} to find the number of bytes required. If this parameter -- is NULL, this function has no effect. --foreign import ccall tox_get_savedata :: {- tox :: -} Ptr Tox -> {- savedata :: -} Ptr (Word8{-[tox_get_savedata_size]-}) -> {- result :: -} () -- | -- Write an 8 bit unsigned integer. --typedef tox_saver_u08_cb = {- saver :: -} Ptr ToxSaver -> {- value :: -} Word8 -> {- user_data :: -} <unresolved> -> () -- | -- Write a 16 bit unsigned integer. --typedef tox_saver_u16_cb = {- saver :: -} Ptr ToxSaver -> {- value :: -} Word16 -> {- user_data :: -} <unresolved> -> () -- | -- Write a 32 bit unsigned integer. --typedef tox_saver_u32_cb = {- saver :: -} Ptr ToxSaver -> {- value :: -} Word32 -> {- user_data :: -} <unresolved> -> () -- | -- Write a 64 bit unsigned integer. --typedef tox_saver_u64_cb = {- saver :: -} Ptr ToxSaver -> {- value :: -} Word64 -> {- user_data :: -} <unresolved> -> () -- | -- Write an array of the given length. This call is followed by exactly -- `elements` calls to other functions. Arrays may be nested, so each -- element of the array may be another call to ${tox_saver_arr_cb} with its own element -- count and subsequent calls. --typedef tox_saver_arr_cb = {- saver :: -} Ptr ToxSaver -> {- elements :: -} CSize -> {- user_data :: -} <unresolved> -> () -- | -- Write a list of key/value pairs. A call to this function is followed by -- `elements * 2` calls to other functions. Every other call is either key -- or value. Keys can be assumed to be unique. --typedef tox_saver_map_cb = {- saver :: -} Ptr ToxSaver -> {- elements :: -} CSize -> {- user_data :: -} <unresolved> -> () -- | -- Write a byte array of a given length. --typedef tox_saver_bin_cb = {- saver :: -} Ptr ToxSaver -> {- data :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- user_data :: -} <unresolved> -> () -- | -- This struct contains callbacks for the save function. You will probably -- want to implement all callbacks to produce a useful result. data ToxSaver = ToxSaver { u08 :: Ptr tox_saver_u08_cb, u16 :: Ptr tox_saver_u16_cb, u32 :: Ptr tox_saver_u32_cb, u64 :: Ptr tox_saver_u64_cb, arr :: Ptr tox_saver_arr_cb, map :: Ptr tox_saver_map_cb, bin :: Ptr tox_saver_bin_cb} --foreign import ccall tox_saver_get_u08 :: {- saver :: -} Ptr ToxSaver -> {- result :: -} Ptr tox_saver_u08_cb --foreign import ccall tox_saver_set_u08 :: {- saver :: -} Ptr ToxSaver -> {- u08 :: -} Ptr tox_saver_u08_cb -> {- result :: -} () --foreign import ccall tox_saver_get_u16 :: {- saver :: -} Ptr ToxSaver -> {- result :: -} Ptr tox_saver_u16_cb --foreign import ccall tox_saver_set_u16 :: {- saver :: -} Ptr ToxSaver -> {- u16 :: -} Ptr tox_saver_u16_cb -> {- result :: -} () --foreign import ccall tox_saver_get_u32 :: {- saver :: -} Ptr ToxSaver -> {- result :: -} Ptr tox_saver_u32_cb --foreign import ccall tox_saver_set_u32 :: {- saver :: -} Ptr ToxSaver -> {- u32 :: -} Ptr tox_saver_u32_cb -> {- result :: -} () --foreign import ccall tox_saver_get_u64 :: {- saver :: -} Ptr ToxSaver -> {- result :: -} Ptr tox_saver_u64_cb --foreign import ccall tox_saver_set_u64 :: {- saver :: -} Ptr ToxSaver -> {- u64 :: -} Ptr tox_saver_u64_cb -> {- result :: -} () --foreign import ccall tox_saver_get_arr :: {- saver :: -} Ptr ToxSaver -> {- result :: -} Ptr tox_saver_arr_cb --foreign import ccall tox_saver_set_arr :: {- saver :: -} Ptr ToxSaver -> {- arr :: -} Ptr tox_saver_arr_cb -> {- result :: -} () --foreign import ccall tox_saver_get_map :: {- saver :: -} Ptr ToxSaver -> {- result :: -} Ptr tox_saver_map_cb --foreign import ccall tox_saver_set_map :: {- saver :: -} Ptr ToxSaver -> {- map :: -} Ptr tox_saver_map_cb -> {- result :: -} () --foreign import ccall tox_saver_get_bin :: {- saver :: -} Ptr ToxSaver -> {- result :: -} Ptr tox_saver_bin_cb --foreign import ccall tox_saver_set_bin :: {- saver :: -} Ptr ToxSaver -> {- bin :: -} Ptr tox_saver_bin_cb -> {- result :: -} () -- | -- Allocates a new ${ToxSaver} object and initialises it with the default -- handlers. -- -- Objects returned from this function must be freed using the ${tox_saver_free} -- function. -- -- @return A new ${ToxSaver} object with default options or NULL on failure. --foreign import ccall tox_saver_new :: {- error :: -} Ptr TOX_ERR_ALLOC -> {- result :: -} Ptr ToxSaver -- | -- Releases all resources associated with a saver objects. -- -- Passing a pointer that was not returned by ${tox_saver_new} results in -- undefined behaviour. --foreign import ccall tox_saver_free :: {- saver :: -} Ptr ToxSaver -> {- result :: -} () --foreign import ccall tox_save :: {- tox :: -} Ptr Tox -> {- saver :: -} Ptr ToxSaver -> {- user_data :: -} <unresolved> -> {- result :: -} () -- | -- Read an 8 bit unsigned integer. --typedef tox_loader_u08_cb = {- loader :: -} Ptr ToxLoader -> {- user_data :: -} <unresolved> -> Word8 -- | -- Read a 16 bit unsigned integer. --typedef tox_loader_u16_cb = {- loader :: -} Ptr ToxLoader -> {- user_data :: -} <unresolved> -> Word16 -- | -- Read a 32 bit unsigned integer. --typedef tox_loader_u32_cb = {- loader :: -} Ptr ToxLoader -> {- user_data :: -} <unresolved> -> Word32 -- | -- Read a 64 bit unsigned integer. --typedef tox_loader_u64_cb = {- loader :: -} Ptr ToxLoader -> {- user_data :: -} <unresolved> -> Word64 -- | -- Read the an array length. This call is followed by exactly the returned -- number calls to other functions. --typedef tox_loader_arr_cb = {- loader :: -} Ptr ToxLoader -> {- user_data :: -} <unresolved> -> CSize -- | -- Read the length of the list of key/value pairs. A call to this function -- is followed by twice the returned number of calls to other functions. -- Every other call is either key or value. --typedef tox_loader_map_cb = {- loader :: -} Ptr ToxLoader -> {- user_data :: -} <unresolved> -> CSize -- | -- Read a byte array of a given length. --typedef tox_loader_bin_cb = {- loader :: -} Ptr ToxLoader -> {- data :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- user_data :: -} <unresolved> -> () -- | -- This struct contains callbacks for the load function. You will probably -- want to implement all callbacks to produce a useful result. data ToxLoader = ToxLoader { u08 :: Ptr tox_loader_u08_cb, u16 :: Ptr tox_loader_u16_cb, u32 :: Ptr tox_loader_u32_cb, u64 :: Ptr tox_loader_u64_cb, arr :: Ptr tox_loader_arr_cb, map :: Ptr tox_loader_map_cb, bin :: Ptr tox_loader_bin_cb} --foreign import ccall tox_loader_get_u08 :: {- loader :: -} Ptr ToxLoader -> {- result :: -} Ptr tox_loader_u08_cb --foreign import ccall tox_loader_set_u08 :: {- loader :: -} Ptr ToxLoader -> {- u08 :: -} Ptr tox_loader_u08_cb -> {- result :: -} () --foreign import ccall tox_loader_get_u16 :: {- loader :: -} Ptr ToxLoader -> {- result :: -} Ptr tox_loader_u16_cb --foreign import ccall tox_loader_set_u16 :: {- loader :: -} Ptr ToxLoader -> {- u16 :: -} Ptr tox_loader_u16_cb -> {- result :: -} () --foreign import ccall tox_loader_get_u32 :: {- loader :: -} Ptr ToxLoader -> {- result :: -} Ptr tox_loader_u32_cb --foreign import ccall tox_loader_set_u32 :: {- loader :: -} Ptr ToxLoader -> {- u32 :: -} Ptr tox_loader_u32_cb -> {- result :: -} () --foreign import ccall tox_loader_get_u64 :: {- loader :: -} Ptr ToxLoader -> {- result :: -} Ptr tox_loader_u64_cb --foreign import ccall tox_loader_set_u64 :: {- loader :: -} Ptr ToxLoader -> {- u64 :: -} Ptr tox_loader_u64_cb -> {- result :: -} () --foreign import ccall tox_loader_get_arr :: {- loader :: -} Ptr ToxLoader -> {- result :: -} Ptr tox_loader_arr_cb --foreign import ccall tox_loader_set_arr :: {- loader :: -} Ptr ToxLoader -> {- arr :: -} Ptr tox_loader_arr_cb -> {- result :: -} () --foreign import ccall tox_loader_get_map :: {- loader :: -} Ptr ToxLoader -> {- result :: -} Ptr tox_loader_map_cb --foreign import ccall tox_loader_set_map :: {- loader :: -} Ptr ToxLoader -> {- map :: -} Ptr tox_loader_map_cb -> {- result :: -} () --foreign import ccall tox_loader_get_bin :: {- loader :: -} Ptr ToxLoader -> {- result :: -} Ptr tox_loader_bin_cb --foreign import ccall tox_loader_set_bin :: {- loader :: -} Ptr ToxLoader -> {- bin :: -} Ptr tox_loader_bin_cb -> {- result :: -} () -- | -- Allocates a new ${ToxLoader} object and initialises it with the default -- handlers. -- -- Objects returned from this function must be freed using the ${tox_loader_free} -- function. -- -- @return A new ${ToxLoader} object with default options or NULL on failure. --foreign import ccall tox_loader_new :: {- error :: -} Ptr TOX_ERR_ALLOC -> {- result :: -} Ptr ToxLoader -- | -- Releases all resources associated with a loader objects. -- -- Passing a pointer that was not returned by ${tox_loader_new} results in -- undefined behaviour. --foreign import ccall tox_loader_free :: {- loader :: -} Ptr ToxLoader -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: Startup options -- -------------------------------------------------------------------------------- -- | -- Type of proxy used to connect to TCP relays. data TOX_PROXY_TYPE = TOX_PROXY_TYPE_NONE -- ^ -- Don't use a proxy. | TOX_PROXY_TYPE_HTTP -- ^ -- HTTP proxy using CONNECT. | TOX_PROXY_TYPE_SOCKS5 -- ^ -- SOCKS proxy for simple socket pipes. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Type of savedata to create the Tox instance from. data TOX_SAVEDATA_TYPE = TOX_SAVEDATA_TYPE_NONE -- ^ -- No savedata. | TOX_SAVEDATA_TYPE_TOX_SAVE -- ^ -- Savedata is one that was obtained from ${tox_get_savedata}. | TOX_SAVEDATA_TYPE_SECRET_KEY -- ^ -- Savedata is a secret key of length ${TOX_SECRET_KEY_SIZE}. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Severity level of log messages. data TOX_LOG_LEVEL = TOX_LOG_LEVEL_TRACE -- ^ -- Very detailed traces including all network activity. | TOX_LOG_LEVEL_DEBUG -- ^ -- Debug messages such as which port we bind to. | TOX_LOG_LEVEL_INFO -- ^ -- Informational log messages such as video call status changes. | TOX_LOG_LEVEL_WARNING -- ^ -- Warnings about internal inconsistency or logic errors. | TOX_LOG_LEVEL_ERROR -- ^ -- Severe unexpected errors caused by external or internal inconsistency. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- This event is triggered when the toxcore library logs an internal message. -- This is mostly useful for debugging. This callback can be called from any -- function, not just ${tox_iterate}. This means the user data lifetime must at -- least extend between registering and unregistering it or ${tox_kill}. -- -- Other toxcore modules such as toxav may concurrently call this callback at -- any time. Thus, user code must make sure it is equipped to handle concurrent -- execution, e.g. by employing appropriate mutex locking. -- -- @param level The severity of the log message. -- @param file The source file from which the message originated. -- @param line The source line from which the message originated. -- @param func The function from which the message originated. -- @param message The log message. -- @param user_data The user data pointer passed to ${tox_new} in options. --typedef tox_log_cb = {- tox :: -} Ptr Tox -> {- level :: -} TOX_LOG_LEVEL -> {- file :: -} CString -> {- line :: -} Word32 -> {- func :: -} CString -> {- message :: -} CString -> {- user_data :: -} <unresolved> -> () -- | -- This struct contains all the startup options for Tox. You can either -- allocate this object yourself, and pass it to ${tox_options_default}, or call ${tox_options_new} to get -- a new default options object. -- -- If you allocate it yourself, be aware that your binary will rely on the -- memory layout of this struct. In particular, if additional fields are added -- in future versions of the API, code that allocates it itself will become -- incompatible. -- -- @deprecated The memory layout of this struct (size, alignment, and field -- order) is not part of the ABI. To remain compatible, prefer to use ${tox_options_new} to -- allocate the object and accessor functions to set the members. The struct -- will become opaque (i.e. the definition will become private) in v0.1.0. data ToxOptions = ToxOptions { ipv6Enabled :: Bool -- ^ -- The type of socket to create. -- -- If this is set to false, an IPv4 socket is created, which subsequently -- only allows IPv4 communication. -- If it is set to true, an IPv6 socket is created, allowing both IPv4 and -- IPv6 communication. , udpEnabled :: Bool -- ^ -- Enable the use of UDP communication when available. -- -- Setting this to false will force Tox to use TCP only. Communications will -- need to be relayed through a TCP relay node, potentially slowing them down. -- Disabling UDP support is necessary when using anonymous proxies or Tor. , proxyType :: TOX_PROXY_TYPE -- ^ -- Pass communications through a proxy. , proxyHost :: CString -- ^ -- The IP address or DNS name of the proxy to be used. -- -- If used, this must be non-NULL and be a valid DNS name. The name must not -- exceed 255 characters, and be in a NUL-terminated C string format -- (255 chars + 1 NUL byte). -- -- This member is ignored (it can be NULL) if ${proxyType} is ${TOX_PROXY_TYPE_NONE}. -- -- The data pointed at by this member is owned by the user, so must -- outlive the options object. , proxyPort :: Word16 -- ^ -- The port to use to connect to the proxy server. -- -- Ports must be in the range (1, 65535). The value is ignored if -- ${proxyType} is ${TOX_PROXY_TYPE_NONE}. , startPort :: Word16 -- ^ -- The start port of the inclusive port range to attempt to use. -- -- If both ${startPort} and ${endPort} are 0, the default port range will be -- used: [33445, 33545]. -- -- If either ${startPort} or ${endPort} is 0 while the other is non-zero, the -- non-zero port will be the only port in the range. -- -- Having ${startPort} > ${endPort} will yield the same behavior as if ${startPort} -- and ${endPort} were swapped. , endPort :: Word16 -- ^ -- The end port of the inclusive port range to attempt to use. , tcpPort :: Word16 -- ^ -- The port to use for the TCP server (relay). If 0, the TCP server is -- disabled. -- -- Enabling it is not required for Tox to function properly. -- -- When enabled, your Tox instance can act as a TCP relay for other Tox -- instance. This leads to increased traffic, thus when writing a client -- it is recommended to enable TCP server only if the user has an option -- to disable it. , holePunchingEnabled :: Bool -- ^ -- Enables or disables UDP hole-punching in toxcore. (Default: enabled). , savedataType :: TOX_SAVEDATA_TYPE -- ^ -- The type of savedata to load from. , savedataData :: Ptr (Word8{-[savedataLength]-}) -- ^ -- The savedata. -- -- The data pointed at by this member is owned by the user, so must -- outlive the options object. , savedataLength :: CSize -- ^ -- The length of the ${savedataData} array. , logCallback :: Ptr tox_log_cb -- ^ -- Logging callback for the new tox instance. , logUserData :: <unresolved> -- ^ -- User data pointer passed to the logging callback. , loadCallbacks :: Ptr ToxLoader -- ^ -- An implementation of the loader interface specified in ${ToxLoader}. , loadUserData :: <unresolved> -- ^ -- User data pointer passed to each of the loader callbacks. } --foreign import ccall tox_options_get_ipv6_enabled :: {- options :: -} Ptr ToxOptions -> {- result :: -} Bool --foreign import ccall tox_options_set_ipv6_enabled :: {- options :: -} Ptr ToxOptions -> {- ipv6_enabled :: -} Bool -> {- result :: -} () --foreign import ccall tox_options_get_udp_enabled :: {- options :: -} Ptr ToxOptions -> {- result :: -} Bool --foreign import ccall tox_options_set_udp_enabled :: {- options :: -} Ptr ToxOptions -> {- udp_enabled :: -} Bool -> {- result :: -} () --foreign import ccall tox_options_get_proxy_type :: {- options :: -} Ptr ToxOptions -> {- result :: -} TOX_PROXY_TYPE --foreign import ccall tox_options_set_proxy_type :: {- options :: -} Ptr ToxOptions -> {- type :: -} TOX_PROXY_TYPE -> {- result :: -} () --foreign import ccall tox_options_get_proxy_host :: {- options :: -} Ptr ToxOptions -> {- result :: -} CString --foreign import ccall tox_options_set_proxy_host :: {- options :: -} Ptr ToxOptions -> {- host :: -} CString -> {- result :: -} () --foreign import ccall tox_options_get_proxy_port :: {- options :: -} Ptr ToxOptions -> {- result :: -} Word16 --foreign import ccall tox_options_set_proxy_port :: {- options :: -} Ptr ToxOptions -> {- port :: -} Word16 -> {- result :: -} () --foreign import ccall tox_options_get_start_port :: {- options :: -} Ptr ToxOptions -> {- result :: -} Word16 --foreign import ccall tox_options_set_start_port :: {- options :: -} Ptr ToxOptions -> {- start_port :: -} Word16 -> {- result :: -} () --foreign import ccall tox_options_get_end_port :: {- options :: -} Ptr ToxOptions -> {- result :: -} Word16 --foreign import ccall tox_options_set_end_port :: {- options :: -} Ptr ToxOptions -> {- end_port :: -} Word16 -> {- result :: -} () --foreign import ccall tox_options_get_tcp_port :: {- options :: -} Ptr ToxOptions -> {- result :: -} Word16 --foreign import ccall tox_options_set_tcp_port :: {- options :: -} Ptr ToxOptions -> {- tcp_port :: -} Word16 -> {- result :: -} () --foreign import ccall tox_options_get_hole_punching_enabled :: {- options :: -} Ptr ToxOptions -> {- result :: -} Bool --foreign import ccall tox_options_set_hole_punching_enabled :: {- options :: -} Ptr ToxOptions -> {- hole_punching_enabled :: -} Bool -> {- result :: -} () --foreign import ccall tox_options_get_savedata_type :: {- options :: -} Ptr ToxOptions -> {- result :: -} TOX_SAVEDATA_TYPE --foreign import ccall tox_options_set_savedata_type :: {- options :: -} Ptr ToxOptions -> {- type :: -} TOX_SAVEDATA_TYPE -> {- result :: -} () --foreign import ccall tox_options_get_savedata_data :: {- options :: -} Ptr ToxOptions -> {- result :: -} Ptr (Word8{-[<unresolved>]-}) --foreign import ccall tox_options_set_savedata_data :: {- options :: -} Ptr ToxOptions -> {- data :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- result :: -} () --foreign import ccall tox_options_get_savedata_length :: {- options :: -} Ptr ToxOptions -> {- result :: -} CSize --foreign import ccall tox_options_set_savedata_length :: {- options :: -} Ptr ToxOptions -> {- length :: -} CSize -> {- result :: -} () --foreign import ccall tox_options_get_log_callback :: {- options :: -} Ptr ToxOptions -> {- result :: -} Ptr tox_log_cb --foreign import ccall tox_options_set_log_callback :: {- options :: -} Ptr ToxOptions -> {- callback :: -} Ptr tox_log_cb -> {- result :: -} () --foreign import ccall tox_options_get_log_user_data :: {- options :: -} Ptr ToxOptions -> {- result :: -} <unresolved> --foreign import ccall tox_options_set_log_user_data :: {- options :: -} Ptr ToxOptions -> {- user_data :: -} <unresolved> -> {- result :: -} () --foreign import ccall tox_options_get_load_callbacks :: {- options :: -} Ptr ToxOptions -> {- result :: -} Ptr ToxLoader --foreign import ccall tox_options_set_load_callbacks :: {- options :: -} Ptr ToxOptions -> {- callbacks :: -} Ptr ToxLoader -> {- result :: -} () --foreign import ccall tox_options_get_load_user_data :: {- options :: -} Ptr ToxOptions -> {- result :: -} <unresolved> --foreign import ccall tox_options_set_load_user_data :: {- options :: -} Ptr ToxOptions -> {- user_data :: -} <unresolved> -> {- result :: -} () -- | -- Initialises a ${ToxOptions} object with the default options. -- -- The result of this function is independent of the original options. All -- values will be overwritten, no values will be read (so it is permissible -- to pass an uninitialised object). -- -- If options is NULL, this function has no effect. -- -- @param options An options object to be filled with default options. --foreign import ccall tox_options_default :: {- options :: -} Ptr ToxOptions -> {- result :: -} () -- | -- Allocates a new ${ToxOptions} object and initialises it with the default -- options. This function can be used to preserve long term ABI compatibility by -- giving the responsibility of allocation and deallocation to the Tox library. -- -- Objects returned from this function must be freed using the ${tox_options_free} -- function. -- -- @return A new ${ToxOptions} object with default options or NULL on failure. --foreign import ccall tox_options_new :: {- error :: -} Ptr TOX_ERR_ALLOC -> {- result :: -} Ptr ToxOptions -- | -- Releases all resources associated with an options objects. -- -- Passing a pointer that was not returned by ${tox_options_new} results in -- undefined behaviour. --foreign import ccall tox_options_free :: {- options :: -} Ptr ToxOptions -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: Creation and destruction -- -------------------------------------------------------------------------------- data TOX_ERR_NEW = TOX_ERR_NEW_OK -- ^ -- The function returned successfully. | TOX_ERR_NEW_NULL -- ^ -- One of the arguments to the function was NULL when it was not expected. | TOX_ERR_NEW_MALLOC -- ^ -- The function was unable to allocate enough memory to store the internal -- structures for the Tox object. | TOX_ERR_NEW_PORT_ALLOC -- ^ -- The function was unable to bind to a port. This may mean that all ports -- have already been bound, e.g. by other Tox instances, or it may mean -- a permission error. You may be able to gather more information from errno. | TOX_ERR_NEW_PROXY_BAD_TYPE -- ^ -- proxy_type was invalid. | TOX_ERR_NEW_PROXY_BAD_HOST -- ^ -- proxy_type was valid but the proxy_host passed had an invalid format -- or was NULL. | TOX_ERR_NEW_PROXY_BAD_PORT -- ^ -- proxy_type was valid, but the proxy_port was invalid. | TOX_ERR_NEW_PROXY_NOT_FOUND -- ^ -- The proxy address passed could not be resolved. | TOX_ERR_NEW_LOAD_ENCRYPTED -- ^ -- The byte array to be loaded contained an encrypted save. | TOX_ERR_NEW_LOAD_BAD_FORMAT -- ^ -- The data format was invalid. This can happen when loading data that was -- saved by an older version of Tox, or when the data has been corrupted. -- When loading from badly formatted data, some data may have been loaded, -- and the rest is discarded. Passing an invalid length parameter also -- causes this error. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- @brief Creates and initialises a new Tox instance with the options passed. -- -- This function will bring the instance into a valid state. Running the event -- loop with a new instance will operate correctly. -- -- If loading failed or succeeded only partially, the new or partially loaded -- instance is returned and an error code is set. -- -- @param options An options object as described above. If this parameter is -- NULL, the default options are used. -- -- @see ${tox_iterate} for the event loop. -- -- @return A new Tox instance pointer on success or NULL on failure. --foreign import ccall tox_new :: {- options :: -} Ptr ToxOptions -> {- error :: -} Ptr TOX_ERR_NEW -> {- result :: -} Ptr Tox -- | -- Releases all resources associated with the Tox instance and disconnects from -- the network. -- -- After calling this function, the Tox pointer becomes invalid. No other -- functions can be called, and the pointer value can no longer be read. --foreign import ccall tox_kill :: {- tox :: -} Ptr Tox -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: Connection lifecycle and event loop -- -------------------------------------------------------------------------------- data TOX_ERR_BOOTSTRAP = TOX_ERR_BOOTSTRAP_OK -- ^ -- The function returned successfully. | TOX_ERR_BOOTSTRAP_NULL -- ^ -- One of the arguments to the function was NULL when it was not expected. | TOX_ERR_BOOTSTRAP_BAD_HOST -- ^ -- The address could not be resolved to an IP address, or the IP address -- passed was invalid. | TOX_ERR_BOOTSTRAP_BAD_PORT -- ^ -- The port passed was invalid. The valid port range is (1, 65535). deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Sends a "get nodes" request to the given bootstrap node with IP, port, and -- public key to setup connections. -- -- This function will attempt to connect to the node using UDP. You must use -- this function even if ${ToxOptions}.${udpEnabled} was set to false. -- -- @param address The hostname or IP address (IPv4 or IPv6) of the node. -- @param port The port on the host on which the bootstrap Tox instance is -- listening. -- @param public_key The long term public key of the bootstrap node -- (${TOX_PUBLIC_KEY_SIZE} bytes). -- @return true on success. --foreign import ccall tox_bootstrap :: {- tox :: -} Ptr Tox -> {- address :: -} CString -> {- port :: -} Word16 -> {- public_key :: -} Ptr (Word8{-[TOX_PUBLIC_KEY_SIZE]-}) -> {- error :: -} Ptr TOX_ERR_BOOTSTRAP -> {- result :: -} Bool -- | -- Adds additional host:port pair as TCP relay. -- -- This function can be used to initiate TCP connections to different ports on -- the same bootstrap node, or to add TCP relays without using them as -- bootstrap nodes. -- -- @param address The hostname or IP address (IPv4 or IPv6) of the TCP relay. -- @param port The port on the host on which the TCP relay is listening. -- @param public_key The long term public key of the TCP relay -- (${TOX_PUBLIC_KEY_SIZE} bytes). -- @return true on success. --foreign import ccall tox_add_tcp_relay :: {- tox :: -} Ptr Tox -> {- address :: -} CString -> {- port :: -} Word16 -> {- public_key :: -} Ptr (Word8{-[TOX_PUBLIC_KEY_SIZE]-}) -> {- error :: -} Ptr TOX_ERR_BOOTSTRAP -> {- result :: -} Bool -- | -- Protocols that can be used to connect to the network or friends. data TOX_CONNECTION = TOX_CONNECTION_NONE -- ^ -- There is no connection. This instance, or the friend the state change is -- about, is now offline. | TOX_CONNECTION_TCP -- ^ -- A TCP connection has been established. For the own instance, this means it -- is connected through a TCP relay, only. For a friend, this means that the -- connection to that particular friend goes through a TCP relay. | TOX_CONNECTION_UDP -- ^ -- A UDP connection has been established. For the own instance, this means it -- is able to send UDP packets to DHT nodes, but may still be connected to -- a TCP relay. For a friend, this means that the connection to that -- particular friend was built using direct UDP packets. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Return whether we are connected to the DHT. The return value is equal to the -- last value received through the `${self_connection_status}` callback. --foreign import ccall tox_self_get_connection_status :: {- tox :: -} Ptr Tox -> {- result :: -} TOX_CONNECTION -- | -- @param connection_status Whether we are connected to the DHT. --typedef tox_self_connection_status_cb = {- tox :: -} Ptr Tox -> {- connection_status :: -} TOX_CONNECTION -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${self_connection_status}` event. Pass NULL to unset. -- -- This event is triggered whenever there is a change in the DHT connection -- state. When disconnected, a client may choose to call ${tox_bootstrap} again, to -- reconnect to the DHT. Note that this state may frequently change for short -- amounts of time. Clients should therefore not immediately bootstrap on -- receiving a disconnect. -- -- TODO(iphydf): how long should a client wait before bootstrapping again? --foreign import ccall tox_callback_self_connection_status :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_self_connection_status_cb -> {- result :: -} () -- | -- Return the time in milliseconds before ${tox_iterate}() should be called again -- for optimal performance. --foreign import ccall tox_iteration_interval :: {- tox :: -} Ptr Tox -> {- result :: -} Word32 -- | -- The main loop that needs to be run in intervals of ${tox_iteration_interval}() -- milliseconds. --foreign import ccall tox_iterate :: {- tox :: -} Ptr Tox -> {- user_data :: -} <unresolved> -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: Internal client information (Tox address/id) -- -------------------------------------------------------------------------------- -- | -- Writes the Tox friend address of the client to a byte array. The address is -- not in human-readable format. If a client wants to display the address, -- formatting is required. -- -- @param address A memory region of at least ${TOX_ADDRESS_SIZE} bytes. If this -- parameter is NULL, this function has no effect. -- @see ${TOX_ADDRESS_SIZE} for the address format. --foreign import ccall tox_self_get_address :: {- tox :: -} Ptr Tox -> {- address :: -} Ptr (Word8{-[TOX_ADDRESS_SIZE]-}) -> {- result :: -} () -- | -- Set the 4-byte nospam part of the address. This value is expected in host -- byte order. I.e. 0x12345678 will form the bytes [12, 34, 56, 78] in the -- nospam part of the Tox friend address. -- -- @param nospam Any 32 bit unsigned integer. --foreign import ccall tox_self_set_nospam :: {- tox :: -} Ptr Tox -> {- nospam :: -} Word32 -> {- result :: -} () -- | -- Get the 4-byte nospam part of the address. This value is returned in host -- byte order. --foreign import ccall tox_self_get_nospam :: {- tox :: -} Ptr Tox -> {- result :: -} Word32 -- | -- Copy the Tox Public Key (long term) from the Tox object. -- -- @param public_key A memory region of at least ${TOX_PUBLIC_KEY_SIZE} bytes. If -- this parameter is NULL, this function has no effect. --foreign import ccall tox_self_get_public_key :: {- tox :: -} Ptr Tox -> {- public_key :: -} Ptr (Word8{-[TOX_PUBLIC_KEY_SIZE]-}) -> {- result :: -} () -- | -- Copy the Tox Secret Key from the Tox object. -- -- @param secret_key A memory region of at least ${TOX_SECRET_KEY_SIZE} bytes. If -- this parameter is NULL, this function has no effect. --foreign import ccall tox_self_get_secret_key :: {- tox :: -} Ptr Tox -> {- secret_key :: -} Ptr (Word8{-[TOX_SECRET_KEY_SIZE]-}) -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: User-visible client information (nickname/status) -- -------------------------------------------------------------------------------- -- | -- Common error codes for all functions that set a piece of user-visible -- client information. data TOX_ERR_SET_INFO = TOX_ERR_SET_INFO_OK -- ^ -- The function returned successfully. | TOX_ERR_SET_INFO_NULL -- ^ -- One of the arguments to the function was NULL when it was not expected. | TOX_ERR_SET_INFO_TOO_LONG -- ^ -- Information length exceeded maximum permissible size. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Set the nickname for the Tox client. -- -- Nickname length cannot exceed ${TOX_MAX_NAME_LENGTH}. If length is 0, the name -- parameter is ignored (it can be NULL), and the nickname is set back to empty. -- -- @param name A byte array containing the new nickname. -- @param length The size of the name byte array. -- -- @return true on success. --foreign import ccall tox_self_set_name :: {- tox :: -} Ptr Tox -> {- name :: -} Ptr (Word8{-[length <= TOX_MAX_NAME_LENGTH]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_SET_INFO -> {- result :: -} Bool -- | -- Return the length of the current nickname as passed to ${tox_self_set_name}. -- -- If no nickname was set before calling this function, the name is empty, -- and this function returns 0. -- -- @see threading for concurrency implications. --foreign import ccall tox_self_get_name_size :: {- tox :: -} Ptr Tox -> {- result :: -} CSize -- | -- Write the nickname set by ${tox_self_set_name} to a byte array. -- -- If no nickname was set before calling this function, the name is empty, -- and this function has no effect. -- -- Call ${tox_self_get_name_size} to find out how much memory to allocate for -- the result. -- -- @param name A valid memory location large enough to hold the nickname. -- If this parameter is NULL, the function has no effect. --foreign import ccall tox_self_get_name :: {- tox :: -} Ptr Tox -> {- name :: -} Ptr (Word8{-[<unresolved> <= TOX_MAX_NAME_LENGTH]-}) -> {- result :: -} () -- | -- Set the client's status message. -- -- Status message length cannot exceed ${TOX_MAX_STATUS_MESSAGE_LENGTH}. If -- length is 0, the status parameter is ignored (it can be NULL), and the -- user status is set back to empty. --foreign import ccall tox_self_set_status_message :: {- tox :: -} Ptr Tox -> {- status_message :: -} Ptr (Word8{-[length <= TOX_MAX_STATUS_MESSAGE_LENGTH]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_SET_INFO -> {- result :: -} Bool -- | -- Return the length of the current status message as passed to ${tox_self_set_status_message}. -- -- If no status message was set before calling this function, the status -- is empty, and this function returns 0. -- -- @see threading for concurrency implications. --foreign import ccall tox_self_get_status_message_size :: {- tox :: -} Ptr Tox -> {- result :: -} CSize -- | -- Write the status message set by ${tox_self_set_status_message} to a byte array. -- -- If no status message was set before calling this function, the status is -- empty, and this function has no effect. -- -- Call ${tox_self_get_status_message_size} to find out how much memory to allocate for -- the result. -- -- @param status_message A valid memory location large enough to hold the -- status message. If this parameter is NULL, the function has no effect. --foreign import ccall tox_self_get_status_message :: {- tox :: -} Ptr Tox -> {- status_message :: -} Ptr (Word8{-[<unresolved> <= TOX_MAX_STATUS_MESSAGE_LENGTH]-}) -> {- result :: -} () -- | -- Set the client's user status. -- -- @param status One of the user statuses listed in the enumeration above. --foreign import ccall tox_self_set_status :: {- tox :: -} Ptr Tox -> {- status :: -} TOX_USER_STATUS -> {- result :: -} () -- | -- Returns the client's user status. --foreign import ccall tox_self_get_status :: {- tox :: -} Ptr Tox -> {- result :: -} TOX_USER_STATUS -------------------------------------------------------------------------------- -- -- :: Friend list management -- -------------------------------------------------------------------------------- data TOX_ERR_FRIEND_ADD = TOX_ERR_FRIEND_ADD_OK -- ^ -- The function returned successfully. | TOX_ERR_FRIEND_ADD_NULL -- ^ -- One of the arguments to the function was NULL when it was not expected. | TOX_ERR_FRIEND_ADD_TOO_LONG -- ^ -- The length of the friend request message exceeded -- ${TOX_MAX_FRIEND_REQUEST_LENGTH}. | TOX_ERR_FRIEND_ADD_NO_MESSAGE -- ^ -- The friend request message was empty. This, and the TOO_LONG code will -- never be returned from ${tox_friend_add_norequest}. | TOX_ERR_FRIEND_ADD_OWN_KEY -- ^ -- The friend address belongs to the sending client. | TOX_ERR_FRIEND_ADD_ALREADY_SENT -- ^ -- A friend request has already been sent, or the address belongs to a friend -- that is already on the friend list. | TOX_ERR_FRIEND_ADD_BAD_CHECKSUM -- ^ -- The friend address checksum failed. | TOX_ERR_FRIEND_ADD_SET_NEW_NOSPAM -- ^ -- The friend was already there, but the nospam value was different. | TOX_ERR_FRIEND_ADD_MALLOC -- ^ -- A memory allocation failed when trying to increase the friend list size. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Add a friend to the friend list and send a friend request. -- -- A friend request message must be at least 1 byte long and at most -- ${TOX_MAX_FRIEND_REQUEST_LENGTH}. -- -- Friend numbers are unique identifiers used in all functions that operate on -- friends. Once added, a friend number is stable for the lifetime of the Tox -- object. After saving the state and reloading it, the friend numbers may not -- be the same as before. Deleting a friend creates a gap in the friend number -- set, which is filled by the next adding of a friend. Any pattern in friend -- numbers should not be relied on. -- -- If more than INT32_MAX friends are added, this function causes undefined -- behaviour. -- -- @param address The address of the friend (returned by ${tox_self_get_address} of -- the friend you wish to add) it must be ${TOX_ADDRESS_SIZE} bytes. -- @param message The message that will be sent along with the friend request. -- @param length The length of the data byte array. -- -- @return the friend number on success, UINT32_MAX on failure. --foreign import ccall tox_friend_add :: {- tox :: -} Ptr Tox -> {- address :: -} Ptr (Word8{-[TOX_ADDRESS_SIZE]-}) -> {- message :: -} Ptr (Word8{-[length <= TOX_MAX_FRIEND_REQUEST_LENGTH]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_FRIEND_ADD -> {- result :: -} Word32 -- | -- Add a friend without sending a friend request. -- -- This function is used to add a friend in response to a friend request. If the -- client receives a friend request, it can be reasonably sure that the other -- client added this client as a friend, eliminating the need for a friend -- request. -- -- This function is also useful in a situation where both instances are -- controlled by the same entity, so that this entity can perform the mutual -- friend adding. In this case, there is no need for a friend request, either. -- -- @param public_key A byte array of length ${TOX_PUBLIC_KEY_SIZE} containing the -- Public Key (not the Address) of the friend to add. -- -- @return the friend number on success, UINT32_MAX on failure. -- @see ${tox_friend_add} for a more detailed description of friend numbers. --foreign import ccall tox_friend_add_norequest :: {- tox :: -} Ptr Tox -> {- public_key :: -} Ptr (Word8{-[TOX_PUBLIC_KEY_SIZE]-}) -> {- error :: -} Ptr TOX_ERR_FRIEND_ADD -> {- result :: -} Word32 data TOX_ERR_FRIEND_DELETE = TOX_ERR_FRIEND_DELETE_OK -- ^ -- The function returned successfully. | TOX_ERR_FRIEND_DELETE_FRIEND_NOT_FOUND -- ^ -- There was no friend with the given friend number. No friends were deleted. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Remove a friend from the friend list. -- -- This does not notify the friend of their deletion. After calling this -- function, this client will appear offline to the friend and no communication -- can occur between the two. -- -- @param friend_number Friend number for the friend to be deleted. -- -- @return true on success. --foreign import ccall tox_friend_delete :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_FRIEND_DELETE -> {- result :: -} Bool -------------------------------------------------------------------------------- -- -- :: Friend list queries -- -------------------------------------------------------------------------------- data TOX_ERR_FRIEND_BY_PUBLIC_KEY = TOX_ERR_FRIEND_BY_PUBLIC_KEY_OK -- ^ -- The function returned successfully. | TOX_ERR_FRIEND_BY_PUBLIC_KEY_NULL -- ^ -- One of the arguments to the function was NULL when it was not expected. | TOX_ERR_FRIEND_BY_PUBLIC_KEY_NOT_FOUND -- ^ -- No friend with the given Public Key exists on the friend list. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Return the friend number associated with that Public Key. -- -- @return the friend number on success, UINT32_MAX on failure. -- @param public_key A byte array containing the Public Key. --foreign import ccall tox_friend_by_public_key :: {- tox :: -} Ptr Tox -> {- public_key :: -} Ptr (Word8{-[TOX_PUBLIC_KEY_SIZE]-}) -> {- error :: -} Ptr TOX_ERR_FRIEND_BY_PUBLIC_KEY -> {- result :: -} Word32 -- | -- Checks if a friend with the given friend number exists and returns true if -- it does. --foreign import ccall tox_friend_exists :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- result :: -} Bool -- | -- Return the number of friends on the friend list. -- -- This function can be used to determine how much memory to allocate for -- ${tox_self_get_friend_list}. --foreign import ccall tox_self_get_friend_list_size :: {- tox :: -} Ptr Tox -> {- result :: -} CSize -- | -- Copy a list of valid friend numbers into an array. -- -- Call ${tox_self_get_friend_list_size} to determine the number of elements to allocate. -- -- @param friend_list A memory region with enough space to hold the friend -- list. If this parameter is NULL, this function has no effect. --foreign import ccall tox_self_get_friend_list :: {- tox :: -} Ptr Tox -> {- friend_list :: -} Ptr (Word32{-[tox_self_get_friend_list_size]-}) -> {- result :: -} () data TOX_ERR_FRIEND_GET_PUBLIC_KEY = TOX_ERR_FRIEND_GET_PUBLIC_KEY_OK -- ^ -- The function returned successfully. | TOX_ERR_FRIEND_GET_PUBLIC_KEY_FRIEND_NOT_FOUND -- ^ -- No friend with the given number exists on the friend list. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Copies the Public Key associated with a given friend number to a byte array. -- -- @param friend_number The friend number you want the Public Key of. -- @param public_key A memory region of at least ${TOX_PUBLIC_KEY_SIZE} bytes. If -- this parameter is NULL, this function has no effect. -- -- @return true on success. --foreign import ccall tox_friend_get_public_key :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- public_key :: -} Ptr (Word8{-[TOX_PUBLIC_KEY_SIZE]-}) -> {- error :: -} Ptr TOX_ERR_FRIEND_GET_PUBLIC_KEY -> {- result :: -} Bool data TOX_ERR_FRIEND_GET_LAST_ONLINE = TOX_ERR_FRIEND_GET_LAST_ONLINE_OK -- ^ -- The function returned successfully. | TOX_ERR_FRIEND_GET_LAST_ONLINE_FRIEND_NOT_FOUND -- ^ -- No friend with the given number exists on the friend list. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Return a unix-time timestamp of the last time the friend associated with a given -- friend number was seen online. This function will return UINT64_MAX on error. -- -- @param friend_number The friend number you want to query. --foreign import ccall tox_friend_get_last_online :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_FRIEND_GET_LAST_ONLINE -> {- result :: -} Word64 -------------------------------------------------------------------------------- -- -- :: Friend-specific state queries (can also be received through callbacks) -- -------------------------------------------------------------------------------- -- | -- Common error codes for friend state query functions. data TOX_ERR_FRIEND_QUERY = TOX_ERR_FRIEND_QUERY_OK -- ^ -- The function returned successfully. | TOX_ERR_FRIEND_QUERY_NULL -- ^ -- The pointer parameter for storing the query result (name, message) was -- NULL. Unlike the `_self_` variants of these functions, which have no effect -- when a parameter is NULL, these functions return an error in that case. | TOX_ERR_FRIEND_QUERY_FRIEND_NOT_FOUND -- ^ -- The friend_number did not designate a valid friend. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Return the length of the friend's name. If the friend number is invalid, the -- return value is unspecified. -- -- The return value is equal to the `length` argument received by the last -- `${friend_name}` callback. --foreign import ccall tox_friend_get_name_size :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_FRIEND_QUERY -> {- result :: -} CSize -- | -- Write the name of the friend designated by the given friend number to a byte -- array. -- -- Call ${tox_friend_get_name_size} to determine the allocation size for the `name` -- parameter. -- -- The data written to `name` is equal to the data received by the last -- `${friend_name}` callback. -- -- @param name A valid memory region large enough to store the friend's name. -- -- @return true on success. --foreign import ccall tox_friend_get_name :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- name :: -} Ptr (Word8{-[<unresolved> <= TOX_MAX_NAME_LENGTH]-}) -> {- error :: -} Ptr TOX_ERR_FRIEND_QUERY -> {- result :: -} Bool -- | -- @param friend_number The friend number of the friend whose name changed. -- @param name A byte array containing the same data as -- ${tox_friend_get_name} would write to its `name` parameter. -- @param length A value equal to the return value of -- ${tox_friend_get_name_size}. --typedef tox_friend_name_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- name :: -} Ptr (Word8{-[length <= TOX_MAX_NAME_LENGTH]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_name}` event. Pass NULL to unset. -- -- This event is triggered when a friend changes their name. --foreign import ccall tox_callback_friend_name :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_name_cb -> {- result :: -} () -- | -- Return the length of the friend's status message. If the friend number is -- invalid, the return value is SIZE_MAX. --foreign import ccall tox_friend_get_status_message_size :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_FRIEND_QUERY -> {- result :: -} CSize -- | -- Write the status message of the friend designated by the given friend number to a byte -- array. -- -- Call ${tox_friend_get_status_message_size} to determine the allocation size for the `status_name` -- parameter. -- -- The data written to `status_message` is equal to the data received by the last -- `${friend_status_message}` callback. -- -- @param status_message A valid memory region large enough to store the friend's status message. --foreign import ccall tox_friend_get_status_message :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- status_message :: -} Ptr (Word8{-[<unresolved> <= TOX_MAX_STATUS_MESSAGE_LENGTH]-}) -> {- error :: -} Ptr TOX_ERR_FRIEND_QUERY -> {- result :: -} Bool -- | -- @param friend_number The friend number of the friend whose status message -- changed. -- @param message A byte array containing the same data as -- ${tox_friend_get_status_message} would write to its `status_message` parameter. -- @param length A value equal to the return value of -- ${tox_friend_get_status_message_size}. --typedef tox_friend_status_message_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- message :: -} Ptr (Word8{-[length <= TOX_MAX_STATUS_MESSAGE_LENGTH]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_status_message}` event. Pass NULL to unset. -- -- This event is triggered when a friend changes their status message. --foreign import ccall tox_callback_friend_status_message :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_status_message_cb -> {- result :: -} () -- | -- Return the friend's user status (away/busy/...). If the friend number is -- invalid, the return value is unspecified. -- -- The status returned is equal to the last status received through the -- `${friend_status}` callback. --foreign import ccall tox_friend_get_status :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_FRIEND_QUERY -> {- result :: -} TOX_USER_STATUS -- | -- @param friend_number The friend number of the friend whose user status -- changed. -- @param status The new user status. --typedef tox_friend_status_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- status :: -} TOX_USER_STATUS -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_status}` event. Pass NULL to unset. -- -- This event is triggered when a friend changes their user status. --foreign import ccall tox_callback_friend_status :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_status_cb -> {- result :: -} () -- | -- Check whether a friend is currently connected to this client. -- -- The result of this function is equal to the last value received by the -- `${friend_connection_status}` callback. -- -- @param friend_number The friend number for which to query the connection -- status. -- -- @return the friend's connection status as it was received through the -- `${friend_connection_status}` event. --foreign import ccall tox_friend_get_connection_status :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_FRIEND_QUERY -> {- result :: -} TOX_CONNECTION -- | -- @param friend_number The friend number of the friend whose connection status -- changed. -- @param connection_status The result of calling -- ${tox_friend_get_connection_status} on the passed friend_number. --typedef tox_friend_connection_status_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- connection_status :: -} TOX_CONNECTION -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_connection_status}` event. Pass NULL to unset. -- -- This event is triggered when a friend goes offline after having been online, -- or when a friend goes online. -- -- This callback is not called when adding friends. It is assumed that when -- adding friends, their connection status is initially offline. --foreign import ccall tox_callback_friend_connection_status :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_connection_status_cb -> {- result :: -} () -- | -- Check whether a friend is currently typing a message. -- -- @param friend_number The friend number for which to query the typing status. -- -- @return true if the friend is typing. -- @return false if the friend is not typing, or the friend number was -- invalid. Inspect the error code to determine which case it is. --foreign import ccall tox_friend_get_typing :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_FRIEND_QUERY -> {- result :: -} Bool -- | -- @param friend_number The friend number of the friend who started or stopped -- typing. -- @param is_typing The result of calling ${tox_friend_get_typing} on the passed -- friend_number. --typedef tox_friend_typing_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- is_typing :: -} Bool -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_typing}` event. Pass NULL to unset. -- -- This event is triggered when a friend starts or stops typing. --foreign import ccall tox_callback_friend_typing :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_typing_cb -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: Sending private messages -- -------------------------------------------------------------------------------- data TOX_ERR_SET_TYPING = TOX_ERR_SET_TYPING_OK -- ^ -- The function returned successfully. | TOX_ERR_SET_TYPING_FRIEND_NOT_FOUND -- ^ -- The friend number did not designate a valid friend. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Set the client's typing status for a friend. -- -- The client is responsible for turning it on or off. -- -- @param friend_number The friend to which the client is typing a message. -- @param typing The typing status. True means the client is typing. -- -- @return true on success. --foreign import ccall tox_self_set_typing :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- typing :: -} Bool -> {- error :: -} Ptr TOX_ERR_SET_TYPING -> {- result :: -} Bool data TOX_ERR_FRIEND_SEND_MESSAGE = TOX_ERR_FRIEND_SEND_MESSAGE_OK -- ^ -- The function returned successfully. | TOX_ERR_FRIEND_SEND_MESSAGE_NULL -- ^ -- One of the arguments to the function was NULL when it was not expected. | TOX_ERR_FRIEND_SEND_MESSAGE_FRIEND_NOT_FOUND -- ^ -- The friend number did not designate a valid friend. | TOX_ERR_FRIEND_SEND_MESSAGE_FRIEND_NOT_CONNECTED -- ^ -- This client is currently not connected to the friend. | TOX_ERR_FRIEND_SEND_MESSAGE_SENDQ -- ^ -- An allocation error occurred while increasing the send queue size. | TOX_ERR_FRIEND_SEND_MESSAGE_TOO_LONG -- ^ -- Message length exceeded ${TOX_MAX_MESSAGE_LENGTH}. | TOX_ERR_FRIEND_SEND_MESSAGE_EMPTY -- ^ -- Attempted to send a zero-length message. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Send a text chat message to an online friend. -- -- This function creates a chat message packet and pushes it into the send -- queue. -- -- The message length may not exceed ${TOX_MAX_MESSAGE_LENGTH}. Larger messages -- must be split by the client and sent as separate messages. Other clients can -- then reassemble the fragments. Messages may not be empty. -- -- The return value of this function is the message ID. If a read receipt is -- received, the triggered `${friend_read_receipt}` event will be passed this message ID. -- -- Message IDs are unique per friend. The first message ID is 0. Message IDs are -- incremented by 1 each time a message is sent. If UINT32_MAX messages were -- sent, the next message ID is 0. -- -- @param type Message type (normal, action, ...). -- @param friend_number The friend number of the friend to send the message to. -- @param message A non-NULL pointer to the first element of a byte array -- containing the message text. -- @param length Length of the message to be sent. --foreign import ccall tox_friend_send_message :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- type :: -} TOX_MESSAGE_TYPE -> {- message :: -} Ptr (Word8{-[length <= TOX_MAX_MESSAGE_LENGTH]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_FRIEND_SEND_MESSAGE -> {- result :: -} Word32 -- | -- @param friend_number The friend number of the friend who received the message. -- @param message_id The message ID as returned from ${tox_friend_send_message} -- corresponding to the message sent. --typedef tox_friend_read_receipt_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- message_id :: -} Word32 -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_read_receipt}` event. Pass NULL to unset. -- -- This event is triggered when the friend receives the message sent with -- ${tox_friend_send_message} with the corresponding message ID. --foreign import ccall tox_callback_friend_read_receipt :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_read_receipt_cb -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: Receiving private messages and friend requests -- -------------------------------------------------------------------------------- -- | -- @param public_key The Public Key of the user who sent the friend request. -- @param message The message they sent along with the request. -- @param length The size of the message byte array. --typedef tox_friend_request_cb = {- tox :: -} Ptr Tox -> {- public_key :: -} Ptr (Word8{-[TOX_PUBLIC_KEY_SIZE]-}) -> {- message :: -} Ptr (Word8{-[length <= TOX_MAX_MESSAGE_LENGTH]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_request}` event. Pass NULL to unset. -- -- This event is triggered when a friend request is received. --foreign import ccall tox_callback_friend_request :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_request_cb -> {- result :: -} () -- | -- @param friend_number The friend number of the friend who sent the message. -- @param message The message data they sent. -- @param length The size of the message byte array. --typedef tox_friend_message_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- type :: -} TOX_MESSAGE_TYPE -> {- message :: -} Ptr (Word8{-[length <= TOX_MAX_MESSAGE_LENGTH]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_message}` event. Pass NULL to unset. -- -- This event is triggered when a message from a friend is received. --foreign import ccall tox_callback_friend_message :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_message_cb -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: File transmission: common between sending and receiving -- -------------------------------------------------------------------------------- -- | -- Generates a cryptographic hash of the given data. -- -- This function may be used by clients for any purpose, but is provided -- primarily for validating cached avatars. This use is highly recommended to -- avoid unnecessary avatar updates. -- -- If hash is NULL or data is NULL while length is not 0 the function returns false, -- otherwise it returns true. -- -- This function is a wrapper to internal message-digest functions. -- -- @param hash A valid memory location the hash data. It must be at least -- ${TOX_HASH_LENGTH} bytes in size. -- @param data Data to be hashed or NULL. -- @param length Size of the data array or 0. -- -- @return true if hash was not NULL. --foreign import ccall tox_hash :: {- hash :: -} Ptr (Word8{-[TOX_HASH_LENGTH]-}) -> {- data :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- result :: -} Bool data TOX_FILE_KIND = TOX_FILE_KIND_DATA -- ^ -- Arbitrary file data. Clients can choose to handle it based on the file name -- or magic or any other way they choose. | TOX_FILE_KIND_AVATAR -- ^ -- Avatar file_id. This consists of ${tox_hash}(image). -- Avatar data. This consists of the image data. -- -- Avatars can be sent at any time the client wishes. Generally, a client will -- send the avatar to a friend when that friend comes online, and to all -- friends when the avatar changed. A client can save some traffic by -- remembering which friend received the updated avatar already and only send -- it if the friend has an out of date avatar. -- -- Clients who receive avatar send requests can reject it (by sending -- ${TOX_FILE_CONTROL_CANCEL} before any other controls), or accept it (by -- sending ${TOX_FILE_CONTROL_RESUME}). The file_id of length ${TOX_HASH_LENGTH} bytes -- (same length as ${TOX_FILE_ID_LENGTH}) will contain the hash. A client can compare -- this hash with a saved hash and send ${TOX_FILE_CONTROL_CANCEL} to terminate the avatar -- transfer if it matches. -- -- When file_size is set to 0 in the transfer request it means that the client -- has no avatar. deriving (Eq, Ord, Enum, Bounded, Read, Show) data TOX_FILE_CONTROL = TOX_FILE_CONTROL_RESUME -- ^ -- Sent by the receiving side to accept a file send request. Also sent after a -- ${TOX_FILE_CONTROL_PAUSE} command to continue sending or receiving. | TOX_FILE_CONTROL_PAUSE -- ^ -- Sent by clients to pause the file transfer. The initial state of a file -- transfer is always paused on the receiving side and running on the sending -- side. If both the sending and receiving side pause the transfer, then both -- need to send ${TOX_FILE_CONTROL_RESUME} for the transfer to resume. | TOX_FILE_CONTROL_CANCEL -- ^ -- Sent by the receiving side to reject a file send request before any other -- commands are sent. Also sent by either side to terminate a file transfer. deriving (Eq, Ord, Enum, Bounded, Read, Show) data TOX_ERR_FILE_CONTROL = TOX_ERR_FILE_CONTROL_OK -- ^ -- The function returned successfully. | TOX_ERR_FILE_CONTROL_FRIEND_NOT_FOUND -- ^ -- The friend_number passed did not designate a valid friend. | TOX_ERR_FILE_CONTROL_FRIEND_NOT_CONNECTED -- ^ -- This client is currently not connected to the friend. | TOX_ERR_FILE_CONTROL_NOT_FOUND -- ^ -- No file transfer with the given file number was found for the given friend. | TOX_ERR_FILE_CONTROL_NOT_PAUSED -- ^ -- A RESUME control was sent, but the file transfer is running normally. | TOX_ERR_FILE_CONTROL_DENIED -- ^ -- A RESUME control was sent, but the file transfer was paused by the other -- party. Only the party that paused the transfer can resume it. | TOX_ERR_FILE_CONTROL_ALREADY_PAUSED -- ^ -- A PAUSE control was sent, but the file transfer was already paused. | TOX_ERR_FILE_CONTROL_SENDQ -- ^ -- Packet queue is full. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Sends a file control command to a friend for a given file transfer. -- -- @param friend_number The friend number of the friend the file is being -- transferred to or received from. -- @param file_number The friend-specific identifier for the file transfer. -- @param control The control command to send. -- -- @return true on success. --foreign import ccall tox_file_control :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- file_number :: -} Word32 -> {- control :: -} TOX_FILE_CONTROL -> {- error :: -} Ptr TOX_ERR_FILE_CONTROL -> {- result :: -} Bool -- | -- When receiving ${TOX_FILE_CONTROL_CANCEL}, the client should release the -- resources associated with the file number and consider the transfer failed. -- -- @param friend_number The friend number of the friend who is sending the file. -- @param file_number The friend-specific file number the data received is -- associated with. -- @param control The file control command received. --typedef tox_file_recv_control_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- file_number :: -} Word32 -> {- control :: -} TOX_FILE_CONTROL -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${file_recv_control}` event. Pass NULL to unset. -- -- This event is triggered when a file control command is received from a -- friend. --foreign import ccall tox_callback_file_recv_control :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_file_recv_control_cb -> {- result :: -} () data TOX_ERR_FILE_SEEK = TOX_ERR_FILE_SEEK_OK -- ^ -- The function returned successfully. | TOX_ERR_FILE_SEEK_FRIEND_NOT_FOUND -- ^ -- The friend_number passed did not designate a valid friend. | TOX_ERR_FILE_SEEK_FRIEND_NOT_CONNECTED -- ^ -- This client is currently not connected to the friend. | TOX_ERR_FILE_SEEK_NOT_FOUND -- ^ -- No file transfer with the given file number was found for the given friend. | TOX_ERR_FILE_SEEK_DENIED -- ^ -- File was not in a state where it could be seeked. | TOX_ERR_FILE_SEEK_INVALID_POSITION -- ^ -- Seek position was invalid | TOX_ERR_FILE_SEEK_SENDQ -- ^ -- Packet queue is full. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Sends a file seek control command to a friend for a given file transfer. -- -- This function can only be called to resume a file transfer right before -- ${TOX_FILE_CONTROL_RESUME} is sent. -- -- @param friend_number The friend number of the friend the file is being -- received from. -- @param file_number The friend-specific identifier for the file transfer. -- @param position The position that the file should be seeked to. --foreign import ccall tox_file_seek :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- file_number :: -} Word32 -> {- position :: -} Word64 -> {- error :: -} Ptr TOX_ERR_FILE_SEEK -> {- result :: -} Bool data TOX_ERR_FILE_GET = TOX_ERR_FILE_GET_OK -- ^ -- The function returned successfully. | TOX_ERR_FILE_GET_NULL -- ^ -- One of the arguments to the function was NULL when it was not expected. | TOX_ERR_FILE_GET_FRIEND_NOT_FOUND -- ^ -- The friend_number passed did not designate a valid friend. | TOX_ERR_FILE_GET_NOT_FOUND -- ^ -- No file transfer with the given file number was found for the given friend. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Copy the file id associated to the file transfer to a byte array. -- -- @param friend_number The friend number of the friend the file is being -- transferred to or received from. -- @param file_number The friend-specific identifier for the file transfer. -- @param file_id A memory region of at least ${TOX_FILE_ID_LENGTH} bytes. If -- this parameter is NULL, this function has no effect. -- -- @return true on success. --foreign import ccall tox_file_get_file_id :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- file_number :: -} Word32 -> {- file_id :: -} Ptr (Word8{-[TOX_FILE_ID_LENGTH]-}) -> {- error :: -} Ptr TOX_ERR_FILE_GET -> {- result :: -} Bool -------------------------------------------------------------------------------- -- -- :: File transmission: sending -- -------------------------------------------------------------------------------- data TOX_ERR_FILE_SEND = TOX_ERR_FILE_SEND_OK -- ^ -- The function returned successfully. | TOX_ERR_FILE_SEND_NULL -- ^ -- One of the arguments to the function was NULL when it was not expected. | TOX_ERR_FILE_SEND_FRIEND_NOT_FOUND -- ^ -- The friend_number passed did not designate a valid friend. | TOX_ERR_FILE_SEND_FRIEND_NOT_CONNECTED -- ^ -- This client is currently not connected to the friend. | TOX_ERR_FILE_SEND_NAME_TOO_LONG -- ^ -- Filename length exceeded ${TOX_MAX_FILENAME_LENGTH} bytes. | TOX_ERR_FILE_SEND_TOO_MANY -- ^ -- Too many ongoing transfers. The maximum number of concurrent file transfers -- is 256 per friend per direction (sending and receiving). deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Send a file transmission request. -- -- Maximum filename length is ${TOX_MAX_FILENAME_LENGTH} bytes. The filename -- should generally just be a file name, not a path with directory names. -- -- If a non-UINT64_MAX file size is provided, it can be used by both sides to -- determine the sending progress. File size can be set to UINT64_MAX for streaming -- data of unknown size. -- -- File transmission occurs in chunks, which are requested through the -- `${file_chunk_request}` event. -- -- When a friend goes offline, all file transfers associated with the friend are -- purged from core. -- -- If the file contents change during a transfer, the behaviour is unspecified -- in general. What will actually happen depends on the mode in which the file -- was modified and how the client determines the file size. -- -- - If the file size was increased -- - and sending mode was streaming (file_size = UINT64_MAX), the behaviour -- will be as expected. -- - and sending mode was file (file_size != UINT64_MAX), the -- ${file_chunk_request} callback will receive length = 0 when Core thinks -- the file transfer has finished. If the client remembers the file size as -- it was when sending the request, it will terminate the transfer normally. -- If the client re-reads the size, it will think the friend cancelled the -- transfer. -- - If the file size was decreased -- - and sending mode was streaming, the behaviour is as expected. -- - and sending mode was file, the callback will return 0 at the new -- (earlier) end-of-file, signalling to the friend that the transfer was -- cancelled. -- - If the file contents were modified -- - at a position before the current read, the two files (local and remote) -- will differ after the transfer terminates. -- - at a position after the current read, the file transfer will succeed as -- expected. -- - In either case, both sides will regard the transfer as complete and -- successful. -- -- @param friend_number The friend number of the friend the file send request -- should be sent to. -- @param kind The meaning of the file to be sent. -- @param file_size Size in bytes of the file the client wants to send, UINT64_MAX if -- unknown or streaming. -- @param file_id A file identifier of length ${TOX_FILE_ID_LENGTH} that can be used to -- uniquely identify file transfers across core restarts. If NULL, a random one will -- be generated by core. It can then be obtained by using ${tox_file_get_file_id}(). -- @param filename Name of the file. Does not need to be the actual name. This -- name will be sent along with the file send request. -- @param filename_length Size in bytes of the filename. -- -- @return A file number used as an identifier in subsequent callbacks. This -- number is per friend. File numbers are reused after a transfer terminates. -- On failure, this function returns UINT32_MAX. Any pattern in file numbers -- should not be relied on. --foreign import ccall tox_file_send :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- kind :: -} Word32 -> {- file_size :: -} Word64 -> {- file_id :: -} Ptr (Word8{-[TOX_FILE_ID_LENGTH]-}) -> {- filename :: -} Ptr (Word8{-[filename_length <= TOX_MAX_FILENAME_LENGTH]-}) -> {- filename_length :: -} CSize -> {- error :: -} Ptr TOX_ERR_FILE_SEND -> {- result :: -} Word32 data TOX_ERR_FILE_SEND_CHUNK = TOX_ERR_FILE_SEND_CHUNK_OK -- ^ -- The function returned successfully. | TOX_ERR_FILE_SEND_CHUNK_NULL -- ^ -- The length parameter was non-zero, but data was NULL. | TOX_ERR_FILE_SEND_CHUNK_FRIEND_NOT_FOUND -- ^ -- The friend_number passed did not designate a valid friend. | TOX_ERR_FILE_SEND_CHUNK_FRIEND_NOT_CONNECTED -- ^ -- This client is currently not connected to the friend. | TOX_ERR_FILE_SEND_CHUNK_NOT_FOUND -- ^ -- No file transfer with the given file number was found for the given friend. | TOX_ERR_FILE_SEND_CHUNK_NOT_TRANSFERRING -- ^ -- File transfer was found but isn't in a transferring state: (paused, done, -- broken, etc...) (happens only when not called from the request chunk callback). | TOX_ERR_FILE_SEND_CHUNK_INVALID_LENGTH -- ^ -- Attempted to send more or less data than requested. The requested data size is -- adjusted according to maximum transmission unit and the expected end of -- the file. Trying to send less or more than requested will return this error. | TOX_ERR_FILE_SEND_CHUNK_SENDQ -- ^ -- Packet queue is full. | TOX_ERR_FILE_SEND_CHUNK_WRONG_POSITION -- ^ -- Position parameter was wrong. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Send a chunk of file data to a friend. -- -- This function is called in response to the `${file_chunk_request}` callback. The -- length parameter should be equal to the one received though the callback. -- If it is zero, the transfer is assumed complete. For files with known size, -- Core will know that the transfer is complete after the last byte has been -- received, so it is not necessary (though not harmful) to send a zero-length -- chunk to terminate. For streams, core will know that the transfer is finished -- if a chunk with length less than the length requested in the callback is sent. -- -- @param friend_number The friend number of the receiving friend for this file. -- @param file_number The file transfer identifier returned by tox_file_send. -- @param position The file or stream position from which to continue reading. -- @return true on success. --foreign import ccall tox_file_send_chunk :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- file_number :: -} Word32 -> {- position :: -} Word64 -> {- data :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_FILE_SEND_CHUNK -> {- result :: -} Bool -- | -- If the length parameter is 0, the file transfer is finished, and the client's -- resources associated with the file number should be released. After a call -- with zero length, the file number can be reused for future file transfers. -- -- If the requested position is not equal to the client's idea of the current -- file or stream position, it will need to seek. In case of read-once streams, -- the client should keep the last read chunk so that a seek back can be -- supported. A seek-back only ever needs to read from the last requested chunk. -- This happens when a chunk was requested, but the send failed. A seek-back -- request can occur an arbitrary number of times for any given chunk. -- -- In response to receiving this callback, the client should call the function -- `${tox_file_send_chunk}` with the requested chunk. If the number of bytes sent -- through that function is zero, the file transfer is assumed complete. A -- client must send the full length of data requested with this callback. -- -- @param friend_number The friend number of the receiving friend for this file. -- @param file_number The file transfer identifier returned by ${tox_file_send}. -- @param position The file or stream position from which to continue reading. -- @param length The number of bytes requested for the current chunk. --typedef tox_file_chunk_request_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- file_number :: -} Word32 -> {- position :: -} Word64 -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${file_chunk_request}` event. Pass NULL to unset. -- -- This event is triggered when Core is ready to send more file data. --foreign import ccall tox_callback_file_chunk_request :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_file_chunk_request_cb -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: File transmission: receiving -- -------------------------------------------------------------------------------- -- | -- The client should acquire resources to be associated with the file transfer. -- Incoming file transfers start in the PAUSED state. After this callback -- returns, a transfer can be rejected by sending a ${TOX_FILE_CONTROL_CANCEL} -- control command before any other control commands. It can be accepted by -- sending ${TOX_FILE_CONTROL_RESUME}. -- -- @param friend_number The friend number of the friend who is sending the file -- transfer request. -- @param file_number The friend-specific file number the data received is -- associated with. -- @param kind The meaning of the file to be sent. -- @param file_size Size in bytes of the file the client wants to send, -- UINT64_MAX if unknown or streaming. -- @param filename Name of the file. Does not need to be the actual name. This -- name will be sent along with the file send request. -- @param filename_length Size in bytes of the filename. --typedef tox_file_recv_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- file_number :: -} Word32 -> {- kind :: -} Word32 -> {- file_size :: -} Word64 -> {- filename :: -} Ptr (Word8{-[filename_length <= TOX_MAX_FILENAME_LENGTH]-}) -> {- filename_length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${file_recv}` event. Pass NULL to unset. -- -- This event is triggered when a file transfer request is received. --foreign import ccall tox_callback_file_recv :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_file_recv_cb -> {- result :: -} () -- | -- When length is 0, the transfer is finished and the client should release the -- resources it acquired for the transfer. After a call with length = 0, the -- file number can be reused for new file transfers. -- -- If position is equal to file_size (received in the file_receive callback) -- when the transfer finishes, the file was received completely. Otherwise, if -- file_size was UINT64_MAX, streaming ended successfully when length is 0. -- -- @param friend_number The friend number of the friend who is sending the file. -- @param file_number The friend-specific file number the data received is -- associated with. -- @param position The file position of the first byte in data. -- @param data A byte array containing the received chunk. -- @param length The length of the received chunk. --typedef tox_file_recv_chunk_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- file_number :: -} Word32 -> {- position :: -} Word64 -> {- data :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${file_recv_chunk}` event. Pass NULL to unset. -- -- This event is first triggered when a file transfer request is received, and -- subsequently when a chunk of file data for an accepted request was received. --foreign import ccall tox_callback_file_recv_chunk :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_file_recv_chunk_cb -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: Conference management -- -------------------------------------------------------------------------------- -- | -- Conference types for the ${conference_invite} event. data TOX_CONFERENCE_TYPE = TOX_CONFERENCE_TYPE_TEXT -- ^ -- Text-only conferences that must be accepted with the ${tox_conference_join} function. | TOX_CONFERENCE_TYPE_AV -- ^ -- Video conference. The function to accept these is in toxav. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- The invitation will remain valid until the inviting friend goes offline -- or exits the conference. -- -- @param friend_number The friend who invited us. -- @param type The conference type (text only or audio/video). -- @param cookie A piece of data of variable length required to join the -- conference. -- @param length The length of the cookie. --typedef tox_conference_invite_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- type :: -} TOX_CONFERENCE_TYPE -> {- cookie :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${conference_invite}` event. Pass NULL to unset. -- -- This event is triggered when the client is invited to join a conference. --foreign import ccall tox_callback_conference_invite :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_conference_invite_cb -> {- result :: -} () -- | -- @param conference_number The conference number of the conference the message is intended for. -- @param peer_number The ID of the peer who sent the message. -- @param type The type of message (normal, action, ...). -- @param message The message data. -- @param length The length of the message. --typedef tox_conference_message_cb = {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- peer_number :: -} Word32 -> {- type :: -} TOX_MESSAGE_TYPE -> {- message :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${conference_message}` event. Pass NULL to unset. -- -- This event is triggered when the client receives a conference message. --foreign import ccall tox_callback_conference_message :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_conference_message_cb -> {- result :: -} () -- | -- @param conference_number The conference number of the conference the title change is intended for. -- @param peer_number The ID of the peer who changed the title. -- @param title The title data. -- @param length The title length. --typedef tox_conference_title_cb = {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- peer_number :: -} Word32 -> {- title :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${conference_title}` event. Pass NULL to unset. -- -- This event is triggered when a peer changes the conference title. -- -- If peer_number == UINT32_MAX, then author is unknown (e.g. initial joining the conference). --foreign import ccall tox_callback_conference_title :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_conference_title_cb -> {- result :: -} () -- | -- Peer list state change types. data TOX_CONFERENCE_STATE_CHANGE = TOX_CONFERENCE_STATE_CHANGE_PEER_JOIN -- ^ -- A peer has joined the conference. | TOX_CONFERENCE_STATE_CHANGE_PEER_EXIT -- ^ -- A peer has exited the conference. | TOX_CONFERENCE_STATE_CHANGE_PEER_NAME_CHANGE -- ^ -- A peer has changed their name. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- @param conference_number The conference number of the conference the title change is intended for. -- @param peer_number The ID of the peer who changed the title. -- @param change The type of change (one of ${TOX_CONFERENCE_STATE_CHANGE}). --typedef tox_conference_namelist_change_cb = {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- peer_number :: -} Word32 -> {- change :: -} TOX_CONFERENCE_STATE_CHANGE -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${conference_namelist_change}` event. Pass NULL to unset. -- -- This event is triggered when the peer list changes (name change, peer join, peer exit). --foreign import ccall tox_callback_conference_namelist_change :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_conference_namelist_change_cb -> {- result :: -} () data TOX_ERR_CONFERENCE_NEW = TOX_ERR_CONFERENCE_NEW_OK -- ^ -- The function returned successfully. | TOX_ERR_CONFERENCE_NEW_INIT -- ^ -- The conference instance failed to initialize. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Creates a new conference. -- -- This function creates a new text conference. -- -- @return conference number on success, or UINT32_MAX on failure. --foreign import ccall tox_conference_new :: {- tox :: -} Ptr Tox -> {- error :: -} Ptr TOX_ERR_CONFERENCE_NEW -> {- result :: -} Word32 data TOX_ERR_CONFERENCE_DELETE = TOX_ERR_CONFERENCE_DELETE_OK -- ^ -- The function returned successfully. | TOX_ERR_CONFERENCE_DELETE_CONFERENCE_NOT_FOUND -- ^ -- The conference number passed did not designate a valid conference. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- This function deletes a conference. -- -- @param conference_number The conference number of the conference to be deleted. -- -- @return true on success. --foreign import ccall tox_conference_delete :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_CONFERENCE_DELETE -> {- result :: -} Bool -- | -- Error codes for peer info queries. data TOX_ERR_CONFERENCE_PEER_QUERY = TOX_ERR_CONFERENCE_PEER_QUERY_OK -- ^ -- The function returned successfully. | TOX_ERR_CONFERENCE_PEER_QUERY_CONFERENCE_NOT_FOUND -- ^ -- The conference number passed did not designate a valid conference. | TOX_ERR_CONFERENCE_PEER_QUERY_PEER_NOT_FOUND -- ^ -- The peer number passed did not designate a valid peer. | TOX_ERR_CONFERENCE_PEER_QUERY_NO_CONNECTION -- ^ -- The client is not connected to the conference. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Return the number of peers in the conference. Return value is unspecified on failure. --foreign import ccall tox_conference_peer_count :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_CONFERENCE_PEER_QUERY -> {- result :: -} Word32 -- | -- Return the length of the peer's name. Return value is unspecified on failure. --foreign import ccall tox_conference_peer_get_name_size :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- peer_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_CONFERENCE_PEER_QUERY -> {- result :: -} CSize -- | -- Copy the name of peer_number who is in conference_number to name. -- name must be at least ${TOX_MAX_NAME_LENGTH} long. -- -- @return true on success. --foreign import ccall tox_conference_peer_get_name :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- peer_number :: -} Word32 -> {- name :: -} Ptr (Word8{-[tox_conference_peer_get_name_size]-}) -> {- error :: -} Ptr TOX_ERR_CONFERENCE_PEER_QUERY -> {- result :: -} Bool -- | -- Copy the public key of peer_number who is in conference_number to public_key. -- public_key must be ${TOX_PUBLIC_KEY_SIZE} long. -- -- @return true on success. --foreign import ccall tox_conference_peer_get_public_key :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- peer_number :: -} Word32 -> {- public_key :: -} Ptr (Word8{-[TOX_PUBLIC_KEY_SIZE]-}) -> {- error :: -} Ptr TOX_ERR_CONFERENCE_PEER_QUERY -> {- result :: -} Bool -- | -- Return true if passed peer_number corresponds to our own. --foreign import ccall tox_conference_peer_number_is_ours :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- peer_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_CONFERENCE_PEER_QUERY -> {- result :: -} Bool data TOX_ERR_CONFERENCE_INVITE = TOX_ERR_CONFERENCE_INVITE_OK -- ^ -- The function returned successfully. | TOX_ERR_CONFERENCE_INVITE_CONFERENCE_NOT_FOUND -- ^ -- The conference number passed did not designate a valid conference. | TOX_ERR_CONFERENCE_INVITE_FAIL_SEND -- ^ -- The invite packet failed to send. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Invites a friend to a conference. -- -- @param friend_number The friend number of the friend we want to invite. -- @param conference_number The conference number of the conference we want to invite the friend to. -- -- @return true on success. --foreign import ccall tox_conference_invite :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- conference_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_CONFERENCE_INVITE -> {- result :: -} Bool data TOX_ERR_CONFERENCE_JOIN = TOX_ERR_CONFERENCE_JOIN_OK -- ^ -- The function returned successfully. | TOX_ERR_CONFERENCE_JOIN_INVALID_LENGTH -- ^ -- The cookie passed has an invalid length. | TOX_ERR_CONFERENCE_JOIN_WRONG_TYPE -- ^ -- The conference is not the expected type. This indicates an invalid cookie. | TOX_ERR_CONFERENCE_JOIN_FRIEND_NOT_FOUND -- ^ -- The friend number passed does not designate a valid friend. | TOX_ERR_CONFERENCE_JOIN_DUPLICATE -- ^ -- Client is already in this conference. | TOX_ERR_CONFERENCE_JOIN_INIT_FAIL -- ^ -- Conference instance failed to initialize. | TOX_ERR_CONFERENCE_JOIN_FAIL_SEND -- ^ -- The join packet failed to send. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Joins a conference that the client has been invited to. -- -- @param friend_number The friend number of the friend who sent the invite. -- @param cookie Received via the `${conference_invite}` event. -- @param length The size of cookie. -- -- @return conference number on success, UINT32_MAX on failure. --foreign import ccall tox_conference_join :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- cookie :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_CONFERENCE_JOIN -> {- result :: -} Word32 data TOX_ERR_CONFERENCE_SEND_MESSAGE = TOX_ERR_CONFERENCE_SEND_MESSAGE_OK -- ^ -- The function returned successfully. | TOX_ERR_CONFERENCE_SEND_MESSAGE_CONFERENCE_NOT_FOUND -- ^ -- The conference number passed did not designate a valid conference. | TOX_ERR_CONFERENCE_SEND_MESSAGE_TOO_LONG -- ^ -- The message is too long. | TOX_ERR_CONFERENCE_SEND_MESSAGE_NO_CONNECTION -- ^ -- The client is not connected to the conference. | TOX_ERR_CONFERENCE_SEND_MESSAGE_FAIL_SEND -- ^ -- The message packet failed to send. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Send a text chat message to the conference. -- -- This function creates a conference message packet and pushes it into the send -- queue. -- -- The message length may not exceed ${TOX_MAX_MESSAGE_LENGTH}. Larger messages -- must be split by the client and sent as separate messages. Other clients can -- then reassemble the fragments. -- -- @param conference_number The conference number of the conference the message is intended for. -- @param type Message type (normal, action, ...). -- @param message A non-NULL pointer to the first element of a byte array -- containing the message text. -- @param length Length of the message to be sent. -- -- @return true on success. --foreign import ccall tox_conference_send_message :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- type :: -} TOX_MESSAGE_TYPE -> {- message :: -} Ptr (Word8{-[length]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_CONFERENCE_SEND_MESSAGE -> {- result :: -} Bool data TOX_ERR_CONFERENCE_TITLE = TOX_ERR_CONFERENCE_TITLE_OK -- ^ -- The function returned successfully. | TOX_ERR_CONFERENCE_TITLE_CONFERENCE_NOT_FOUND -- ^ -- The conference number passed did not designate a valid conference. | TOX_ERR_CONFERENCE_TITLE_INVALID_LENGTH -- ^ -- The title is too long or empty. | TOX_ERR_CONFERENCE_TITLE_FAIL_SEND -- ^ -- The title packet failed to send. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Return the length of the conference title. Return value is unspecified on failure. -- -- The return value is equal to the `length` argument received by the last -- `${conference_title}` callback. --foreign import ccall tox_conference_get_title_size :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_CONFERENCE_TITLE -> {- result :: -} CSize -- | -- Write the title designated by the given conference number to a byte array. -- -- Call ${tox_conference_get_title_size} to determine the allocation size for the `title` parameter. -- -- The data written to `title` is equal to the data received by the last -- `${conference_title}` callback. -- -- @param title A valid memory region large enough to store the title. -- If this parameter is NULL, this function has no effect. -- -- @return true on success. --foreign import ccall tox_conference_get_title :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- title :: -} Ptr (Word8{-[<unresolved> <= TOX_MAX_NAME_LENGTH]-}) -> {- error :: -} Ptr TOX_ERR_CONFERENCE_TITLE -> {- result :: -} Bool -- | -- Set the conference title and broadcast it to the rest of the conference. -- -- Title length cannot be longer than ${TOX_MAX_NAME_LENGTH}. -- -- @return true on success. --foreign import ccall tox_conference_set_title :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- title :: -} Ptr (Word8{-[length <= TOX_MAX_NAME_LENGTH]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_CONFERENCE_TITLE -> {- result :: -} Bool -- | -- Return the number of conferences in the Tox instance. -- This should be used to determine how much memory to allocate for `${tox_conference_get_chatlist}`. --foreign import ccall tox_conference_get_chatlist_size :: {- tox :: -} Ptr Tox -> {- result :: -} CSize -- | -- Copy a list of valid conference IDs into the array chatlist. Determine how much space -- to allocate for the array with the `${tox_conference_get_chatlist_size}` function. --foreign import ccall tox_conference_get_chatlist :: {- tox :: -} Ptr Tox -> {- chatlist :: -} Ptr (Word32{-[tox_conference_get_chatlist_size]-}) -> {- result :: -} () -- | -- Returns the type of conference (${TOX_CONFERENCE_TYPE}) that conference_number is. Return value is -- unspecified on failure. data TOX_ERR_CONFERENCE_GET_TYPE = TOX_ERR_CONFERENCE_GET_TYPE_OK -- ^ -- The function returned successfully. | TOX_ERR_CONFERENCE_GET_TYPE_CONFERENCE_NOT_FOUND -- ^ -- The conference number passed did not designate a valid conference. deriving (Eq, Ord, Enum, Bounded, Read, Show) --foreign import ccall tox_conference_get_type :: {- tox :: -} Ptr Tox -> {- conference_number :: -} Word32 -> {- error :: -} Ptr TOX_ERR_CONFERENCE_GET_TYPE -> {- result :: -} TOX_CONFERENCE_TYPE -------------------------------------------------------------------------------- -- -- :: Low-level custom packet sending and receiving -- -------------------------------------------------------------------------------- data TOX_ERR_FRIEND_CUSTOM_PACKET = TOX_ERR_FRIEND_CUSTOM_PACKET_OK -- ^ -- The function returned successfully. | TOX_ERR_FRIEND_CUSTOM_PACKET_NULL -- ^ -- One of the arguments to the function was NULL when it was not expected. | TOX_ERR_FRIEND_CUSTOM_PACKET_FRIEND_NOT_FOUND -- ^ -- The friend number did not designate a valid friend. | TOX_ERR_FRIEND_CUSTOM_PACKET_FRIEND_NOT_CONNECTED -- ^ -- This client is currently not connected to the friend. | TOX_ERR_FRIEND_CUSTOM_PACKET_INVALID -- ^ -- The first byte of data was not in the specified range for the packet type. -- This range is 200-254 for lossy, and 160-191 for lossless packets. | TOX_ERR_FRIEND_CUSTOM_PACKET_EMPTY -- ^ -- Attempted to send an empty packet. | TOX_ERR_FRIEND_CUSTOM_PACKET_TOO_LONG -- ^ -- Packet data length exceeded ${TOX_MAX_CUSTOM_PACKET_SIZE}. | TOX_ERR_FRIEND_CUSTOM_PACKET_SENDQ -- ^ -- Packet queue is full. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Send a custom lossy packet to a friend. -- -- The first byte of data must be in the range 200-254. Maximum length of a -- custom packet is ${TOX_MAX_CUSTOM_PACKET_SIZE}. -- -- Lossy packets behave like UDP packets, meaning they might never reach the -- other side or might arrive more than once (if someone is messing with the -- connection) or might arrive in the wrong order. -- -- Unless latency is an issue, it is recommended that you use lossless custom -- packets instead. -- -- @param friend_number The friend number of the friend this lossy packet -- should be sent to. -- @param data A byte array containing the packet data. -- @param length The length of the packet data byte array. -- -- @return true on success. --foreign import ccall tox_friend_send_lossy_packet :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- data :: -} Ptr (Word8{-[length <= TOX_MAX_CUSTOM_PACKET_SIZE]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_FRIEND_CUSTOM_PACKET -> {- result :: -} Bool -- | -- Send a custom lossless packet to a friend. -- -- The first byte of data must be in the range 160-191. Maximum length of a -- custom packet is ${TOX_MAX_CUSTOM_PACKET_SIZE}. -- -- Lossless packet behaviour is comparable to TCP (reliability, arrive in order) -- but with packets instead of a stream. -- -- @param friend_number The friend number of the friend this lossless packet -- should be sent to. -- @param data A byte array containing the packet data. -- @param length The length of the packet data byte array. -- -- @return true on success. --foreign import ccall tox_friend_send_lossless_packet :: {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- data :: -} Ptr (Word8{-[length <= TOX_MAX_CUSTOM_PACKET_SIZE]-}) -> {- length :: -} CSize -> {- error :: -} Ptr TOX_ERR_FRIEND_CUSTOM_PACKET -> {- result :: -} Bool -- | -- @param friend_number The friend number of the friend who sent a lossy packet. -- @param data A byte array containing the received packet data. -- @param length The length of the packet data byte array. --typedef tox_friend_lossy_packet_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- data :: -} Ptr (Word8{-[length <= TOX_MAX_CUSTOM_PACKET_SIZE]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_lossy_packet}` event. Pass NULL to unset. -- --foreign import ccall tox_callback_friend_lossy_packet :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_lossy_packet_cb -> {- result :: -} () -- | -- @param friend_number The friend number of the friend who sent the packet. -- @param data A byte array containing the received packet data. -- @param length The length of the packet data byte array. --typedef tox_friend_lossless_packet_cb = {- tox :: -} Ptr Tox -> {- friend_number :: -} Word32 -> {- data :: -} Ptr (Word8{-[length <= TOX_MAX_CUSTOM_PACKET_SIZE]-}) -> {- length :: -} CSize -> {- user_data :: -} Ptr () -> () -- | -- Set the callback for the `${friend_lossless_packet}` event. Pass NULL to unset. -- --foreign import ccall tox_callback_friend_lossless_packet :: {- tox :: -} Ptr Tox -> {- callback :: -} Ptr tox_friend_lossless_packet_cb -> {- result :: -} () -------------------------------------------------------------------------------- -- -- :: Low-level network information -- -------------------------------------------------------------------------------- -- | -- Writes the temporary DHT public key of this instance to a byte array. -- -- This can be used in combination with an externally accessible IP address and -- the bound port (from ${tox_self_get_udp_port}) to run a temporary bootstrap node. -- -- Be aware that every time a new instance is created, the DHT public key -- changes, meaning this cannot be used to run a permanent bootstrap node. -- -- @param dht_id A memory region of at least ${TOX_PUBLIC_KEY_SIZE} bytes. If this -- parameter is NULL, this function has no effect. --foreign import ccall tox_self_get_dht_id :: {- tox :: -} Ptr Tox -> {- dht_id :: -} Ptr (Word8{-[TOX_PUBLIC_KEY_SIZE]-}) -> {- result :: -} () data TOX_ERR_GET_PORT = TOX_ERR_GET_PORT_OK -- ^ -- The function returned successfully. | TOX_ERR_GET_PORT_NOT_BOUND -- ^ -- The instance was not bound to any port. deriving (Eq, Ord, Enum, Bounded, Read, Show) -- | -- Return the UDP port this Tox instance is bound to. --foreign import ccall tox_self_get_udp_port :: {- tox :: -} Ptr Tox -> {- error :: -} Ptr TOX_ERR_GET_PORT -> {- result :: -} Word16 -- | -- Return the TCP port this Tox instance is bound to. This is only relevant if -- the instance is acting as a TCP relay. --foreign import ccall tox_self_get_tcp_port :: {- tox :: -} Ptr Tox -> {- error :: -} Ptr TOX_ERR_GET_PORT -> {- result :: -} Word16
iphydf/apidsl
test/tox/tox.exp.hs
gpl-3.0
111,355
7
10
21,012
3,821
2,969
852
-1
-1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Main -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Main (main) where import Test.Tasty import Test.AWS.DynamoDB import Test.AWS.DynamoDB.Internal main :: IO () main = defaultMain $ testGroup "DynamoDB" [ testGroup "tests" tests , testGroup "fixtures" fixtures ]
olorin/amazonka
amazonka-dynamodb/test/Main.hs
mpl-2.0
537
0
8
103
76
47
29
9
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudFront.GetCloudFrontOriginAccessIdentity -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Get the information about an origin access identity. -- -- /See:/ <http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/GetCloudFrontOriginAccessIdentity.html AWS API Reference> for GetCloudFrontOriginAccessIdentity. module Network.AWS.CloudFront.GetCloudFrontOriginAccessIdentity ( -- * Creating a Request getCloudFrontOriginAccessIdentity , GetCloudFrontOriginAccessIdentity -- * Request Lenses , gcfoaiId -- * Destructuring the Response , getCloudFrontOriginAccessIdentityResponse , GetCloudFrontOriginAccessIdentityResponse -- * Response Lenses , gcfoairsETag , gcfoairsCloudFrontOriginAccessIdentity , gcfoairsResponseStatus ) where import Network.AWS.CloudFront.Types import Network.AWS.CloudFront.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | The request to get an origin access identity\'s information. -- -- /See:/ 'getCloudFrontOriginAccessIdentity' smart constructor. newtype GetCloudFrontOriginAccessIdentity = GetCloudFrontOriginAccessIdentity' { _gcfoaiId :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetCloudFrontOriginAccessIdentity' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcfoaiId' getCloudFrontOriginAccessIdentity :: Text -- ^ 'gcfoaiId' -> GetCloudFrontOriginAccessIdentity getCloudFrontOriginAccessIdentity pId_ = GetCloudFrontOriginAccessIdentity' { _gcfoaiId = pId_ } -- | The identity\'s id. gcfoaiId :: Lens' GetCloudFrontOriginAccessIdentity Text gcfoaiId = lens _gcfoaiId (\ s a -> s{_gcfoaiId = a}); instance AWSRequest GetCloudFrontOriginAccessIdentity where type Rs GetCloudFrontOriginAccessIdentity = GetCloudFrontOriginAccessIdentityResponse request = get cloudFront response = receiveXML (\ s h x -> GetCloudFrontOriginAccessIdentityResponse' <$> (h .#? "ETag") <*> (parseXML x) <*> (pure (fromEnum s))) instance ToHeaders GetCloudFrontOriginAccessIdentity where toHeaders = const mempty instance ToPath GetCloudFrontOriginAccessIdentity where toPath GetCloudFrontOriginAccessIdentity'{..} = mconcat ["/2015-04-17/origin-access-identity/cloudfront/", toBS _gcfoaiId] instance ToQuery GetCloudFrontOriginAccessIdentity where toQuery = const mempty -- | The returned result of the corresponding request. -- -- /See:/ 'getCloudFrontOriginAccessIdentityResponse' smart constructor. data GetCloudFrontOriginAccessIdentityResponse = GetCloudFrontOriginAccessIdentityResponse' { _gcfoairsETag :: !(Maybe Text) , _gcfoairsCloudFrontOriginAccessIdentity :: !(Maybe CloudFrontOriginAccessIdentity) , _gcfoairsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetCloudFrontOriginAccessIdentityResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gcfoairsETag' -- -- * 'gcfoairsCloudFrontOriginAccessIdentity' -- -- * 'gcfoairsResponseStatus' getCloudFrontOriginAccessIdentityResponse :: Int -- ^ 'gcfoairsResponseStatus' -> GetCloudFrontOriginAccessIdentityResponse getCloudFrontOriginAccessIdentityResponse pResponseStatus_ = GetCloudFrontOriginAccessIdentityResponse' { _gcfoairsETag = Nothing , _gcfoairsCloudFrontOriginAccessIdentity = Nothing , _gcfoairsResponseStatus = pResponseStatus_ } -- | The current version of the origin access identity\'s information. For -- example: E2QWRUHAPOMQZL. gcfoairsETag :: Lens' GetCloudFrontOriginAccessIdentityResponse (Maybe Text) gcfoairsETag = lens _gcfoairsETag (\ s a -> s{_gcfoairsETag = a}); -- | The origin access identity\'s information. gcfoairsCloudFrontOriginAccessIdentity :: Lens' GetCloudFrontOriginAccessIdentityResponse (Maybe CloudFrontOriginAccessIdentity) gcfoairsCloudFrontOriginAccessIdentity = lens _gcfoairsCloudFrontOriginAccessIdentity (\ s a -> s{_gcfoairsCloudFrontOriginAccessIdentity = a}); -- | The response status code. gcfoairsResponseStatus :: Lens' GetCloudFrontOriginAccessIdentityResponse Int gcfoairsResponseStatus = lens _gcfoairsResponseStatus (\ s a -> s{_gcfoairsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-cloudfront/gen/Network/AWS/CloudFront/GetCloudFrontOriginAccessIdentity.hs
mpl-2.0
5,277
0
13
974
605
363
242
78
1
----------------------------------------------------------------------------- -- | -- Module : Distribution.PackageDescription.PrettyPrint -- Copyright : Jürgen Nicklisch-Franken 2010 -- License : BSD3 -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Pretty printing for cabal files -- ----------------------------------------------------------------------------- module Distribution.PackageDescription.PrettyPrint ( -- * Generic package descriptions writeGenericPackageDescription, showGenericPackageDescription, -- * Package descriptions writePackageDescription, showPackageDescription, -- ** Supplementary build information writeHookedBuildInfo, showHookedBuildInfo, ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Types.Dependency import Distribution.Types.ForeignLib import Distribution.Types.UnqualComponentName import Distribution.Types.CondTree import Distribution.PackageDescription import Distribution.Simple.Utils import Distribution.ParseUtils import Distribution.PackageDescription.Parse import Distribution.Text import Distribution.ModuleName import Text.PrettyPrint (hsep, space, parens, char, nest, isEmpty, ($$), (<+>), colon, text, vcat, ($+$), Doc, render) import qualified Data.ByteString.Lazy.Char8 as BS.Char8 -- | Recompile with false for regression testing simplifiedPrinting :: Bool simplifiedPrinting = False -- | Writes a .cabal file from a generic package description writeGenericPackageDescription :: FilePath -> GenericPackageDescription -> NoCallStackIO () writeGenericPackageDescription fpath pkg = writeUTF8File fpath (showGenericPackageDescription pkg) -- | Writes a generic package description to a string showGenericPackageDescription :: GenericPackageDescription -> String showGenericPackageDescription = render . ppGenericPackageDescription ppGenericPackageDescription :: GenericPackageDescription -> Doc ppGenericPackageDescription gpd = ppPackageDescription (packageDescription gpd) $+$ ppGenPackageFlags (genPackageFlags gpd) $+$ ppCondLibrary (condLibrary gpd) $+$ ppCondSubLibraries (condSubLibraries gpd) $+$ ppCondExecutables (condExecutables gpd) $+$ ppCondTestSuites (condTestSuites gpd) $+$ ppCondBenchmarks (condBenchmarks gpd) ppPackageDescription :: PackageDescription -> Doc ppPackageDescription pd = ppFields pkgDescrFieldDescrs pd $+$ ppCustomFields (customFieldsPD pd) $+$ ppSourceRepos (sourceRepos pd) ppSourceRepos :: [SourceRepo] -> Doc ppSourceRepos [] = mempty ppSourceRepos (hd:tl) = ppSourceRepo hd $+$ ppSourceRepos tl ppSourceRepo :: SourceRepo -> Doc ppSourceRepo repo = emptyLine $ text "source-repository" <+> disp (repoKind repo) $+$ (nest indentWith (ppFields sourceRepoFieldDescrs' repo)) where sourceRepoFieldDescrs' = [fd | fd <- sourceRepoFieldDescrs, fieldName fd /= "kind"] -- TODO: this is a temporary hack. Ideally, fields containing default values -- would be filtered out when the @FieldDescr a@ list is generated. ppFieldsFiltered :: [(String, String)] -> [FieldDescr a] -> a -> Doc ppFieldsFiltered removable fields x = ppFields (filter nondefault fields) x where nondefault (FieldDescr name getter _) = maybe True (render (getter x) /=) (lookup name removable) binfoDefaults :: [(String, String)] binfoDefaults = [("buildable", "True")] libDefaults :: [(String, String)] libDefaults = ("exposed", "True") : binfoDefaults flagDefaults :: [(String, String)] flagDefaults = [("default", "True"), ("manual", "False")] ppDiffFields :: [FieldDescr a] -> a -> a -> Doc ppDiffFields fields x y = vcat [ ppField name (getter x) | FieldDescr name getter _ <- fields , render (getter x) /= render (getter y) ] ppCustomFields :: [(String,String)] -> Doc ppCustomFields flds = vcat [ppCustomField f | f <- flds] ppCustomField :: (String,String) -> Doc ppCustomField (name,val) = text name <<>> colon <+> showFreeText val ppGenPackageFlags :: [Flag] -> Doc ppGenPackageFlags flds = vcat [ppFlag f | f <- flds] ppFlag :: Flag -> Doc ppFlag flag@(MkFlag name _ _ _) = emptyLine $ text "flag" <+> ppFlagName name $+$ nest indentWith fields where fields = ppFieldsFiltered flagDefaults flagFieldDescrs flag ppCondLibrary :: Maybe (CondTree ConfVar [Dependency] Library) -> Doc ppCondLibrary Nothing = mempty ppCondLibrary (Just condTree) = emptyLine $ text "library" $+$ nest indentWith (ppCondTree condTree Nothing ppLib) ppCondSubLibraries :: [(UnqualComponentName, CondTree ConfVar [Dependency] Library)] -> Doc ppCondSubLibraries libs = vcat [emptyLine $ (text "library " <+> disp n) $+$ nest indentWith (ppCondTree condTree Nothing ppLib)| (n,condTree) <- libs] ppLib :: Library -> Maybe Library -> Doc ppLib lib Nothing = ppFieldsFiltered libDefaults libFieldDescrs lib $$ ppCustomFields (customFieldsBI (libBuildInfo lib)) ppLib lib (Just plib) = ppDiffFields libFieldDescrs lib plib $$ ppCustomFields (customFieldsBI (libBuildInfo lib)) ppCondExecutables :: [(UnqualComponentName, CondTree ConfVar [Dependency] Executable)] -> Doc ppCondExecutables exes = vcat [emptyLine $ (text "executable " <+> disp n) $+$ nest indentWith (ppCondTree condTree Nothing ppExe)| (n,condTree) <- exes] where ppExe (Executable _ modulePath' exeScope' buildInfo') Nothing = (if modulePath' == "" then mempty else text "main-is:" <+> text modulePath') $+$ if exeScope' == mempty then mempty else text "scope:" <+> disp exeScope' $+$ ppFieldsFiltered binfoDefaults binfoFieldDescrs buildInfo' $+$ ppCustomFields (customFieldsBI buildInfo') ppExe (Executable _ modulePath' exeScope' buildInfo') (Just (Executable _ modulePath2 exeScope2 buildInfo2)) = (if modulePath' == "" || modulePath' == modulePath2 then mempty else text "main-is:" <+> text modulePath') $+$ if exeScope' == exeScope2 then mempty else text "scope:" <+> disp exeScope' $+$ ppDiffFields binfoFieldDescrs buildInfo' buildInfo2 $+$ ppCustomFields (customFieldsBI buildInfo') ppCondTestSuites :: [(UnqualComponentName, CondTree ConfVar [Dependency] TestSuite)] -> Doc ppCondTestSuites suites = emptyLine $ vcat [ (text "test-suite " <+> disp n) $+$ nest indentWith (ppCondTree condTree Nothing ppTestSuite) | (n,condTree) <- suites] where ppTestSuite testsuite Nothing = maybe mempty (\t -> text "type:" <+> disp t) maybeTestType $+$ maybe mempty (\f -> text "main-is:" <+> text f) (testSuiteMainIs testsuite) $+$ maybe mempty (\m -> text "test-module:" <+> disp m) (testSuiteModule testsuite) $+$ ppFieldsFiltered binfoDefaults binfoFieldDescrs (testBuildInfo testsuite) $+$ ppCustomFields (customFieldsBI (testBuildInfo testsuite)) where maybeTestType | testInterface testsuite == mempty = Nothing | otherwise = Just (testType testsuite) ppTestSuite test' (Just test2) = ppDiffFields binfoFieldDescrs (testBuildInfo test') (testBuildInfo test2) $+$ ppCustomFields (customFieldsBI (testBuildInfo test')) testSuiteMainIs test = case testInterface test of TestSuiteExeV10 _ f -> Just f _ -> Nothing testSuiteModule test = case testInterface test of TestSuiteLibV09 _ m -> Just m _ -> Nothing ppCondBenchmarks :: [(UnqualComponentName, CondTree ConfVar [Dependency] Benchmark)] -> Doc ppCondBenchmarks suites = emptyLine $ vcat [ (text "benchmark " <+> disp n) $+$ nest indentWith (ppCondTree condTree Nothing ppBenchmark) | (n,condTree) <- suites] where ppBenchmark benchmark Nothing = maybe mempty (\t -> text "type:" <+> disp t) maybeBenchmarkType $+$ maybe mempty (\f -> text "main-is:" <+> text f) (benchmarkMainIs benchmark) $+$ ppFieldsFiltered binfoDefaults binfoFieldDescrs (benchmarkBuildInfo benchmark) $+$ ppCustomFields (customFieldsBI (benchmarkBuildInfo benchmark)) where maybeBenchmarkType | benchmarkInterface benchmark == mempty = Nothing | otherwise = Just (benchmarkType benchmark) ppBenchmark bench' (Just bench2) = ppDiffFields binfoFieldDescrs (benchmarkBuildInfo bench') (benchmarkBuildInfo bench2) $+$ ppCustomFields (customFieldsBI (benchmarkBuildInfo bench')) benchmarkMainIs benchmark = case benchmarkInterface benchmark of BenchmarkExeV10 _ f -> Just f _ -> Nothing ppCondition :: Condition ConfVar -> Doc ppCondition (Var x) = ppConfVar x ppCondition (Lit b) = text (show b) ppCondition (CNot c) = char '!' <<>> (ppCondition c) ppCondition (COr c1 c2) = parens (hsep [ppCondition c1, text "||" <+> ppCondition c2]) ppCondition (CAnd c1 c2) = parens (hsep [ppCondition c1, text "&&" <+> ppCondition c2]) ppConfVar :: ConfVar -> Doc ppConfVar (OS os) = text "os" <<>> parens (disp os) ppConfVar (Arch arch) = text "arch" <<>> parens (disp arch) ppConfVar (Flag name) = text "flag" <<>> parens (ppFlagName name) ppConfVar (Impl c v) = text "impl" <<>> parens (disp c <+> disp v) ppFlagName :: FlagName -> Doc ppFlagName = text . unFlagName ppCondTree :: CondTree ConfVar [Dependency] a -> Maybe a -> (a -> Maybe a -> Doc) -> Doc ppCondTree ct@(CondNode it _ ifs) mbIt ppIt = let res = (vcat $ map ppIf ifs) $+$ ppIt it mbIt in if isJust mbIt && isEmpty res then ppCondTree ct Nothing ppIt else res where -- TODO: this ends up printing trailing spaces when combined with nest. ppIf (CondBranch c thenTree (Just elseTree)) = ppIfElse it ppIt c thenTree elseTree ppIf (CondBranch c thenTree Nothing) = ppIf' it ppIt c thenTree ppIfCondition :: (Condition ConfVar) -> Doc ppIfCondition c = (emptyLine $ text "if" <+> ppCondition c) ppIf' :: a -> (a -> Maybe a -> Doc) -> Condition ConfVar -> CondTree ConfVar [Dependency] a -> Doc ppIf' it ppIt c thenTree = if isEmpty thenDoc then mempty else ppIfCondition c $$ nest indentWith thenDoc where thenDoc = ppCondTree thenTree (if simplifiedPrinting then (Just it) else Nothing) ppIt ppIfElse :: a -> (a -> Maybe a -> Doc) -> Condition ConfVar -> CondTree ConfVar [Dependency] a -> CondTree ConfVar [Dependency] a -> Doc ppIfElse it ppIt c thenTree elseTree = case (isEmpty thenDoc, isEmpty elseDoc) of (True, True) -> mempty (False, True) -> ppIfCondition c $$ nest indentWith thenDoc (True, False) -> ppIfCondition (cNot c) $$ nest indentWith elseDoc (False, False) -> (ppIfCondition c $$ nest indentWith thenDoc) $+$ (text "else" $$ nest indentWith elseDoc) where thenDoc = ppCondTree thenTree (if simplifiedPrinting then (Just it) else Nothing) ppIt elseDoc = ppCondTree elseTree (if simplifiedPrinting then (Just it) else Nothing) ppIt emptyLine :: Doc -> Doc emptyLine d = text "" $+$ d -- | @since 1.26.0.0@ writePackageDescription :: FilePath -> PackageDescription -> NoCallStackIO () writePackageDescription fpath pkg = writeUTF8File fpath (showPackageDescription pkg) --TODO: make this use section syntax -- add equivalent for GenericPackageDescription -- | @since 1.26.0.0@ showPackageDescription :: PackageDescription -> String showPackageDescription pkg = render $ ppPackageDescription pkg $+$ ppMaybeLibrary (library pkg) $+$ ppSubLibraries (subLibraries pkg) $+$ ppForeignLibs (foreignLibs pkg) $+$ ppExecutables (executables pkg) $+$ ppTestSuites (testSuites pkg) $+$ ppBenchmarks (benchmarks pkg) ppMaybeLibrary :: Maybe Library -> Doc ppMaybeLibrary Nothing = mempty ppMaybeLibrary (Just lib) = emptyLine $ text "library" $+$ nest indentWith (ppFields libFieldDescrs lib) ppSubLibraries :: [Library] -> Doc ppSubLibraries libs = vcat [ emptyLine $ text "library" <+> disp libname $+$ nest indentWith (ppFields libFieldDescrs lib) | lib@Library{ libName = Just libname } <- libs ] ppForeignLibs :: [ForeignLib] -> Doc ppForeignLibs flibs = vcat [ emptyLine $ text "foreign library" <+> disp flibname $+$ nest indentWith (ppFields foreignLibFieldDescrs flib) | flib@ForeignLib{ foreignLibName = flibname } <- flibs ] ppExecutables :: [Executable] -> Doc ppExecutables exes = vcat [ emptyLine $ text "executable" <+> disp (exeName exe) $+$ nest indentWith (ppFields executableFieldDescrs exe) | exe <- exes ] ppTestSuites :: [TestSuite] -> Doc ppTestSuites tests = vcat [ emptyLine $ text "test-suite" <+> disp (testName test) $+$ nest indentWith (ppFields testSuiteFieldDescrs test_stanza) | test <- tests , let test_stanza = TestSuiteStanza { testStanzaTestType = Just (testSuiteInterfaceToTestType (testInterface test)), testStanzaMainIs = testSuiteInterfaceToMaybeMainIs (testInterface test), testStanzaTestModule = testSuiteInterfaceToMaybeModule (testInterface test), testStanzaBuildInfo = testBuildInfo test } ] testSuiteInterfaceToTestType :: TestSuiteInterface -> TestType testSuiteInterfaceToTestType (TestSuiteExeV10 ver _) = TestTypeExe ver testSuiteInterfaceToTestType (TestSuiteLibV09 ver _) = TestTypeLib ver testSuiteInterfaceToTestType (TestSuiteUnsupported ty) = ty testSuiteInterfaceToMaybeMainIs :: TestSuiteInterface -> Maybe FilePath testSuiteInterfaceToMaybeMainIs (TestSuiteExeV10 _ fp) = Just fp testSuiteInterfaceToMaybeMainIs TestSuiteLibV09{} = Nothing testSuiteInterfaceToMaybeMainIs TestSuiteUnsupported{} = Nothing testSuiteInterfaceToMaybeModule :: TestSuiteInterface -> Maybe ModuleName testSuiteInterfaceToMaybeModule (TestSuiteLibV09 _ mod_name) = Just mod_name testSuiteInterfaceToMaybeModule TestSuiteExeV10{} = Nothing testSuiteInterfaceToMaybeModule TestSuiteUnsupported{} = Nothing ppBenchmarks :: [Benchmark] -> Doc ppBenchmarks benchs = vcat [ emptyLine $ text "benchmark" <+> disp (benchmarkName bench) $+$ nest indentWith (ppFields benchmarkFieldDescrs bench_stanza) | bench <- benchs , let bench_stanza = BenchmarkStanza { benchmarkStanzaBenchmarkType = Just (benchmarkInterfaceToBenchmarkType (benchmarkInterface bench)), benchmarkStanzaMainIs = benchmarkInterfaceToMaybeMainIs (benchmarkInterface bench), benchmarkStanzaBenchmarkModule = Nothing, benchmarkStanzaBuildInfo = benchmarkBuildInfo bench }] benchmarkInterfaceToBenchmarkType :: BenchmarkInterface -> BenchmarkType benchmarkInterfaceToBenchmarkType (BenchmarkExeV10 ver _) = BenchmarkTypeExe ver benchmarkInterfaceToBenchmarkType (BenchmarkUnsupported ty) = ty benchmarkInterfaceToMaybeMainIs :: BenchmarkInterface -> Maybe FilePath benchmarkInterfaceToMaybeMainIs (BenchmarkExeV10 _ fp) = Just fp benchmarkInterfaceToMaybeMainIs BenchmarkUnsupported{} = Nothing -- | @since 1.26.0.0@ writeHookedBuildInfo :: FilePath -> HookedBuildInfo -> NoCallStackIO () writeHookedBuildInfo fpath = writeFileAtomic fpath . BS.Char8.pack . showHookedBuildInfo -- | @since 1.26.0.0@ showHookedBuildInfo :: HookedBuildInfo -> String showHookedBuildInfo (mb_lib_bi, ex_bis) = render $ (case mb_lib_bi of Nothing -> mempty Just bi -> ppBuildInfo bi) $$ vcat [ space $$ (text "executable:" <+> disp name) $$ ppBuildInfo bi | (name, bi) <- ex_bis ] where ppBuildInfo bi = ppFields binfoFieldDescrs bi $$ ppCustomFields (customFieldsBI bi)
themoritz/cabal
Cabal/Distribution/PackageDescription/PrettyPrint.hs
bsd-3-clause
16,991
0
17
4,300
4,411
2,245
2,166
287
6
{-# LANGUAGE PatternGuards, ViewPatterns #-} module Idris.Elab.Record(elabRecord) where import Idris.AbsSyntax import Idris.Docstrings import Idris.Error import Idris.Delaborate import Idris.Imports import Idris.Elab.Term 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.ParseExpr (tryFullExpr) import Idris.Elab.Type import Idris.Elab.Data import Idris.Elab.Utils import Idris.Core.TT import Idris.Core.Evaluate import Idris.Elab.Data import Data.Maybe import Data.List import Control.Monad -- | Elaborate a record declaration elabRecord :: ElabInfo -> (Docstring (Either Err PTerm)) -- ^ The documentation for the whole declaration -> SyntaxInfo -> FC -> DataOpts -> Name -- ^ The name of the type being defined -> FC -- ^ The precise source location of the tycon name -> [(Name, FC, Plicity, PTerm)] -- ^ Parameters -> [(Name, Docstring (Either Err PTerm))] -- ^ Parameter Docs -> [(Maybe (Name, FC), Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -- ^ Fields -> Maybe (Name, FC) -- ^ Constructor Name -> (Docstring (Either Err PTerm)) -- ^ Constructor Doc -> SyntaxInfo -- ^ Constructor SyntaxInfo -> Idris () elabRecord info doc rsyn fc opts tyn nfc params paramDocs fields cname cdoc csyn = do logLvl 1 $ "Building data declaration for " ++ show tyn -- Type constructor let tycon = generateTyConType params logLvl 1 $ "Type constructor " ++ showTmImpls tycon -- Data constructor dconName <- generateDConName (fmap fst cname) let dconTy = generateDConType params fieldsWithNameAndDoc logLvl 1 $ "Data constructor: " ++ showTmImpls dconTy -- Build data declaration for elaboration logLvl 1 $ foldr (++) "" $ intersperse "\n" (map show dconsArgDocs) let datadecl = PDatadecl tyn NoFC tycon [(cdoc, dconsArgDocs, dconName, NoFC, dconTy, fc, [])] elabData info rsyn doc paramDocs fc opts datadecl logLvl 1 $ "fieldsWithName " ++ show fieldsWithName logLvl 1 $ "fieldsWIthNameAndDoc " ++ show fieldsWithNameAndDoc elabRecordFunctions info rsyn fc tyn paramsAndDoc fieldsWithNameAndDoc dconName target sendHighlighting $ [(nfc, AnnName tyn Nothing Nothing Nothing)] ++ maybe [] (\(_, cnfc) -> [(cnfc, AnnName dconName Nothing Nothing Nothing)]) cname ++ [(ffc, AnnBoundName fn False) | (fn, ffc, _, _, _) <- fieldsWithName] where -- | Generates a type constructor. generateTyConType :: [(Name, FC, Plicity, PTerm)] -> PTerm generateTyConType ((n, nfc, p, t) : rest) = PPi p (nsroot n) nfc t (generateTyConType rest) generateTyConType [] = (PType fc) -- | Generates a name for the data constructor if none was specified. generateDConName :: Maybe Name -> Idris Name generateDConName (Just n) = return $ expandNS csyn n generateDConName Nothing = uniqueName (expandNS csyn $ sMN 0 ("Mk" ++ (show (nsroot tyn)))) where uniqueName :: Name -> Idris Name uniqueName n = do i <- getIState case lookupTyNameExact n (tt_ctxt i) of Just _ -> uniqueName (nextName n) Nothing -> return n -- | Generates the data constructor type. generateDConType :: [(Name, FC, Plicity, PTerm)] -> [(Name, FC, Plicity, PTerm, a)] -> PTerm generateDConType ((n, nfc, _, t) : ps) as = PPi impl (nsroot n) NoFC t (generateDConType ps as) generateDConType [] ((n, _, p, t, _) : as) = PPi p (nsroot n) NoFC t (generateDConType [] as) generateDConType [] [] = target -- | The target for the constructor and projection functions. Also the source of the update functions. target :: PTerm target = PApp fc (PRef fc [] tyn) $ map (uncurry asPRefArg) [(p, n) | (n, _, p, _) <- params] paramsAndDoc :: [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] paramsAndDoc = pad params paramDocs where pad :: [(Name, FC, Plicity, PTerm)] -> [(Name, Docstring (Either Err PTerm))] -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] pad ((n, fc, p, t) : rest) docs = let d = case lookup n docs of Just d' -> d Nothing -> emptyDocstring in (n, fc, p, t, d) : (pad rest docs) pad _ _ = [] dconsArgDocs :: [(Name, Docstring (Either Err PTerm))] dconsArgDocs = paramDocs ++ (dcad fieldsWithName) where dcad :: [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -> [(Name, Docstring (Either Err PTerm))] dcad ((n, _, _, _, (Just d)) : rest) = ((nsroot n), d) : (dcad rest) dcad (_ : rest) = dcad rest dcad [] = [] fieldsWithName :: [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] fieldsWithName = fwn [] fields where fwn :: [Name] -> [(Maybe (Name, FC), Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -> [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] fwn ns ((n, p, t, d) : rest) = let nn = case n of Just n' -> n' Nothing -> newName ns baseName withNS = expandNS rsyn (fst nn) in (withNS, snd nn, p, t, d) : (fwn (fst nn : ns) rest) fwn _ _ = [] baseName = (sUN "__pi_arg", NoFC) newName :: [Name] -> (Name, FC) -> (Name, FC) newName ns (n, nfc) | n `elem` ns = newName ns (nextName n, nfc) | otherwise = (n, nfc) fieldsWithNameAndDoc :: [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] fieldsWithNameAndDoc = fwnad fieldsWithName where fwnad :: [(Name, FC, Plicity, PTerm, Maybe (Docstring (Either Err PTerm)))] -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] fwnad ((n, nfc, p, t, d) : rest) = let doc = fromMaybe emptyDocstring d in (n, nfc, p, t, doc) : (fwnad rest) fwnad [] = [] elabRecordFunctions :: ElabInfo -> SyntaxInfo -> FC -> Name -- ^ Record type name -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] -- ^ Parameters -> [(Name, FC, Plicity, PTerm, Docstring (Either Err PTerm))] -- ^ Fields -> Name -- ^ Constructor Name -> PTerm -- ^ Target type -> Idris () elabRecordFunctions info rsyn fc tyn params fields dconName target = do logLvl 1 $ "Elaborating helper functions for record " ++ show tyn logLvl 1 $ "Fields: " ++ show fieldNames logLvl 1 $ "Params: " ++ show paramNames -- The elaborated constructor type for the data declaration i <- getIState ttConsTy <- case lookupTyExact dconName (tt_ctxt i) of Just as -> return as Nothing -> tclift $ tfail $ At fc (Elaborating "record " tyn (InternalMsg "It seems like the constructor for this record has disappeared. :( \n This is a bug. Please report.")) -- The arguments to the constructor let constructorArgs = getArgTys ttConsTy logLvl 1 $ "Cons args: " ++ show constructorArgs logLvl 1 $ "Free fields: " ++ show (filter (not . isFieldOrParam') constructorArgs) -- If elaborating the constructor has resulted in some new implicit fields we make projection functions for them. let freeFieldsForElab = map (freeField i) (filter (not . isFieldOrParam') constructorArgs) -- The parameters for elaboration with their documentation -- Parameter functions are all prefixed with "param_". let paramsForElab = [((nsroot n), (paramName n), impl, t, d) | (n, _, _, t, d) <- params] -- zipParams i params paramDocs] -- The fields (written by the user) with their documentation. let userFieldsForElab = [((nsroot n), n, p, t, d) | (n, nfc, p, t, d) <- fields] -- All things we need to elaborate projection functions for, together with a number denoting their position in the constructor. let projectors = [(n, n', p, t, d, i) | ((n, n', p, t, d), i) <- zip (freeFieldsForElab ++ paramsForElab ++ userFieldsForElab) [0..]] -- Build and elaborate projection functions elabProj dconName projectors logLvl 1 $ "Dependencies: " ++ show fieldDependencies logLvl 1 $ "Depended on: " ++ show dependedOn -- All things we need to elaborate update functions for, together with a number denoting their position in the constructor. let updaters = [(n, n', p, t, d, i) | ((n, n', p, t, d), i) <- zip (paramsForElab ++ userFieldsForElab) [0..]] -- Build and elaborate update functions elabUp dconName updaters where -- | Creates a PArg from a plicity and a name where the term is a Placeholder. placeholderArg :: Plicity -> Name -> PArg placeholderArg p n = asArg p (nsroot n) Placeholder -- | Root names of all fields in the current record declarations fieldNames :: [Name] fieldNames = [nsroot n | (n, _, _, _, _) <- fields] paramNames :: [Name] paramNames = [nsroot n | (n, _, _, _, _) <- params] isFieldOrParam :: Name -> Bool isFieldOrParam n = n `elem` (fieldNames ++ paramNames) isFieldOrParam' :: (Name, a) -> Bool isFieldOrParam' = isFieldOrParam . fst isField :: Name -> Bool isField = flip elem fieldNames isField' :: (Name, a, b, c, d, f) -> Bool isField' (n, _, _, _, _, _) = isField n fieldTerms :: [PTerm] fieldTerms = [t | (_, _, _, t, _) <- fields] -- Delabs the TT to PTerm -- This is not good. -- However, for machine generated implicits, there seems to be no PTerm available. -- Is there a better way to do this without building the setters and getters as TT? freeField :: IState -> (Name, TT Name) -> (Name, Name, Plicity, PTerm, Docstring (Either Err PTerm)) freeField i arg = let nameInCons = fst arg -- The name as it appears in the constructor nameFree = expandNS rsyn (freeName $ fst arg) -- The name prefixed with "free_" plicity = impl -- All free fields are implicit as they are machine generated fieldType = delab i (snd arg) -- The type of the field doc = emptyDocstring -- No docmentation for machine generated fields in (nameInCons, nameFree, plicity, fieldType, doc) freeName :: Name -> Name freeName (UN n) = sUN ("free_" ++ str n) freeName (MN i n) = sMN i ("free_" ++ str n) freeName (NS n s) = NS (freeName n) s freeName n = n -- | Zips together parameters with their documentation. If no documentation for a given field exists, an empty docstring is used. zipParams :: IState -> [(Name, Plicity, PTerm)] -> [(Name, Docstring (Either Err PTerm))] -> [(Name, PTerm, Docstring (Either Err PTerm))] zipParams i ((n, _, t) : rest) ((_, d) : rest') = (n, t, d) : (zipParams i rest rest') zipParams i ((n, _, t) : rest) [] = (n, t, emptyDoc) : (zipParams i rest []) where emptyDoc = annotCode (tryFullExpr rsyn i) emptyDocstring zipParams _ [] [] = [] paramName :: Name -> Name paramName (UN n) = sUN ("param_" ++ str n) paramName (MN i n) = sMN i ("param_" ++ str n) paramName (NS n s) = NS (paramName n) s paramName n = n -- | Elaborate the projection functions. elabProj :: Name -> [(Name, Name, Plicity, PTerm, Docstring (Either Err PTerm), Int)] -> Idris () elabProj cn fs = let phArgs = map (uncurry placeholderArg) [(p, n) | (n, _, p, _, _, _) <- fs] elab = \(n, n', p, t, doc, i) -> -- Use projections in types do let t' = projectInType [(m, m') | (m, m', _, _, _, _) <- fs -- Parameters are already in scope, so just use them , not (m `elem` paramNames)] t elabProjection info n n' p t' doc rsyn fc target cn phArgs fieldNames i in mapM_ elab fs -- | Elaborate the update functions. elabUp :: Name -> [(Name, Name, Plicity, PTerm, Docstring (Either Err PTerm), Int)] -> Idris () elabUp cn fs = let args = map (uncurry asPRefArg) [(p, n) | (n, _, p, _, _, _) <- fs] elab = \(n, n', p, t, doc, i) -> elabUpdate info n n' p t doc rsyn fc target cn args fieldNames i (optionalSetter n) in mapM_ elab fs -- | Decides whether a setter should be generated for a field or not. optionalSetter :: Name -> Bool optionalSetter n = n `elem` dependedOn -- | A map from a field name to the other fields it depends on. fieldDependencies :: [(Name, [Name])] fieldDependencies = map (uncurry fieldDep) [(n, t) | (n, _, _, t, _) <- fields ++ params] where fieldDep :: Name -> PTerm -> (Name, [Name]) fieldDep n t = ((nsroot n), paramNames ++ fieldNames `intersect` allNamesIn t) -- | A list of fields depending on another field. dependentFields :: [Name] dependentFields = filter depends fieldNames where depends :: Name -> Bool depends n = case lookup n fieldDependencies of Just xs -> not $ null xs Nothing -> False -- | A list of fields depended on by other fields. dependedOn :: [Name] dependedOn = concat ((catMaybes (map (\x -> lookup x fieldDependencies) fieldNames))) -- | Creates and elaborates a projection function. elabProjection :: ElabInfo -> Name -- ^ Name of the argument in the constructor -> Name -- ^ Projection Name -> Plicity -- ^ Projection Plicity -> PTerm -- ^ Projection Type -> (Docstring (Either Err PTerm)) -- ^ Projection Documentation -> SyntaxInfo -- ^ Projection SyntaxInfo -> FC -> PTerm -- ^ Projection target type -> Name -- ^ Data constructor tame -> [PArg] -- ^ Placeholder Arguments to constructor -> [Name] -- ^ All Field Names -> Int -- ^ Argument Index -> Idris () elabProjection info cname pname plicity projTy pdoc psyn fc targetTy cn phArgs fnames index = do logLvl 1 $ "Generating Projection for " ++ show pname let ty = generateTy logLvl 1 $ "Type of " ++ show pname ++ ": " ++ show ty let lhs = generateLhs logLvl 1 $ "LHS of " ++ show pname ++ ": " ++ showTmImpls lhs let rhs = generateRhs logLvl 1 $ "RHS of " ++ show pname ++ ": " ++ showTmImpls rhs rec_elabDecl info EAll info ty let clause = PClause fc pname lhs [] rhs [] rec_elabDecl info EAll info $ PClauses fc [] pname [clause] where -- | The type of the projection function. generateTy :: PDecl generateTy = PTy pdoc [] psyn fc [] pname NoFC $ PPi expl recName NoFC targetTy projTy -- | The left hand side of the projection function. generateLhs :: PTerm generateLhs = let args = lhsArgs index phArgs in PApp fc (PRef fc [] pname) [pexp (PApp fc (PRef fc [] cn) args)] where lhsArgs :: Int -> [PArg] -> [PArg] lhsArgs 0 (_ : rest) = (asArg plicity (nsroot cname) (PRef fc [] pname_in)) : rest lhsArgs i (x : rest) = x : (lhsArgs (i-1) rest) lhsArgs _ [] = [] -- | The "_in" name. Used for the lhs. pname_in :: Name pname_in = rootname -- in_name rootname rootname :: Name rootname = nsroot cname -- | The right hand side of the projection function. generateRhs :: PTerm generateRhs = PRef fc [] pname_in -- | Creates and elaborates an update function. -- If 'optional' is true, we will not fail if we can't elaborate the update function. elabUpdate :: ElabInfo -> Name -- ^ Name of the argument in the constructor -> Name -- ^ Field Name -> Plicity -- ^ Field Plicity -> PTerm -- ^ Field Type -> (Docstring (Either Err PTerm)) -- ^ Field Documentation -> SyntaxInfo -- ^ Field SyntaxInfo -> FC -> PTerm -- ^ Projection Source Type -> Name -- ^ Data Constructor Name -> [PArg] -- ^ Arguments to constructor -> [Name] -- ^ All fields -> Int -- ^ Argument Index -> Bool -- ^ Optional -> Idris () elabUpdate info cname pname plicity pty pdoc psyn fc sty cn args fnames i optional = do logLvl 1 $ "Generating Update for " ++ show pname let ty = generateTy logLvl 1 $ "Type of " ++ show set_pname ++ ": " ++ show ty let lhs = generateLhs logLvl 1 $ "LHS of " ++ show set_pname ++ ": " ++ showTmImpls lhs let rhs = generateRhs logLvl 1 $ "RHS of " ++ show set_pname ++ ": " ++ showTmImpls rhs let clause = PClause fc set_pname lhs [] rhs [] idrisCatch (do rec_elabDecl info EAll info ty rec_elabDecl info EAll info $ PClauses fc [] set_pname [clause]) (\err -> logLvl 1 $ "Could not generate update function for " ++ show pname) {-if optional then logLvl 1 $ "Could not generate update function for " ++ show pname else tclift $ tfail $ At fc (Elaborating "record update function " pname err)) -} where -- | The type of the update function. generateTy :: PDecl generateTy = PTy pdoc [] psyn fc [] set_pname NoFC $ PPi expl (nsroot pname) NoFC pty $ PPi expl recName NoFC sty (substInput sty) where substInput = substMatches [(cname, PRef fc [] (nsroot pname))] -- | The "_set" name. set_pname :: Name set_pname = set_name pname set_name :: Name -> Name set_name (UN n) = sUN ("set_" ++ str n) set_name (MN i n) = sMN i ("set_" ++ str n) set_name (NS n s) = NS (set_name n) s set_name n = n -- | The left-hand side of the update function. generateLhs :: PTerm generateLhs = PApp fc (PRef fc [] set_pname) [pexp $ PRef fc [] pname_in, pexp constructorPattern] where constructorPattern :: PTerm constructorPattern = PApp fc (PRef fc [] cn) args -- | The "_in" name. pname_in :: Name pname_in = in_name rootname rootname :: Name rootname = nsroot pname -- | The right-hand side of the update function. generateRhs :: PTerm generateRhs = PApp fc (PRef fc [] cn) (newArgs i args) where newArgs :: Int -> [PArg] -> [PArg] newArgs 0 (_ : rest) = (asArg plicity (nsroot cname) (PRef fc [] pname_in)) : rest newArgs i (x : rest) = x : (newArgs (i-1) rest) newArgs _ [] = [] -- | Post-fixes a name with "_in". in_name :: Name -> Name in_name (UN n) = sMN 0 (str n ++ "_in") in_name (MN i n) = sMN i (str n ++ "_in") in_name (NS n s) = NS (in_name n) s in_name n = n -- | Creates a PArg with a given plicity, name, and term. asArg :: Plicity -> Name -> PTerm -> PArg asArg (Imp os _ _ _) n t = PImp 0 False os n t asArg (Exp os _ _) n t = PExp 0 os n t asArg (Constraint os _) n t = PConstraint 0 os n t asArg (TacImp os _ s) n t = PTacImplicit 0 os n s t -- | Machine name "rec". recName :: Name recName = sMN 0 "rec" recRef = PRef emptyFC [] recName projectInType :: [(Name, Name)] -> PTerm -> PTerm projectInType xs = mapPT st where st :: PTerm -> PTerm st (PRef fc hls n) | Just pn <- lookup n xs = PApp fc (PRef fc hls pn) [pexp recRef] st t = t -- | Creates an PArg from a plicity and a name where the term is a PRef. asPRefArg :: Plicity -> Name -> PArg asPRefArg p n = asArg p (nsroot n) $ PRef emptyFC [] (nsroot n)
uwap/Idris-dev
src/Idris/Elab/Record.hs
bsd-3-clause
20,222
0
22
6,073
6,392
3,408
2,984
314
13
module KAT_MiyaguchiPreneel (tests) where import Crypto.Cipher.AES (AES128) import Crypto.ConstructHash.MiyaguchiPreneel as MiyaguchiPreneel import Imports import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteArray as B import Data.ByteArray.Encoding (Base (Base16), convertFromBase) runMP128 :: ByteString -> ByteString runMP128 s = B.convert (MiyaguchiPreneel.compute s :: MiyaguchiPreneel AES128) hxs :: String -> ByteString hxs = either (error . ("hxs:" ++)) id . convertFromBase Base16 . B8.pack . filter (/= ' ') gAES128 :: TestTree gAES128 = igroup "aes128" [ runMP128 B8.empty @?= hxs "66e94bd4 ef8a2c3b 884cfa59 ca342b2e" , runMP128 (hxs "01000000 00000000 00000000 00000000") @?= hxs "46711816 e91d6ff0 59bbbf2b f58e0fd3" , runMP128 (hxs "00000000 00000000 00000000 00000001") @?= hxs "58e2fcce fa7e3061 367f1d57 a4e7455b" , runMP128 (hxs $ "00000000 00000000 00000000 00000000" ++ "01") @?= hxs "a5ff35ae 097adf5d 646abf5e bf4c16f4" ] igroup :: TestName -> [Assertion] -> TestTree igroup nm = testGroup nm . zipWith (flip ($)) [1..] . map icase where icase c i = testCase (show (i :: Int)) c vectors :: TestTree vectors = testGroup "KATs" [ gAES128 ] tests :: TestTree tests = testGroup "MiyaguchiPreneel" [ vectors ]
vincenthz/cryptonite
tests/KAT_MiyaguchiPreneel.hs
bsd-3-clause
1,405
0
11
333
367
201
166
36
1
{-# OPTIONS -fno-warn-orphans #-} -- | `DPrim` and `DT` instances for scalar types. module Data.Array.Parallel.Unlifted.Distributed.Data.Scalar.Base where import Data.Array.Parallel.Unlifted.Distributed.Primitive.DPrim import Data.Array.Parallel.Unlifted.Distributed.Primitive import Data.Word import qualified Data.Array.Parallel.Unlifted.Sequential.Vector as V import qualified Data.Vector.Unboxed.Mutable as MV import Prelude as P -- Integer ----------------------------------------------------------------------- -- FIXME: fake instances instance DPrim Integer instance DT Integer -- Char ----------------------------------------------------------------------- instance DPrim Char where mkDPrim = DChar unDPrim (DChar a) = a mkMDPrim = MDChar unMDPrim (MDChar a) = a instance DT Char where data Dist Char = DChar !(V.Vector Char) data MDist Char s = MDChar !(MV.STVector s Char) indexD = primIndexD newMD = primNewMD readMD = primReadMD writeMD = primWriteMD unsafeFreezeMD = primUnsafeFreezeMD sizeD = primSizeD sizeMD = primSizeMD -- Int ------------------------------------------------------------------------ instance DPrim Int where mkDPrim = DInt unDPrim (DInt a) = a mkMDPrim = MDInt unMDPrim (MDInt a) = a instance DT Int where data Dist Int = DInt !(V.Vector Int) data MDist Int s = MDInt !(MV.STVector s Int) indexD = primIndexD newMD = primNewMD readMD = primReadMD writeMD = primWriteMD unsafeFreezeMD = primUnsafeFreezeMD sizeD = primSizeD sizeMD = primSizeMD measureD n = "Int " P.++ show n -- Word8 ---------------------------------------------------------------------- instance DPrim Word8 where mkDPrim = DWord8 unDPrim (DWord8 a) = a mkMDPrim = MDWord8 unMDPrim (MDWord8 a) = a instance DT Word8 where data Dist Word8 = DWord8 !(V.Vector Word8) data MDist Word8 s = MDWord8 !(MV.STVector s Word8) indexD = primIndexD newMD = primNewMD readMD = primReadMD writeMD = primWriteMD unsafeFreezeMD = primUnsafeFreezeMD sizeD = primSizeD sizeMD = primSizeMD -- Float ---------------------------------------------------------------------- instance DPrim Float where mkDPrim = DFloat unDPrim (DFloat a) = a mkMDPrim = MDFloat unMDPrim (MDFloat a) = a instance DT Float where data Dist Float = DFloat !(V.Vector Float) data MDist Float s = MDFloat !(MV.STVector s Float) indexD = primIndexD newMD = primNewMD readMD = primReadMD writeMD = primWriteMD unsafeFreezeMD = primUnsafeFreezeMD sizeD = primSizeD sizeMD = primSizeMD -- Double --------------------------------------------------------------------- instance DPrim Double where mkDPrim = DDouble unDPrim (DDouble a) = a mkMDPrim = MDDouble unMDPrim (MDDouble a) = a instance DT Double where data Dist Double = DDouble !(V.Vector Double) data MDist Double s = MDDouble !(MV.STVector s Double) indexD = primIndexD newMD = primNewMD readMD = primReadMD writeMD = primWriteMD unsafeFreezeMD = primUnsafeFreezeMD sizeD = primSizeD sizeMD = primSizeMD
mainland/dph
dph-prim-par/Data/Array/Parallel/Unlifted/Distributed/Data/Scalar/Base.hs
bsd-3-clause
3,817
0
11
1,281
788
428
360
-1
-1
import Some d :: Int d = a * b
YoshikuniJujo/funpaala
samples/24_adt_module/useSome.hs
bsd-3-clause
32
0
5
11
18
10
8
3
1