code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
{-# LANGUAGE GeneralizedNewtypeDeriving, CPP, TypeSynonymInstances, FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Perfs
-- Copyright : (c)2011, Texas Instruments France
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : c-favergeon-borgialli@ti.com
-- Stability : provisional
-- Portability : portable
--
-- Functions for helping write and display performance tests
--
-----------------------------------------------------------------------------
module Perfs(
-- * Benchmark environment
Bench(..)
, Samples(..)
, Sample(..)
, classifySample
, newSample
, recordSample
, getBenchResults
, io
, simpleCurve
, graph
, Byte(..)
, AsByte(..)
) where
import qualified Data.Map as M
import Data.Monoid
import Control.Monad.Trans.Writer.Strict
import Benchmark
import TestTools
import Control.Monad(when)
import Control.Monad.IO.Class
import System.FilePath
import System.IO
import System.Cmd(system)
import Data.Int
type Sample = (Int,Double)
type Samples = [(String,Sample)]
type Bench a = WriterT Samples IO a
newtype Byte = Byte Int deriving(Eq,Num,Ord, Integral, Real, Enum)
instance Show Byte where
show (Byte s) = show s
class AsByte a where
toBytes :: a -> Byte
instance AsByte (CLInt s) where
toBytes _ = Byte 4
instance AsByte Int32 where
toBytes _ = Byte 4
instance AsByte (CLFloat s) where
toBytes _ = Byte 4
instance AsByte Float where
toBytes _ = Byte 4
instance AsByte [Float] where
toBytes l = toBytes (undefined :: Float) * fromIntegral (length l)
instance AsByte [Int32] where
toBytes l = toBytes (undefined :: Int32) * fromIntegral (length l)
instance AsByte Float4 where
toBytes _ = Byte 16
instance AsByte [Float4] where
toBytes l = toBytes (undefined :: Float4) * fromIntegral (length l)
instance AsByte (CLIntArray s) where
toBytes (CLIntArray l) = toBytes (undefined :: Int32) * fromIntegral (length l)
toBytes (CLConstIntArray l _) = toBytes (undefined :: Int32) * fromIntegral l
instance AsByte (CLFloatArray s) where
toBytes (CLFloatArray l) = toBytes (undefined :: Float) * fromIntegral (length l)
toBytes (CLConstFloatArray l _) = toBytes (undefined :: Float) * fromIntegral l
instance AsByte (CLFloat4Array s) where
toBytes (CLFloat4Array l) = toBytes (undefined :: Float4) * fromIntegral (length l)
toBytes (CLConstFloat4Array l _) = toBytes (undefined :: Float4) * fromIntegral l
newSample :: Sample -> Bench()
newSample s = tell [("",s)]
-- | Create a text file for R post processing
withR name = withFile (makeValid ("R" </> name)) WriteMode
-- | Create a R data file and process it using the simple.r script
-- to generate a y=f(x) curve for several clock values
simpleCurve :: (Num a , Num b)
=> String -- ^ Name
-> String -- ^ y
-> String -- ^ x
-> (Clocks -> IO [(a,b)])
-> IO ()
simpleCurve name x y a = do
withR (name <.> "dat") $ \h -> do
hPutStrLn h $ y ++ "," ++ x ++ ",cpu,mem,gpu"
forAllClocks (\_ c -> a c >>= writeResult h c)
system("./simple.r " ++ name)
return()
where
writeResult h c l = do
let Clocks cpu mem gpu = c
clockString = "," ++ show cpu ++ "," ++ show mem ++ "," ++ show gpu
writeSample (xa,ya) = hPutStrLn h $ show ya ++ "," ++ show xa ++ clockString
mapM_ writeSample l
-- | Create a R data file and process it using the graph.r script
graph :: String -- ^ Name
-> (Clocks -> IO [(Byte,TimingResult)])
-> IO ()
graph name a = do
withR (name <.> "dat") $ \h -> do
hPutStrLn h "b,nb,c,w,e,r,cpu,mem,gpu"
forAllClocks (\_ c -> a c >>= writeResult h c)
system("./graph.r " ++ name)
return()
where
writeResult h c l = do
let Clocks cpu mem gpu = c
clockString = "," ++ show cpu ++ "," ++ show mem ++ "," ++ show gpu
writeSample (bytes,(c,w,e,r)) = do
let clBandwidth = fromIntegral bytes / e * 1e-6
s = show clBandwidth ++ "," ++ show bytes ++ "," ++ show c ++ "," ++ show w ++ ","
++ show e ++ "," ++ show r ++ clockString
hPutStrLn h s
mapM_ writeSample l
-- | Classify a sample
classifySample :: String -> Bool -> Bench Sample -> Bench Sample
classifySample curve cond b = do
s <- b
when (cond) $ do
recordSample curve s
return s
-- | Record a new sample with classification
recordSample :: String -> Sample -> Bench ()
recordSample curve s = tell [(curve,s)]
getBenchResults :: Bench () -> IO Samples
getBenchResults b = execWriterT b
#ifdef OMAP4
-- | Generate different benchmark for different clock values
forAllClocks :: MonadIO m => (String -> Clocks -> m ()) -> m ()
forAllClocks b = do
io $ putStrLn " CPU 1GHz, L3 200MHz, DDR 400MHz, GPU 307MHz"
b "CPU 1GHz, L3 200MHz, DDR 400MHz, GPU 307MHz" defaultClocks
io $ putStrLn " CPU 800MHz"
b "CPU 800MHz, L3 200MHz, DDR 400MHz, GPU 307MHz" (defaultClocks {cpuClock = CPU_800MHz})
io $ putStrLn " L3 100MHz, DDR 200MHz"
b "CPU 1GHz, L3 100MHz, DDR 200MHz, GPU 307MHz" (defaultClocks {memClock = MEM_200MHz})
io $ putStrLn " GPU 192MHz"
b "CPU 1GHz, L3 200MHz, DDR 400 MHz, GPU 192MHz" (defaultClocks {gpuClock = GPU_192MHz})
io $ putStrLn " CPU 800MHz, L3 100MHz, DDR 200 MHz, GPU 192MHz"
b "CPU 800MHz, L3 100MHz, DDR 200 MHz, GPU 192MHz" (defaultClocks {cpuClock = CPU_800MHz, memClock = MEM_200MHz, gpuClock = GPU_192MHz})
#else
-- | Generate different benchmark for different clock values
forAllClocks :: (String -> Clocks -> Bench()) -> Bench ()
forAllClocks b = b "Standard clocks" defaultClocks
#endif
|
ChristopheF/OpenCLTestFramework
|
Client/Perfs.hs
|
Haskell
|
bsd-3-clause
| 5,643
|
{-# LANGUAGE TemplateHaskell #-}
module Chess.Search.SearchResult
( SearchResult(..)
, (<@>)
, (<++>)
, first
, second
, eval
, moves
) where
import Control.Lens
import Control.Monad
import Data.Maybe
import qualified Chess.Move as M
-- | Represents the result of a Search
data SearchResult = SearchResult
{ _moves :: ! [ M.Move ]
, _eval :: ! Int
}
$(makeLenses ''SearchResult)
-- | modifies eval in a SearchResult, in a monadic computation
(<@>) :: (Monad m) => (Int -> Int) -> m (Maybe SearchResult) -> m (Maybe SearchResult)
f <@> m = liftM ((_Just . eval) %~ f) m
-- | Prepends a Move to a SearchResult
(<++>) :: Monad m => M.Move -> m (Maybe SearchResult) -> m (Maybe SearchResult)
x <++> m = liftM (_Just . moves %~ (x:)) m
-- | The first Move of a SearchResult
first :: SearchResult -> Maybe M.Move
first = listToMaybe . view moves
-- | The second Move of a SearchResult
second :: SearchResult -> Maybe M.Move
second sr = case sr^.moves of
_:m:_ -> Just m
_ -> Nothing
|
phaul/chess
|
Chess/Search/SearchResult.hs
|
Haskell
|
bsd-3-clause
| 1,147
|
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}
{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}
module Paths_HaskellEngine (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/bin"
libdir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/lib/x86_64-osx-ghc-8.0.1/HaskellEngine-0.1.0.0"
datadir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/share/x86_64-osx-ghc-8.0.1/HaskellEngine-0.1.0.0"
libexecdir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/libexec"
sysconfdir = "/Users/user/Desktop/HaskellEngine/.cabal-sandbox/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "HaskellEngine_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "HaskellEngine_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "HaskellEngine_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "HaskellEngine_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "HaskellEngine_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
|
MyForteIsTimeTravel/HaskellEngine
|
dist/build/autogen/Paths_HaskellEngine.hs
|
Haskell
|
bsd-3-clause
| 1,816
|
myNot True = False
myNot False = True
sumList (x:xs) = x + sumList xs
sumList [] = 0
|
NeonGraal/rwh-stack
|
ch03/add.hs
|
Haskell
|
bsd-3-clause
| 90
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module KMC.Util.Bits ( DoubleBits(combine, split), packCombine, unpackSplit ) where
import Data.Bits (shift, (.|.), (.&.), complement, finiteBitSize, clearBit, Bits(bit), FiniteBits)
import Data.Word (Word8, Word16, Word32, Word64)
-- | Pack two 8-bit words in a 16-bit word, two 16-bit words in a 32-bit word,
-- etc. Split a 16-bit word into two 8-bit words, etc.
class (FiniteBits b, Enum b, FiniteBits (Twice b), Enum (Twice b)) => DoubleBits b where
type Twice b :: *
combine :: (b, b) -> Twice b
combine (w1, w2) = (castWord w1 `shift` (finiteBitSize w1)) .|. (castWord w2)
-- The actual split implementation requires a zero element of the correct
-- type, so the type checker knows which instance to pick.
split' :: b -> Twice b -> (b, b)
split' z w = ( castWord $ (w .&. hi) `shift` (negate (finiteBitSize w `div` 2))
, castWord $ w .&. lo
)
where
hi = combine (complement z, z)
lo = combine (z, complement z)
split :: (Twice b) -> (b, b)
-- The implementation is just split' but with a type-annotated zero element
-- given to make the type checker happy. It complains about Twice being
-- non-injective, so we help it with type annotations in the instances.
zeroBits :: (Bits a) => a
zeroBits = clearBit (bit 0) 0
instance DoubleBits Word8 where
type Twice Word8 = Word16
split = split' (zeroBits :: Word8)
instance DoubleBits Word16 where
type Twice Word16 = Word32
split = split' (zeroBits :: Word16)
instance DoubleBits Word32 where
type Twice Word32 = Word64
split = split' (zeroBits :: Word32)
packCombine :: (DoubleBits b) => b -> [b] -> [Twice b]
packCombine _ [] = []
packCombine end (w1:w2:ws) = combine (w1, w2) : packCombine end ws
packCombine end [w1] = [combine (w1, end)]
unpackSplit :: (DoubleBits b) => [Twice b] -> [b]
unpackSplit = concatMap ((\(x,y) -> [x,y]) . split)
castWord :: (Enum a, Enum b) => a -> b
castWord = toEnum . fromEnum
|
diku-kmc/repg
|
src/KMC/Util/Bits.hs
|
Haskell
|
mit
| 2,101
|
module Main where
import Web.GitHub.CLI.Options
import Web.GitHub.CLI.Actions
import Options.Applicative
import Network.Octohat.Types (OrganizationName(..), TeamName(..))
import qualified Data.Text as T (pack)
accessBotCLI :: TeamOptions -> IO ()
accessBotCLI (TeamOptions (ListTeams nameOfOrg)) =
findTeamsInOrganization (OrganizationName $ T.pack nameOfOrg)
accessBotCLI (TeamOptions (ListMembers nameOfOrg nameOfTeam)) =
findMembersInTeam (OrganizationName $ T.pack nameOfOrg) (TeamName $ T.pack nameOfTeam)
accessBotCLI (TeamOptions (AddToTeam nameOfOrg nameOfTeam nameOfUser)) =
addUserToTeamInOrganization nameOfUser
(OrganizationName $ T.pack nameOfOrg)
(TeamName $ T.pack nameOfTeam)
accessBotCLI (TeamOptions (DeleteFromTeam nameOfOrg nameOfTeam nameOfUser)) =
deleteUserFromTeamInOrganization nameOfUser
(OrganizationName $ T.pack nameOfOrg)
(TeamName $ T.pack nameOfTeam)
main :: IO ()
main = execParser argumentsParser >>= accessBotCLI
argumentsParser :: ParserInfo TeamOptions
argumentsParser = info (helper <*> teamOptions)
(fullDesc
<> progDesc "GitHub client to manage teams. Please specify your token as GITHUB_TOKEN"
<> header "Some options"
)
|
stackbuilders/octohat
|
src-demo/Web/GitHub/CLI/Main.hs
|
Haskell
|
mit
| 1,385
|
import Universum
import Test.Hspec (hspec)
import Spec (spec)
main :: IO ()
main =
hspec spec
|
input-output-hk/pos-haskell-prototype
|
util/test/test.hs
|
Haskell
|
mit
| 131
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Stack.Options
(BuildCommand(..)
,GlobalOptsContext(..)
,benchOptsParser
,buildOptsParser
,cleanOptsParser
,configCmdSetParser
,configOptsParser
,dockerOptsParser
,dockerCleanupOptsParser
,dotOptsParser
,execOptsParser
,evalOptsParser
,globalOptsParser
,initOptsParser
,newOptsParser
,nixOptsParser
,logLevelOptsParser
,ghciOptsParser
,solverOptsParser
,testOptsParser
,hpcReportOptsParser
,pvpBoundsOption
,globalOptsFromMonoid
,splitObjsWarning
) where
import Control.Monad.Logger (LogLevel (..))
import Data.Char (isSpace, toLower, toUpper)
import Data.List (intercalate)
import Data.List.Split (splitOn)
import qualified Data.Map as Map
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid.Extra
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Text.Read (decimal)
import Distribution.Version (anyVersion)
import Options.Applicative
import Options.Applicative.Args
import Options.Applicative.Builder.Extra
import Options.Applicative.Types (fromM, oneM, readerAsk)
import Path
import Stack.Build (splitObjsWarning)
import Stack.Clean (CleanOpts (..))
import Stack.Config (packagesParser)
import Stack.ConfigCmd
import Stack.Constants
import Stack.Coverage (HpcReportOpts (..))
import Stack.Docker
import qualified Stack.Docker as Docker
import Stack.Dot
import Stack.Ghci (GhciOpts (..))
import Stack.Init
import Stack.New
import Stack.Nix
import Stack.Types
import Stack.Types.TemplateName
-- | Allows adjust global options depending on their context
-- Note: This was being used to remove ambibuity between the local and global
-- implementation of stack init --resolver option. Now that stack init has no
-- local --resolver this is not being used anymore but the code is kept for any
-- similar future use cases.
data GlobalOptsContext
= OuterGlobalOpts -- ^ Global options before subcommand name
| OtherCmdGlobalOpts -- ^ Global options following any other subcommand
| BuildCmdGlobalOpts
deriving (Show, Eq)
-- | Parser for bench arguments.
-- FIXME hiding options
benchOptsParser :: Bool -> Parser BenchmarkOptsMonoid
benchOptsParser hide0 = BenchmarkOptsMonoid
<$> optionalFirst (strOption (long "benchmark-arguments" <>
metavar "BENCH_ARGS" <>
help ("Forward BENCH_ARGS to the benchmark suite. " <>
"Supports templates from `cabal bench`") <>
hide))
<*> optionalFirst (switch (long "no-run-benchmarks" <>
help "Disable running of benchmarks. (Benchmarks will still be built.)" <>
hide))
where hide = hideMods hide0
-- | Parser for CLI-only build arguments
buildOptsParser :: BuildCommand
-> Parser BuildOptsCLI
buildOptsParser cmd =
BuildOptsCLI <$>
many
(textArgument
(metavar "TARGET" <>
help "If none specified, use all packages")) <*>
switch
(long "dry-run" <>
help "Don't build anything, just prepare to") <*>
((\x y z ->
concat [x, y, z]) <$>
flag
[]
["-Wall", "-Werror"]
(long "pedantic" <>
help "Turn on -Wall and -Werror") <*>
flag
[]
["-O0"]
(long "fast" <>
help "Turn off optimizations (-O0)") <*>
many
(textOption
(long "ghc-options" <>
metavar "OPTION" <>
help "Additional options passed to GHC"))) <*>
(Map.unionsWith Map.union <$>
many
(option
readFlag
(long "flag" <>
metavar "PACKAGE:[-]FLAG" <>
help
("Override flags set in stack.yaml " <>
"(applies to local packages and extra-deps)")))) <*>
(flag'
BSOnlyDependencies
(long "dependencies-only" <>
help "A synonym for --only-dependencies") <|>
flag'
BSOnlySnapshot
(long "only-snapshot" <>
help
"Only build packages for the snapshot database, not the local database") <|>
flag'
BSOnlyDependencies
(long "only-dependencies" <>
help
"Only build packages that are dependencies of targets on the command line") <|>
pure BSAll) <*>
(flag'
FileWatch
(long "file-watch" <>
help
"Watch for changes in local files and automatically rebuild. Ignores files in VCS boring/ignore file") <|>
flag'
FileWatchPoll
(long "file-watch-poll" <>
help
"Like --file-watch, but polling the filesystem instead of using events") <|>
pure NoFileWatch) <*>
many (cmdOption
(long "exec" <>
metavar "CMD [ARGS]" <>
help "Command and arguments to run after a successful build")) <*>
switch
(long "only-configure" <>
help
"Only perform the configure step, not any builds. Intended for tool usage, may break when used on multiple packages at once!") <*>
pure cmd
-- | Parser for package:[-]flag
readFlag :: ReadM (Map (Maybe PackageName) (Map FlagName Bool))
readFlag = do
s <- readerAsk
case break (== ':') s of
(pn, ':':mflag) -> do
pn' <-
case parsePackageNameFromString pn of
Nothing
| pn == "*" -> return Nothing
| otherwise -> readerError $ "Invalid package name: " ++ pn
Just x -> return $ Just x
let (b, flagS) =
case mflag of
'-':x -> (False, x)
_ -> (True, mflag)
flagN <-
case parseFlagNameFromString flagS of
Nothing -> readerError $ "Invalid flag name: " ++ flagS
Just x -> return x
return $ Map.singleton pn' $ Map.singleton flagN b
_ -> readerError "Must have a colon"
-- | Command-line parser for the clean command.
cleanOptsParser :: Parser CleanOpts
cleanOptsParser = CleanShallow <$> packages <|> doFullClean
where
packages =
many
(packageNameArgument
(metavar "PACKAGE" <>
help "If none specified, clean all local packages"))
doFullClean =
flag'
CleanFull
(long "full" <>
help "Delete all work directories (.stack-work by default) in the project")
-- | Command-line arguments parser for configuration.
configOptsParser :: GlobalOptsContext -> Parser ConfigMonoid
configOptsParser hide0 =
(\stackRoot workDir buildOpts dockerOpts nixOpts systemGHC installGHC arch os ghcVariant jobs includes libs skipGHCCheck skipMsys localBin modifyCodePage allowDifferentUser -> mempty
{ configMonoidStackRoot = stackRoot
, configMonoidWorkDir = workDir
, configMonoidBuildOpts = buildOpts
, configMonoidDockerOpts = dockerOpts
, configMonoidNixOpts = nixOpts
, configMonoidSystemGHC = systemGHC
, configMonoidInstallGHC = installGHC
, configMonoidSkipGHCCheck = skipGHCCheck
, configMonoidArch = arch
, configMonoidOS = os
, configMonoidGHCVariant = ghcVariant
, configMonoidJobs = jobs
, configMonoidExtraIncludeDirs = includes
, configMonoidExtraLibDirs = libs
, configMonoidSkipMsys = skipMsys
, configMonoidLocalBinPath = localBin
, configMonoidModifyCodePage = modifyCodePage
, configMonoidAllowDifferentUser = allowDifferentUser
})
<$> optionalFirst (option readAbsDir
( long stackRootOptionName
<> metavar (map toUpper stackRootOptionName)
<> help ("Absolute path to the global stack root directory " ++
"(Overrides any STACK_ROOT environment variable)")
<> hide
))
<*> optionalFirst (strOption
( long "work-dir"
<> metavar "WORK-DIR"
<> help "Override work directory (default: .stack-work)"
<> hide
))
<*> buildOptsMonoidParser (hide0 /= BuildCmdGlobalOpts)
<*> dockerOptsParser True
<*> nixOptsParser True
<*> firstBoolFlags
"system-ghc"
"using the system installed GHC (on the PATH) if available and a matching version"
hide
<*> firstBoolFlags
"install-ghc"
"downloading and installing GHC if necessary (can be done manually with stack setup)"
hide
<*> optionalFirst (strOption
( long "arch"
<> metavar "ARCH"
<> help "System architecture, e.g. i386, x86_64"
<> hide
))
<*> optionalFirst (strOption
( long "os"
<> metavar "OS"
<> help "Operating system, e.g. linux, windows"
<> hide
))
<*> optionalFirst (ghcVariantParser (hide0 /= OuterGlobalOpts))
<*> optionalFirst (option auto
( long "jobs"
<> short 'j'
<> metavar "JOBS"
<> help "Number of concurrent jobs to run"
<> hide
))
<*> fmap Set.fromList (many (textOption
( long "extra-include-dirs"
<> metavar "DIR"
<> help "Extra directories to check for C header files"
<> hide
)))
<*> fmap Set.fromList (many (textOption
( long "extra-lib-dirs"
<> metavar "DIR"
<> help "Extra directories to check for libraries"
<> hide
)))
<*> firstBoolFlags
"skip-ghc-check"
"skipping the GHC version and architecture check"
hide
<*> firstBoolFlags
"skip-msys"
"skipping the local MSYS installation (Windows only)"
hide
<*> optionalFirst (strOption
( long "local-bin-path"
<> metavar "DIR"
<> help "Install binaries to DIR"
<> hide
))
<*> firstBoolFlags
"modify-code-page"
"setting the codepage to support UTF-8 (Windows only)"
hide
<*> firstBoolFlags
"allow-different-user"
("permission for users other than the owner of the stack root " ++
"directory to use a stack installation (POSIX only)")
hide
where hide = hideMods (hide0 /= OuterGlobalOpts)
readAbsDir :: ReadM (Path Abs Dir)
readAbsDir = do
s <- readerAsk
case parseAbsDir s of
Just p -> return p
Nothing ->
readerError
("Failed to parse absolute path to directory: '" ++ s ++ "'")
buildOptsMonoidParser :: Bool -> Parser BuildOptsMonoid
buildOptsMonoidParser hide0 =
transform <$> trace <*> profile <*> options
where
hide =
hideMods hide0
transform tracing profiling =
enable
where
enable opts
| tracing || profiling =
opts
{ buildMonoidLibProfile = First (Just True)
, buildMonoidExeProfile = First (Just True)
, buildMonoidBenchmarkOpts = bopts
{ beoMonoidAdditionalArgs = First (getFirst (beoMonoidAdditionalArgs bopts) <>
Just (" " <> unwords additionalArgs))
}
, buildMonoidTestOpts = topts
{ toMonoidAdditionalArgs = (toMonoidAdditionalArgs topts) <>
additionalArgs
}
}
| otherwise =
opts
where
bopts =
buildMonoidBenchmarkOpts opts
topts =
buildMonoidTestOpts opts
additionalArgs =
"+RTS" : catMaybes [trac, prof, Just "-RTS"]
trac =
if tracing
then Just "-xc"
else Nothing
prof =
if profiling
then Just "-p"
else Nothing
profile =
flag
False
True
(long "profile" <>
help
"Enable profiling in libraries, executables, etc. \
\for all expressions and generate a profiling report\
\ in exec or benchmarks" <>
hide)
trace =
flag
False
True
(long "trace" <>
help
"Enable profiling in libraries, executables, etc. \
\for all expressions and generate a backtrace on \
\exception" <>
hide)
options =
BuildOptsMonoid <$> libProfiling <*> exeProfiling <*> haddock <*> openHaddocks <*>
haddockDeps <*> copyBins <*> preFetch <*> keepGoing <*> forceDirty <*>
tests <*> testOptsParser hide0 <*> benches <*> benchOptsParser hide0 <*> reconfigure <*>
cabalVerbose <*> splitObjs
libProfiling =
firstBoolFlags
"library-profiling"
"library profiling for TARGETs and all its dependencies"
hide
exeProfiling =
firstBoolFlags
"executable-profiling"
"executable profiling for TARGETs and all its dependencies"
hide
haddock =
firstBoolFlags
"haddock"
"generating Haddocks the package(s) in this directory/configuration"
hide
openHaddocks =
firstBoolFlags
"open"
"opening the local Haddock documentation in the browser"
hide
haddockDeps =
firstBoolFlags "haddock-deps" "building Haddocks for dependencies" hide
copyBins =
firstBoolFlags
"copy-bins"
"copying binaries to the local-bin-path (see 'stack path')"
hide
keepGoing =
firstBoolFlags
"keep-going"
"continue running after a step fails (default: false for build, true for test/bench)"
hide
preFetch =
firstBoolFlags
"prefetch"
"Fetch packages necessary for the build immediately, useful with --dry-run"
hide
forceDirty =
firstBoolFlags
"force-dirty"
"Force treating all local packages as having dirty files (useful for cases where stack can't detect a file change"
hide
tests =
firstBoolFlags
"test"
"testing the package(s) in this directory/configuration"
hide
benches =
firstBoolFlags
"bench"
"benchmarking the package(s) in this directory/configuration"
hide
reconfigure =
firstBoolFlags
"reconfigure"
"Perform the configure step even if unnecessary. Useful in some corner cases with custom Setup.hs files"
hide
cabalVerbose =
firstBoolFlags
"cabal-verbose"
"Ask Cabal to be verbose in its output"
hide
splitObjs =
firstBoolFlags
"split-objs"
("Enable split-objs, to reduce output size (at the cost of build time). " ++ splitObjsWarning)
hide
nixOptsParser :: Bool -> Parser NixOptsMonoid
nixOptsParser hide0 = overrideActivation <$>
(NixOptsMonoid
<$> pure (Any False)
<*> firstBoolFlags nixCmdName
"use of a Nix-shell"
hide
<*> firstBoolFlags "nix-pure"
"use of a pure Nix-shell"
hide
<*> optionalFirst
(textArgsOption
(long "nix-packages" <>
metavar "NAMES" <>
help "List of packages that should be available in the nix-shell (space separated)" <>
hide))
<*> optionalFirst
(option
str
(long "nix-shell-file" <>
metavar "FILEPATH" <>
help "Nix file to be used to launch a nix-shell (for regular Nix users)" <>
hide))
<*> optionalFirst
(textArgsOption
(long "nix-shell-options" <>
metavar "OPTIONS" <>
help "Additional options passed to nix-shell" <>
hide))
<*> optionalFirst
(textArgsOption
(long "nix-path" <>
metavar "PATH_OPTIONS" <>
help "Additional options to override NIX_PATH parts (notably 'nixpkgs')" <>
hide))
)
where
hide = hideMods hide0
overrideActivation m =
if m /= mempty then m { nixMonoidEnable = (First . Just . fromFirst True) (nixMonoidEnable m) }
else m
textArgsOption = fmap (map T.pack) . argsOption
-- | Options parser configuration for Docker.
dockerOptsParser :: Bool -> Parser DockerOptsMonoid
dockerOptsParser hide0 =
DockerOptsMonoid
<$> pure (Any False)
<*> firstBoolFlags dockerCmdName
"using a Docker container"
hide
<*> fmap First
((Just . DockerMonoidRepo) <$> option str (long (dockerOptName dockerRepoArgName) <>
hide <>
metavar "NAME" <>
help "Docker repository name") <|>
(Just . DockerMonoidImage) <$> option str (long (dockerOptName dockerImageArgName) <>
hide <>
metavar "IMAGE" <>
help "Exact Docker image ID (overrides docker-repo)") <|>
pure Nothing)
<*> firstBoolFlags (dockerOptName dockerRegistryLoginArgName)
"registry requires login"
hide
<*> firstStrOption (long (dockerOptName dockerRegistryUsernameArgName) <>
hide <>
metavar "USERNAME" <>
help "Docker registry username")
<*> firstStrOption (long (dockerOptName dockerRegistryPasswordArgName) <>
hide <>
metavar "PASSWORD" <>
help "Docker registry password")
<*> firstBoolFlags (dockerOptName dockerAutoPullArgName)
"automatic pulling latest version of image"
hide
<*> firstBoolFlags (dockerOptName dockerDetachArgName)
"running a detached Docker container"
hide
<*> firstBoolFlags (dockerOptName dockerPersistArgName)
"not deleting container after it exits"
hide
<*> firstStrOption (long (dockerOptName dockerContainerNameArgName) <>
hide <>
metavar "NAME" <>
help "Docker container name")
<*> argsOption (long (dockerOptName dockerRunArgsArgName) <>
hide <>
value [] <>
metavar "'ARG1 [ARG2 ...]'" <>
help "Additional options to pass to 'docker run'")
<*> many (option auto (long (dockerOptName dockerMountArgName) <>
hide <>
metavar "(PATH | HOST-PATH:CONTAINER-PATH)" <>
help ("Mount volumes from host in container " ++
"(may specify multiple times)")))
<*> many (option str (long (dockerOptName dockerEnvArgName) <>
hide <>
metavar "NAME=VALUE" <>
help ("Set environment variable in container " ++
"(may specify multiple times)")))
<*> firstStrOption (long (dockerOptName dockerDatabasePathArgName) <>
hide <>
metavar "PATH" <>
help "Location of image usage tracking database")
<*> firstStrOption
(long(dockerOptName dockerStackExeArgName) <>
hide <>
metavar (intercalate "|"
[ dockerStackExeDownloadVal
, dockerStackExeHostVal
, dockerStackExeImageVal
, "PATH" ]) <>
help (concat [ "Location of "
, stackProgName
, " executable used in container" ]))
<*> firstBoolFlags (dockerOptName dockerSetUserArgName)
"setting user in container to match host"
hide
<*> pure (IntersectingVersionRange anyVersion)
where
dockerOptName optName = dockerCmdName ++ "-" ++ T.unpack optName
firstStrOption = optionalFirst . option str
hide = hideMods hide0
-- | Parser for docker cleanup arguments.
dockerCleanupOptsParser :: Parser Docker.CleanupOpts
dockerCleanupOptsParser =
Docker.CleanupOpts <$>
(flag' Docker.CleanupInteractive
(short 'i' <>
long "interactive" <>
help "Show cleanup plan in editor and allow changes (default)") <|>
flag' Docker.CleanupImmediate
(short 'y' <>
long "immediate" <>
help "Immediately execute cleanup plan") <|>
flag' Docker.CleanupDryRun
(short 'n' <>
long "dry-run" <>
help "Display cleanup plan but do not execute") <|>
pure Docker.CleanupInteractive) <*>
opt (Just 14) "known-images" "LAST-USED" <*>
opt Nothing "unknown-images" "CREATED" <*>
opt (Just 0) "dangling-images" "CREATED" <*>
opt Nothing "stopped-containers" "CREATED" <*>
opt Nothing "running-containers" "CREATED"
where opt def' name mv =
fmap Just
(option auto
(long name <>
metavar (mv ++ "-DAYS-AGO") <>
help ("Remove " ++
toDescr name ++
" " ++
map toLower (toDescr mv) ++
" N days ago" ++
case def' of
Just n -> " (default " ++ show n ++ ")"
Nothing -> ""))) <|>
flag' Nothing
(long ("no-" ++ name) <>
help ("Do not remove " ++
toDescr name ++
case def' of
Just _ -> ""
Nothing -> " (default)")) <|>
pure def'
toDescr = map (\c -> if c == '-' then ' ' else c)
-- | Parser for arguments to `stack dot`
dotOptsParser :: Parser DotOpts
dotOptsParser = DotOpts
<$> includeExternal
<*> includeBase
<*> depthLimit
<*> fmap (maybe Set.empty Set.fromList . fmap splitNames) prunedPkgs
where includeExternal = boolFlags False
"external"
"inclusion of external dependencies"
idm
includeBase = boolFlags True
"include-base"
"inclusion of dependencies on base"
idm
depthLimit =
optional (option auto
(long "depth" <>
metavar "DEPTH" <>
help ("Limit the depth of dependency resolution " <>
"(Default: No limit)")))
prunedPkgs = optional (strOption
(long "prune" <>
metavar "PACKAGES" <>
help ("Prune each package name " <>
"from the comma separated list " <>
"of package names PACKAGES")))
splitNames :: String -> [String]
splitNames = map (takeWhile (not . isSpace) . dropWhile isSpace) . splitOn ","
ghciOptsParser :: Parser GhciOpts
ghciOptsParser = GhciOpts
<$> switch (long "no-build" <> help "Don't build before launching GHCi")
<*> fmap concat (many (argsOption (long "ghci-options" <>
metavar "OPTION" <>
help "Additional options passed to GHCi")))
<*> optional
(strOption (long "with-ghc" <>
metavar "GHC" <>
help "Use this GHC to run GHCi"))
<*> (not <$> boolFlags True "load" "load modules on start-up" idm)
<*> packagesParser
<*> optional
(textOption
(long "main-is" <>
metavar "TARGET" <>
help "Specify which target should contain the main \
\module to load, such as for an executable for \
\test suite or benchmark."))
<*> switch (long "load-local-deps" <> help "Load all local dependencies of your targets")
<*> switch (long "skip-intermediate-deps" <> help "Skip loading intermediate target dependencies")
<*> boolFlags True "package-hiding" "package hiding" idm
<*> buildOptsParser Build
-- | Parser for exec command
execOptsParser :: Maybe SpecialExecCmd -> Parser ExecOpts
execOptsParser mcmd =
ExecOpts
<$> maybe eoCmdParser pure mcmd
<*> eoArgsParser
<*> execOptsExtraParser
where
eoCmdParser = ExecCmd <$> strArgument (metavar "CMD")
eoArgsParser = many (strArgument (metavar "-- ARGS (e.g. stack ghc -- X.hs -o x)"))
evalOptsParser :: String -- ^ metavar
-> Parser EvalOpts
evalOptsParser meta =
EvalOpts
<$> eoArgsParser
<*> execOptsExtraParser
where
eoArgsParser :: Parser String
eoArgsParser = strArgument (metavar meta)
-- | Parser for extra options to exec command
execOptsExtraParser :: Parser ExecOptsExtra
execOptsExtraParser = eoPlainParser <|>
ExecOptsEmbellished
<$> eoEnvSettingsParser
<*> eoPackagesParser
where
eoEnvSettingsParser :: Parser EnvSettings
eoEnvSettingsParser = EnvSettings
<$> pure True
<*> boolFlags True
"ghc-package-path"
"setting the GHC_PACKAGE_PATH variable for the subprocess"
idm
<*> boolFlags True
"stack-exe"
"setting the STACK_EXE environment variable to the path for the stack executable"
idm
<*> pure False
eoPackagesParser :: Parser [String]
eoPackagesParser = many (strOption (long "package" <> help "Additional packages that must be installed"))
eoPlainParser :: Parser ExecOptsExtra
eoPlainParser = flag' ExecOptsPlain
(long "plain" <>
help "Use an unmodified environment (only useful with Docker)")
-- | Parser for global command-line options.
globalOptsParser :: GlobalOptsContext -> Maybe LogLevel -> Parser GlobalOptsMonoid
globalOptsParser kind defLogLevel =
GlobalOptsMonoid <$>
optionalFirst (strOption (long Docker.reExecArgName <> hidden <> internal)) <*>
optionalFirst (option auto (long dockerEntrypointArgName <> hidden <> internal)) <*>
(First <$> logLevelOptsParser hide0 defLogLevel) <*>
configOptsParser kind <*>
optionalFirst (abstractResolverOptsParser hide0) <*>
optionalFirst (compilerOptsParser hide0) <*>
firstBoolFlags
"terminal"
"overriding terminal detection in the case of running in a false terminal"
hide <*>
optionalFirst
(strOption
(long "stack-yaml" <>
metavar "STACK-YAML" <>
help ("Override project stack.yaml file " <>
"(overrides any STACK_YAML environment variable)") <>
hide))
where
hide = hideMods hide0
hide0 = kind /= OuterGlobalOpts
-- | Create GlobalOpts from GlobalOptsMonoid.
globalOptsFromMonoid :: Bool -> GlobalOptsMonoid -> GlobalOpts
globalOptsFromMonoid defaultTerminal GlobalOptsMonoid{..} = GlobalOpts
{ globalReExecVersion = getFirst globalMonoidReExecVersion
, globalDockerEntrypoint = getFirst globalMonoidDockerEntrypoint
, globalLogLevel = fromFirst defaultLogLevel globalMonoidLogLevel
, globalConfigMonoid = globalMonoidConfigMonoid
, globalResolver = getFirst globalMonoidResolver
, globalCompiler = getFirst globalMonoidCompiler
, globalTerminal = fromFirst defaultTerminal globalMonoidTerminal
, globalStackYaml = getFirst globalMonoidStackYaml }
initOptsParser :: Parser InitOpts
initOptsParser =
InitOpts <$> searchDirs
<*> solver <*> omitPackages
<*> overwrite <*> fmap not ignoreSubDirs
where
searchDirs =
many (textArgument
(metavar "DIRS" <>
help "Directories to include, default is current directory."))
ignoreSubDirs = switch (long "ignore-subdirs" <>
help "Do not search for .cabal files in sub directories")
overwrite = switch (long "force" <>
help "Force overwriting an existing stack.yaml")
omitPackages = switch (long "omit-packages" <>
help "Exclude conflicting or incompatible user packages")
solver = switch (long "solver" <>
help "Use a dependency solver to determine extra dependencies")
-- | 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)
-- | Parser for the resolver
abstractResolverOptsParser :: Bool -> Parser AbstractResolver
abstractResolverOptsParser hide =
option readAbstractResolver
(long "resolver" <>
metavar "RESOLVER" <>
help "Override resolver in project file" <>
hideMods hide)
readAbstractResolver :: ReadM AbstractResolver
readAbstractResolver = do
s <- readerAsk
case s of
"global" -> return ARGlobal
"nightly" -> return ARLatestNightly
"lts" -> return ARLatestLTS
'l':'t':'s':'-':x | Right (x', "") <- decimal $ T.pack x ->
return $ ARLatestLTSMajor x'
_ ->
case parseResolverText $ T.pack s of
Left e -> readerError $ show e
Right x -> return $ ARResolver x
compilerOptsParser :: Bool -> Parser CompilerVersion
compilerOptsParser hide =
option readCompilerVersion
(long "compiler" <>
metavar "COMPILER" <>
help "Use the specified compiler" <>
hideMods hide)
readCompilerVersion :: ReadM CompilerVersion
readCompilerVersion = do
s <- readerAsk
case parseCompilerVersion (T.pack s) of
Nothing -> readerError $ "Failed to parse compiler: " ++ s
Just x -> return x
-- | GHC variant parser
ghcVariantParser :: Bool -> Parser GHCVariant
ghcVariantParser hide =
option
readGHCVariant
(long "ghc-variant" <> metavar "VARIANT" <>
help
"Specialized GHC variant, e.g. integersimple (implies --no-system-ghc)" <>
hideMods hide
)
where
readGHCVariant = do
s <- readerAsk
case parseGHCVariant s of
Left e -> readerError (show e)
Right v -> return v
-- | Parser for @solverCmd@
solverOptsParser :: Parser Bool
solverOptsParser = boolFlags False
"update-config"
"Automatically update stack.yaml with the solver's recommendations"
idm
-- | Parser for test arguments.
-- FIXME hide args
testOptsParser :: Bool -> Parser TestOptsMonoid
testOptsParser hide0 =
TestOptsMonoid
<$> firstBoolFlags
"rerun-tests"
"running already successful tests"
hide
<*> fmap
(fromMaybe [])
(optional
(argsOption
(long "test-arguments" <>
metavar "TEST_ARGS" <>
help "Arguments passed in to the test suite program" <>
hide)))
<*> optionalFirst
(switch
(long "coverage" <>
help "Generate a code coverage report" <>
hide))
<*> optionalFirst
(switch
(long "no-run-tests" <>
help "Disable running of tests. (Tests will still be built.)" <>
hide))
where hide = hideMods hide0
-- | Parser for @stack new@.
newOptsParser :: Parser (NewOpts,InitOpts)
newOptsParser = (,) <$> newOpts <*> initOptsParser
where
newOpts =
NewOpts <$>
packageNameArgument
(metavar "PACKAGE_NAME" <> help "A valid package name.") <*>
switch
(long "bare" <>
help "Do not create a subdirectory for the project") <*>
optional (templateNameArgument
(metavar "TEMPLATE_NAME" <>
help "Name of a template or a local template in a file or a URL.\
\ For example: foo or foo.hsfiles or ~/foo or\
\ https://example.com/foo.hsfiles")) <*>
fmap
M.fromList
(many
(templateParamArgument
(short 'p' <> long "param" <> metavar "KEY:VALUE" <>
help
"Parameter for the template in the format key:value")))
-- | Parser for @stack hpc report@.
hpcReportOptsParser :: Parser HpcReportOpts
hpcReportOptsParser = HpcReportOpts
<$> many (textArgument $ metavar "TARGET_OR_TIX")
<*> switch (long "all" <> help "Use results from all packages and components")
<*> optional (strOption (long "destdir" <> help "Output directy for HTML report"))
pvpBoundsOption :: Parser PvpBounds
pvpBoundsOption =
option
readPvpBounds
(long "pvp-bounds" <> metavar "PVP-BOUNDS" <>
help
"How PVP version bounds should be added to .cabal file: none, lower, upper, both")
where
readPvpBounds = do
s <- readerAsk
case parsePvpBounds $ T.pack s of
Left e ->
readerError e
Right v ->
return v
configCmdSetParser :: Parser ConfigCmdSet
configCmdSetParser =
fromM
(do field <-
oneM
(strArgument
(metavar "FIELD VALUE"))
oneM (fieldToValParser field))
where
fieldToValParser :: String -> Parser ConfigCmdSet
fieldToValParser s =
case s of
"resolver" ->
ConfigCmdSetResolver <$>
argument
readAbstractResolver
idm
_ ->
error "parse stack config set field: only set resolver is implemented"
-- | If argument is True, hides the option from usage and help
hideMods :: Bool -> Mod f a
hideMods hide = if hide then internal <> hidden else idm
|
phadej/stack
|
src/Stack/Options.hs
|
Haskell
|
bsd-3-clause
| 37,388
|
-- Par monad and thread representation; types
--
-- Visibility: HpH.Internal.{IVar,Sparkpool,Threadpool,Scheduler}
-- Author: Patrick Maier <P.Maier@hw.ac.uk>
-- Created: 28 Sep 2011
--
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE TemplateHaskell #-} -- req'd for mkClosure, etc
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
module Control.Parallel.HdpH.Internal.Type.Par
( -- * Par monad, threads and sparks
ParM(..),
Thread(..),
CurrentLocation(..),
Task,SupervisedSpark(..),
SupervisedTaskState(..),Scheduling(..),
taskSupervised,declareStatic
) where
import Prelude
import Control.Parallel.HdpH.Internal.Location (NodeId)
import Control.Parallel.HdpH.Internal.Type.GRef (TaskRef)
import Data.Monoid (mconcat)
import Control.Parallel.HdpH.Closure
(Closure,ToClosure(..),StaticDecl,StaticToClosure,
declare,staticToClosure,here)
import Data.Binary (Binary,put,get)
declareStatic :: StaticDecl
declareStatic = mconcat
[declare (staticToClosure :: forall a . StaticToClosure (SupervisedSpark a))]
-----------------------------------------------------------------------------
-- Par monad, based on ideas from
-- [1] Claessen "A Poor Man's Concurrency Monad", JFP 9(3), 1999.
-- [2] Marlow et al. "A monad for deterministic parallelism". Haskell 2011.
-- 'ParM m' is a continuation monad, specialised to the return type 'Thread m';
-- 'm' abstracts a monad encapsulating the underlying state.
newtype ParM m a = Par { unPar :: (a -> Thread m) -> Thread m }
-- A thread is determined by its actions, as described in this data type.
-- In [2] this type is called 'Trace'.
newtype Thread m = Atom (m (Maybe (Thread m))) -- atomic action (in monad 'm')
-- result is next action, maybe
data SupervisedSpark m = SupervisedSpark
{
clo :: Closure (ParM m ())
, remoteRef :: TaskRef
, thisReplica :: Int
}
instance Binary (SupervisedSpark m) where
put (SupervisedSpark closure ref thisSeq) =
Data.Binary.put closure >>
Data.Binary.put ref >>
Data.Binary.put thisSeq
get = do
closure <- Data.Binary.get
ref <- Data.Binary.get
thisSeq <- Data.Binary.get
return $ SupervisedSpark closure ref thisSeq
type Task m = Either (Closure (SupervisedSpark m)) (Closure (ParM m ()))
taskSupervised :: Task m -> Bool
taskSupervised (Left _) = True
taskSupervised (Right _) = False
-- |Local representation of a spark for the supervisor
data SupervisedTaskState m = SupervisedTaskState
{
-- | The copy of the task that will need rescheduled,
-- in the case when it has not been evaluated.
task :: Closure (ParM m ())
-- | Used by the spark supervisor. Used to decide
-- whether to put the spark copy in the local
-- sparkpool or threadpool.
, scheduling :: Scheduling
-- | sequence number of most recent copy of the task.
, newestReplica :: Int
-- | book keeping for most recent task copy.
, location :: CurrentLocation
}
-- | Book keeping of a task. A task is either
-- known to be on a node, or in transition between
-- two nodes over the wire.
data CurrentLocation =
OnNode NodeId
| InTransition
{ movingFrom :: NodeId
, movingTo :: NodeId }
-- | The task was originally created as a spark
-- or as an eagerly scheduled thread
data Scheduling = Sparked | Pushed deriving (Eq)
instance ToClosure (SupervisedSpark m) where locToClosure = $(here)
|
robstewart57/hdph-rs
|
src/Control/Parallel/HdpH/Internal/Type/Par.hs
|
Haskell
|
bsd-3-clause
| 3,793
|
{-# LANGUAGE TypeOperators, TypeSynonymInstances #-}
{-# LANGUAGE GADTs, KindSignatures #-}
{-# OPTIONS_GHC -Wall #-}
-- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
-- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
----------------------------------------------------------------------
-- |
-- Module : Circat.LinearMap
-- Copyright : (c) 2014 Tabula, Inc.
--
-- Maintainer : conal@tabula.com
-- Stability : experimental
--
-- Linear maps as GADT
----------------------------------------------------------------------
module Circat.LinearMap where
-- TODO: explicit exports
import Circat.Misc ((:*))
import Data.AdditiveGroup (AdditiveGroup(..))
infixr 1 :-*
data (:-*) :: * -> * -> * where
Scale :: Num a => a -> (a :-* a)
(:&&&) :: (a :-* c) -> (a :-* d) -> (a :-* c :* d)
(:|||) :: AdditiveGroup c =>
(a :-* c) -> (b :-* c) -> (a :* b :-* c)
-- infixl 9 @$
-- Scale s @$ x = s * x
-- (f :&&& g) @$ a = (f @$ a, g @$ a)
-- (f :||| g) @$ (a,b) = f @$ a ^+^ f @$ b
-- mu = (@$) -- for prefix
mu :: (u :-* v) -> u -> v
mu (Scale s) x = s * x
mu (f :&&& g) a = (mu f a, mu g a)
mu (f :||| g) (a,b) = mu f a ^+^ mu g b
{- Note the homomorphisms:
> mu (f :&&& g) = mu f &&& mu g
> mu (f :||| g) = mu f ||| mu g
if the RHSs are interpreted in **Vect**.
To do: make a clear notational distinction between the representation and the model of linear maps.
-}
class HasZero z where zeroL :: a :-* z
instance (HasZero u, HasZero v) => HasZero (u :* v) where
zeroL = (zeroL,zeroL)
-- instance AdditiveGroup v => AdditiveGroup (u :-* v) where
-- zeroV =
-- infixr 9 @.
-- (@.) :: (b :-* c) -> (a :- b) -> (a :-* c)
-- Specification: mu (g @. f) == mu g . mu f
|
capn-freako/circat
|
src/Circat/LinearMap.hs
|
Haskell
|
bsd-3-clause
| 1,746
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Monad (unless)
import Data.Monoid
import Data.Version (showVersion)
import Options.Applicative
import System.Environment (getEnvironment)
import System.Exit (ExitCode (ExitSuccess), exitWith)
import System.FilePath (splitSearchPath)
import System.Process (rawSystem)
import AddHandler (addHandler)
import Devel (DevelOpts (..), devel, DevelTermOpt(..))
import Keter (keter)
import Options (injectDefaults)
import qualified Paths_yesod_bin
import Scaffolding.Scaffolder (scaffold, backendOptions)
import HsFile (mkHsFile)
#ifndef WINDOWS
import Build (touch)
touch' :: IO ()
touch' = touch
windowsWarning :: String
windowsWarning = ""
#else
touch' :: IO ()
touch' = return ()
windowsWarning :: String
windowsWarning = " (does not work on Windows)"
#endif
data CabalPgm = Cabal | CabalDev deriving (Show, Eq)
data Options = Options
{ optCabalPgm :: CabalPgm
, optVerbose :: Bool
, optCommand :: Command
}
deriving (Show, Eq)
data Command = Init { _initBare :: Bool, _initName :: Maybe String, _initDatabase :: Maybe String }
| HsFiles
| Configure
| Build { buildExtraArgs :: [String] }
| Touch
| Devel { _develDisableApi :: Bool
, _develSuccessHook :: Maybe String
, _develFailHook :: Maybe String
, _develRescan :: Int
, _develBuildDir :: Maybe String
, develIgnore :: [String]
, develExtraArgs :: [String]
, _develPort :: Int
, _develTlsPort :: Int
, _proxyTimeout :: Int
, _noReverseProxy :: Bool
, _interruptOnly :: Bool
}
| Test
| AddHandler
{ addHandlerRoute :: Maybe String
, addHandlerPattern :: Maybe String
, addHandlerMethods :: [String]
}
| Keter
{ _keterNoRebuild :: Bool
, _keterNoCopyTo :: Bool
}
| Version
deriving (Show, Eq)
cabalCommand :: Options -> String
cabalCommand mopt
| optCabalPgm mopt == CabalDev = "cabal-dev"
| otherwise = "cabal"
main :: IO ()
main = do
o <- execParser =<< injectDefaults "yesod"
[ ("yesod.devel.extracabalarg" , \o args -> o { optCommand =
case optCommand o of
d@Devel{} -> d { develExtraArgs = args }
c -> c
})
, ("yesod.devel.ignore" , \o args -> o { optCommand =
case optCommand o of
d@Devel{} -> d { develIgnore = args }
c -> c
})
, ("yesod.build.extracabalarg" , \o args -> o { optCommand =
case optCommand o of
b@Build{} -> b { buildExtraArgs = args }
c -> c
})
] optParser'
let cabal = rawSystem' (cabalCommand o)
case optCommand o of
Init{..} -> scaffold _initBare _initName _initDatabase
HsFiles -> mkHsFile
Configure -> cabal ["configure"]
Build es -> touch' >> cabal ("build":es)
Touch -> touch'
Keter{..} -> keter (cabalCommand o) _keterNoRebuild _keterNoCopyTo
Version -> putStrLn ("yesod-bin version: " ++ showVersion Paths_yesod_bin.version)
AddHandler{..} -> addHandler addHandlerRoute addHandlerPattern addHandlerMethods
Test -> cabalTest cabal
Devel{..} ->do
(configOpts, menv) <- handleGhcPackagePath
let develOpts = DevelOpts
{ isCabalDev = optCabalPgm o == CabalDev
, forceCabal = _develDisableApi
, verbose = optVerbose o
, eventTimeout = _develRescan
, successHook = _develSuccessHook
, failHook = _develFailHook
, buildDir = _develBuildDir
, develPort = _develPort
, develTlsPort = _develTlsPort
, proxyTimeout = _proxyTimeout
, useReverseProxy = not _noReverseProxy
, terminateWith = if _interruptOnly then TerminateOnlyInterrupt else TerminateOnEnter
, develConfigOpts = configOpts
, develEnv = menv
}
devel develOpts develExtraArgs
where
cabalTest cabal = do touch'
_ <- cabal ["configure", "--enable-tests", "-flibrary-only"]
_ <- cabal ["build"]
cabal ["test"]
handleGhcPackagePath :: IO ([String], Maybe [(String, String)])
handleGhcPackagePath = do
env <- getEnvironment
case lookup "GHC_PACKAGE_PATH" env of
Nothing -> return ([], Nothing)
Just gpp -> do
let opts = "--package-db=clear"
: "--package-db=global"
: map ("--package-db=" ++)
(drop 1 $ reverse $ splitSearchPath gpp)
return (opts, Just $ filter (\(x, _) -> x /= "GHC_PACKAGE_PATH") env)
optParser' :: ParserInfo Options
optParser' = info (helper <*> optParser) ( fullDesc <> header "Yesod Web Framework command line utility" )
optParser :: Parser Options
optParser = Options
<$> flag Cabal CabalDev ( long "dev" <> short 'd' <> help "use cabal-dev" )
<*> switch ( long "verbose" <> short 'v' <> help "More verbose output" )
<*> subparser ( command "init" (info initOptions
(progDesc "Scaffold a new site"))
<> command "hsfiles" (info (pure HsFiles)
(progDesc "Create a hsfiles file for the current folder"))
<> command "configure" (info (pure Configure)
(progDesc "Configure a project for building"))
<> command "build" (info (Build <$> extraCabalArgs)
(progDesc $ "Build project (performs TH dependency analysis)" ++ windowsWarning))
<> command "touch" (info (pure Touch)
(progDesc $ "Touch any files with altered TH dependencies but do not build" ++ windowsWarning))
<> command "devel" (info develOptions
(progDesc "Run project with the devel server"))
<> command "test" (info (pure Test)
(progDesc "Build and run the integration tests"))
<> command "add-handler" (info addHandlerOptions
(progDesc ("Add a new handler and module to the project."
++ " Interactively asks for input if you do not specify arguments.")))
<> command "keter" (info keterOptions
(progDesc "Build a keter bundle"))
<> command "version" (info (pure Version)
(progDesc "Print the version of Yesod"))
)
initOptions :: Parser Command
initOptions = Init
<$> switch (long "bare" <> help "Create files in current folder")
<*> optStr (long "name" <> short 'n' <> metavar "APP_NAME"
<> help "Set the application name")
<*> optStr (long "database" <> short 'd' <> metavar "DATABASE"
<> help ("Preconfigure for selected database (options: " ++ backendOptions ++ ")"))
keterOptions :: Parser Command
keterOptions = Keter
<$> switch ( long "nobuild" <> short 'n' <> help "Skip rebuilding" )
<*> switch ( long "nocopyto" <> help "Ignore copy-to directive in keter config file" )
defaultRescan :: Int
defaultRescan = 10
develOptions :: Parser Command
develOptions = Devel <$> switch ( long "disable-api" <> short 'd'
<> help "Disable fast GHC API rebuilding")
<*> optStr ( long "success-hook" <> short 's' <> metavar "COMMAND"
<> help "Run COMMAND after rebuild succeeds")
<*> optStr ( long "failure-hook" <> short 'f' <> metavar "COMMAND"
<> help "Run COMMAND when rebuild fails")
<*> option auto ( long "event-timeout" <> short 't' <> value defaultRescan <> metavar "N"
<> help ("Force rescan of files every N seconds (default "
++ show defaultRescan
++ ", use -1 to rely on FSNotify alone)") )
<*> optStr ( long "builddir" <> short 'b'
<> help "Set custom cabal build directory, default `dist'")
<*> many ( strOption ( long "ignore" <> short 'i' <> metavar "DIR"
<> help "ignore file changes in DIR" )
)
<*> extraCabalArgs
<*> option auto ( long "port" <> short 'p' <> value 3000 <> metavar "N"
<> help "Devel server listening port" )
<*> option auto ( long "tls-port" <> short 'q' <> value 3443 <> metavar "N"
<> help "Devel server listening port (tls)" )
<*> option auto ( long "proxy-timeout" <> short 'x' <> value 0 <> metavar "N"
<> help "Devel server timeout before returning 'not ready' message (in seconds, 0 for none)" )
<*> switch ( long "disable-reverse-proxy" <> short 'n'
<> help "Disable reverse proxy" )
<*> switch ( long "interrupt-only" <> short 'c'
<> help "Disable exiting when enter is pressed")
extraCabalArgs :: Parser [String]
extraCabalArgs = many (strOption ( long "extra-cabal-arg" <> short 'e' <> metavar "ARG"
<> help "pass extra argument ARG to cabal")
)
addHandlerOptions :: Parser Command
addHandlerOptions = AddHandler
<$> optStr ( long "route" <> short 'r' <> metavar "ROUTE"
<> help "Name of route (without trailing R). Required.")
<*> optStr ( long "pattern" <> short 'p' <> metavar "PATTERN"
<> help "Route pattern (ex: /entry/#EntryId). Defaults to \"\".")
<*> many (strOption ( long "method" <> short 'm' <> metavar "METHOD"
<> help "Takes one method. Use this multiple times to add multiple methods. Defaults to none.")
)
-- | Optional @String@ argument
optStr :: Mod OptionFields (Maybe String) -> Parser (Maybe String)
optStr m = option (Just <$> str) $ value Nothing <> m
-- | Like @rawSystem@, but exits if it receives a non-success result.
rawSystem' :: String -> [String] -> IO ()
rawSystem' x y = do
res <- rawSystem x y
unless (res == ExitSuccess) $ exitWith res
|
frontrowed/yesod
|
yesod-bin/main.hs
|
Haskell
|
mit
| 11,794
|
athing = and [a, b]
|
mpickering/hlint-refactor
|
tests/examples/AndList.hs
|
Haskell
|
bsd-3-clause
| 20
|
<?xml version='1.0' encoding='ISO-8859-1' ?>
<!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">
<!-- title -->
<title>Spring Rich Simple Sample Help</title>
<!-- maps -->
<maps>
<homeID>Overview</homeID>
<mapref location="simple.jhm" />
</maps>
<!-- views -->
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch</data>
</view>
<view>
<name>favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
lievendoclo/Valkyrie-RCP
|
valkyrie-rcp-samples/valkyrie-rcp-simple-sample/src/main/resources/help/simple.hs
|
Haskell
|
apache-2.0
| 756
|
{-# LANGUAGE MultiParamTypeClasses #-}
import Data.Coerce (Coercible)
instance Coercible () ()
main = return ()
|
ezyang/ghc
|
testsuite/tests/typecheck/should_fail/TcCoercibleFail2.hs
|
Haskell
|
bsd-3-clause
| 115
|
module Main (main) where
import Data.Bits
{-
Do some bitwise operations on some large numbers.
These number are designed so that they are likely to exercise all the
interesting split-up cases for implementations that implement Integer
as some sort of sequence of roughly word-sized values. They are
essentially random apart from that.
-}
px, py, nx, ny :: Integer
px = 0x03A4B5C281F6E9D7029C3FE81D6A4B75
nx = -0x03A4B5C281F6E9D7029C3FE81D6A4B75
py = 0x069AF53C4D1BE728
ny = -0x069AF53C4D1BE728
-- \.. 64 bits ../\.. 64 bits ../
{-
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
px and py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000001010011000001101010010100000001101000010100100001100100000
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
px and ny = 0 0000001110100100101101011100001010000001111101101110100111010111 0000000000000100000010101100000000010000011000000000100001010000
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
nx and py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000010000000010110000000001010001000000000100011010010000001000
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
nx and ny = 1 1111110001011011010010100011110101111110000010010001011000101000 1111100101100001000000000000001110100010100001000001000010001000
= neg 0 0000001110100100101101011100001010000001111101101110100111010111 0000011010011110111111111111110001011101011110111110111101111000
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
px or py = 0 0000001110100100101101011100001010000001111101101110100111010111 0000011010011110111111111111110001011101011110111110111101111101
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
px or ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111101111111101001111111110101110111111111011100101101111111101
= neg 0 0000000000000000000000000000000000000000000000000000000000000000 0000010000000010110000000001010001000000000100011010010000000011
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
nx or py = 1 1111110001011011010010100011110101111110000010010001011000101000 1111111111111011111101010011111111101111100111111111011110101011
= neg 0 0000001110100100101101011100001010000001111101101110100111010111 0000000000000100000010101100000000010000011000000000100001010101
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
nx or ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111110101100111110010101101011111110010111101011011110011011011
= neg 0 0000000000000000000000000000000000000000000000000000000000000000 0000001010011000001101010010100000001101000010100100001100100101
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
px xor py = 0 0000001110100100101101011100001010000001111101101110100111010111 0000010000000110110010101101010001010000011100011010110001011101
px = 0 0000001110100100101101011100001010000001111101101110100111010111 0000001010011100001111111110100000011101011010100100101101110101
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
px xor ny = 1 1111110001011011010010100011110101111110000010010001011000101000 1111101111111001001101010010101110101111100011100101001110101101
= neg 0 0000001110100100101101011100001010000001111101101110100111010111 0000010000000110110010101101010001010000011100011010110001010011
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
py = 0 0000000000000000000000000000000000000000000000000000000000000000 0000011010011010111101010011110001001101000110111110011100101000
nx xor py = 1 1111110001011011010010100011110101111110000010010001011000101000 1111101111111001001101010010101110101111100011100101001110100011
= neg 0 0000001110100100101101011100001010000001111101101110100111010111 0000010000000110110010101101010001010000011100011010110001011101
nx = 1 1111110001011011010010100011110101111110000010010001011000101000 1111110101100011110000000001011111100010100101011011010010001011
ny = 1 1111111111111111111111111111111111111111111111111111111111111111 1111100101100101000010101100001110110010111001000001100011011000
nx xor ny = 0 0000001110100100101101011100001010000001111101101110100111010111 0000010000000110110010101101010001010000011100011010110001010011
-}
px_and_py :: Integer
px_and_py = 0x29835280D0A4320
px_and_ny :: Integer
px_and_ny = 0x3A4B5C281F6E9D700040AC010600850
nx_and_py :: Integer
nx_and_py = 0x402C0144011A408
nx_and_ny :: Integer
nx_and_ny = -0x3A4B5C281F6E9D7069EFFFC5D7BEF78
px_or_py :: Integer
px_or_py = 0x3A4B5C281F6E9D7069EFFFC5D7BEF7D
px_or_ny :: Integer
px_or_ny = -0x402C0144011A403
nx_or_py :: Integer
nx_or_py = -0x3A4B5C281F6E9D700040AC010600855
nx_or_ny :: Integer
nx_or_ny = -0x29835280D0A4325
px_xor_py :: Integer
px_xor_py = 0x3A4B5C281F6E9D70406CAD45071AC5D
px_xor_ny :: Integer
px_xor_ny = -0x3A4B5C281F6E9D70406CAD45071AC53
nx_xor_py :: Integer
nx_xor_py = -0x3A4B5C281F6E9D70406CAD45071AC5D
nx_xor_ny :: Integer
nx_xor_ny = 0x3A4B5C281F6E9D70406CAD45071AC53
main :: IO ()
main = do putStrLn "Start"
test "px and py" px_and_py (px .&. py)
test "px and ny" px_and_ny (px .&. ny)
test "nx and py" nx_and_py (nx .&. py)
test "nx and ny" nx_and_ny (nx .&. ny)
test "px or py" px_or_py (px .|. py)
test "px or ny" px_or_ny (px .|. ny)
test "nx or py" nx_or_py (nx .|. py)
test "nx or ny" nx_or_ny (nx .|. ny)
test "px xor py" px_xor_py (px `xor` py)
test "px xor ny" px_xor_ny (px `xor` ny)
test "nx xor py" nx_xor_py (nx `xor` py)
test "nx xor ny" nx_xor_ny (nx `xor` ny)
putStrLn "End"
test :: String -> Integer -> Integer -> IO ()
test what want got
| want == got = return ()
| otherwise = print (what, want, got)
|
urbanslug/ghc
|
testsuite/tests/lib/integer/integerBits.hs
|
Haskell
|
bsd-3-clause
| 8,148
|
-- #hide, prune, ignore-exports
module A where
|
siddhanathan/ghc
|
testsuite/tests/haddock/should_compile_noflag_haddock/haddockC017.hs
|
Haskell
|
bsd-3-clause
| 47
|
{-# LANGUAGE CPP,
TupleSections, LambdaCase, RecordWildCards,
OverloadedLists, OverloadedStrings,
FlexibleContexts, RankNTypes, ScopedTypeVariables,
ViewPatterns, MultiWayIf #-}
#include "ghc-compat.h"
module HsToCoq.ConvertHaskell.Expr (
convertTypedModuleBinding,
convertMethodBinding,
convertTypedModuleBindings,
hsBindName,
) where
import Prelude hiding (Num())
import Control.Lens
import Control.Arrow ((&&&))
import Data.Bifunctor
import Data.Foldable
import HsToCoq.Util.Foldable
import Data.Functor (($>))
import Data.Traversable
import Data.Bitraversable
import HsToCoq.Util.Function
import Data.Maybe
import Data.Either
import Data.List (sortOn)
import HsToCoq.Util.List hiding (unsnoc)
import Data.List.NonEmpty (nonEmpty, NonEmpty(..))
import qualified Data.List.NonEmpty as NEL
import qualified HsToCoq.Util.List as NEL ((|>))
import Data.Text (Text)
import qualified Data.Text as T
import Control.Monad.Trans.Maybe
import Control.Monad.Except
import Control.Monad.Writer
import HsToCoq.Util.Containers
import Data.Set (Set)
import Data.Map.Strict (Map)
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import GHC hiding (Name, HsChar, HsString, AsPat)
import qualified GHC
import Bag
import BasicTypes
import HsToCoq.Util.GHC.FastString
import RdrName
import HsToCoq.Util.GHC.Exception
import qualified Outputable as GHC
import HsToCoq.Util.GHC
import HsToCoq.Util.GHC.Name hiding (Name)
import HsToCoq.Util.GHC.HsExpr
import HsToCoq.Util.GHC.HsTypes (selectorFieldOcc_, fieldOcc)
#if __GLASGOW_HASKELL__ >= 806
import HsToCoq.Util.GHC.HsTypes (noExtCon)
#endif
import HsToCoq.Coq.Gallina as Coq
import HsToCoq.Coq.Gallina.Util
import HsToCoq.Coq.Gallina.UseTypeInBinders
import HsToCoq.Coq.Subst
import HsToCoq.Coq.Gallina.Rewrite as Coq
import HsToCoq.Coq.FreeVars
import HsToCoq.Util.FVs (ErrOrVars(..))
import HsToCoq.Coq.Pretty
import HsToCoq.ConvertHaskell.Parameters.Edits
import HsToCoq.ConvertHaskell.TypeInfo
import HsToCoq.ConvertHaskell.Monad
import HsToCoq.ConvertHaskell.Variables
import HsToCoq.ConvertHaskell.Definitions
import HsToCoq.ConvertHaskell.Literals
import HsToCoq.ConvertHaskell.Type
import HsToCoq.ConvertHaskell.Pattern
import HsToCoq.ConvertHaskell.Sigs
import HsToCoq.ConvertHaskell.Axiomatize
--------------------------------------------------------------------------------
rewriteExpr :: ConversionMonad r m => Term -> m Term
rewriteExpr tm = do
rws <- view (edits.rewrites)
return $ Coq.rewrite rws tm
-- Module-local
il_integer :: IntegralLit -> Integer
il_integer IL{..} = (if il_neg then negate else id) il_value
-- Module-local
convert_int_literal :: LocalConvMonad r m => String -> Integer -> m Term
convert_int_literal what = either convUnsupported (pure . Num)
. convertInteger (what ++ " literals")
convertExpr :: LocalConvMonad r m => HsExpr GhcRn -> m Term
convertExpr hsExpr = convertExpr_ hsExpr >>= rewriteExpr
convertExpr_ :: forall r m. LocalConvMonad r m => HsExpr GhcRn -> m Term
convertExpr_ (HsVar NOEXTP (L _ x)) =
Qualid <$> var ExprNS x
convertExpr_ (HsUnboundVar NOEXTP x) =
Var <$> freeVar (unboundVarOcc x)
convertExpr_ (HsRecFld NOEXTP fld) =
Qualid <$> recordField fld
convertExpr_ HsOverLabel{} =
convUnsupported "overloaded labels"
convertExpr_ (HsIPVar NOEXTP _) =
convUnsupported "implicit parameters"
convertExpr_ (HsOverLit NOEXTP OverLit{..}) =
case ol_val of
HsIntegral intl -> App1 "GHC.Num.fromInteger" <$> convert_int_literal "integer" (il_integer intl)
HsFractional fr -> convertFractional fr
HsIsString _src str -> pure $ convertFastString str
convertExpr_ (HsLit NOEXTP lit) =
case lit of
GHC.HsChar _ c -> pure $ HsChar c
HsCharPrim _ _ -> convUnsupported "`Char#' literals"
GHC.HsString _ fs -> pure $ convertFastString fs
HsStringPrim _ _ -> convUnsupported "`Addr#' literals"
HsInt _ intl -> convert_int_literal "`Int'" (il_integer intl)
HsIntPrim _ int -> convert_int_literal "`IntPrim'" int
HsWordPrim _ _ -> convUnsupported "`Word#' literals"
HsInt64Prim _ _ -> convUnsupported "`Int64#' literals"
HsWord64Prim _ _ -> convUnsupported "`Word64#' literals"
HsInteger _ int _ty -> convert_int_literal "`Integer'" int
HsRat _ _ _ -> convUnsupported "`Rational' literals"
HsFloatPrim _ _ -> convUnsupported "`Float#' literals"
HsDoublePrim _ _ -> convUnsupported "`Double#' literals"
#if __GLASGOW_HASKELL__ >= 806
XLit v -> noExtCon v
#endif
convertExpr_ (HsLam NOEXTP mg) =
uncurry Fun <$> convertFunction [] mg -- We don't skip any equations in an ordinary lambda
convertExpr_ (HsLamCase NOEXTP mg) = do
skipPats <- views (edits.skippedCasePatterns) (S.map pure)
uncurry Fun <$> convertFunction skipPats mg
convertExpr_ (HsApp NOEXTP e1 e2) =
App1 <$> convertLExpr e1 <*> convertLExpr e2
#if __GLASGOW_HASKELL__ >= 808
convertExpr_ (HsAppType NOEXTP e1 _) =
#elif __GLASGOW_HASKELL__ == 806
convertExpr_ (HsAppType _ e1) =
#else
convertExpr_ (HsAppType e1 _) =
#endif
convertLExpr e1
-- convUnsupported "type applications"
-- SCW: just ignore them for now, and let the user figure it out.
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (OpApp _fixity el eop er) =
#else
convertExpr_ (OpApp el eop _fixity er) =
#endif
case eop of
L _ (HsVar NOEXTP (L _ hsOp)) -> do
op <- var ExprNS hsOp
op' <- rewriteExpr $ Qualid op
l <- convertLExpr el
r <- convertLExpr er
pure $ App2 op' l r
_ ->
convUnsupported "non-variable infix operators"
convertExpr_ (NegApp NOEXTP e1 _) =
App1 <$> (pure "GHC.Num.negate" >>= rewriteExpr) <*> convertLExpr e1
convertExpr_ (HsPar NOEXTP e) =
Parens <$> convertLExpr e
convertExpr_ (SectionL NOEXTP l opE) =
convert_section (Just l) opE Nothing
convertExpr_ (SectionR NOEXTP opE r) =
convert_section Nothing opE (Just r)
-- TODO: Mark converted unboxed tuples specially?
convertExpr_ (ExplicitTuple NOEXTP exprs _boxity) = do
-- TODO A tuple constructor in the Gallina grammar?
(tuple, args) <- runWriterT
. fmap (foldl1 . App2 $ "pair")
. for exprs $ unLoc <&> \case
Present NOEXTP e -> lift $ convertLExpr e
Missing PlaceHolder ->
do arg <- lift (genqid "arg")
Qualid arg <$ tell [arg]
#if __GLASGOW_HASKELL__ >= 806
XTupArg v -> noExtCon v
#endif
pure $ maybe id Fun (nonEmpty $ map (mkBinder Coq.Explicit . Ident) args) tuple
convertExpr_ (HsCase NOEXTP e mg) = do
scrut <- convertLExpr e
skipPats <- views (edits.skippedCasePatterns) (S.map pure)
bindIn "scrut" scrut $ \scrut -> convertMatchGroup skipPats [scrut] mg
convertExpr_ (HsIf NOEXTP overloaded c t f) =
if maybe True isNoSyntaxExpr overloaded
then ifThenElse <*> pure SymmetricIf <*> convertLExpr c <*> convertLExpr t <*> convertLExpr f
else convUnsupported "overloaded if-then-else"
convertExpr_ (HsMultiIf PlaceHolder lgrhsList) =
convertLGRHSList [] lgrhsList patternFailure
convertExpr_ (HsLet NOEXTP (L _ binds) body) =
convertLocalBinds binds $ convertLExpr body
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (HsDo _ sty (L _ stmts)) =
#else
convertExpr_ (HsDo sty (L _ stmts) PlaceHolder) =
#endif
case sty of
ListComp -> convertListComprehension stmts
DoExpr -> convertDoBlock stmts
MonadComp -> convUnsupported "monad comprehensions"
MDoExpr -> convUnsupported "`mdo' expressions"
ArrowExpr -> convUnsupported "arrow expressions"
GhciStmtCtxt -> convUnsupported "GHCi statement expressions"
PatGuard _ -> convUnsupported "pattern guard expressions"
ParStmtCtxt _ -> convUnsupported "parallel statement expressions"
TransStmtCtxt _ -> convUnsupported "transform statement expressions"
#if __GLASGOW_HASKELL__ < 806
PArrComp -> convUnsupported "parallel array comprehensions"
#endif
convertExpr_ (ExplicitList PlaceHolder overloaded exprs) =
if maybe True isNoSyntaxExpr overloaded
then foldr (App2 "cons") "nil" <$> traverse convertLExpr exprs
else convUnsupported "overloaded lists"
-- TODO: Unify with the `RecCon` case in `ConPatIn` for `convertPat` (in
-- `HsToCoq.ConvertHaskell.Pattern`)
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (RecordCon _ (L _ hsCon) HsRecFields{..}) = do
#else
convertExpr_ (RecordCon (L _ hsCon) PlaceHolder conExpr HsRecFields{..}) = do
unless (isNoPostTcExpr conExpr) $
convUnsupported "unexpected post-typechecker record constructor"
#endif
let recConUnsupported what = do
hsConStr <- ghcPpr hsCon
convUnsupported $ "creating a record with the " ++ what
++ " constructor `" ++ T.unpack hsConStr ++ "'"
con <- var ExprNS hsCon
lookupConstructorFields con >>= \case
Just (RecordFields conFields) -> do
let defaultVal field | isJust rec_dotdot = Qualid field
| otherwise = missingValue
vals <- fmap M.fromList . for rec_flds $
\(L _ (HsRecField (L _ occ) hsVal pun)) -> do
field <- var ExprNS (selectorFieldOcc_ occ)
val <- if pun
then pure $ Qualid field
else convertLExpr hsVal
pure (field, val)
pure . appList (Qualid con)
$ map (\field -> PosArg $ M.findWithDefault (defaultVal field) field vals) conFields
Just (NonRecordFields count)
| null rec_flds && isNothing rec_dotdot ->
pure . appList (Qualid con) $ replicate count (PosArg missingValue)
| otherwise ->
recConUnsupported "non-record"
Nothing -> recConUnsupported "unknown"
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (RecordUpd _ recVal fields) = do
#else
convertExpr_ (RecordUpd recVal fields PlaceHolder PlaceHolder PlaceHolder PlaceHolder) = do
#endif
updates <- fmap M.fromList . for fields $ \(L _ HsRecField{..}) -> do
field <- recordField $ unLoc hsRecFieldLbl
pure (field, if hsRecPun then Nothing else Just hsRecFieldArg)
let updFields = M.keys updates
prettyUpdFields what =
let quote f = "`" ++ T.unpack (qualidToIdent f) ++ "'"
in explainStrItems quote "no" "," "and" what (what ++ "s") updFields
recType <- S.minView . S.fromList <$> traverse (\field -> lookupRecordFieldType field) updFields >>= \case
Just (Just recType, []) -> pure recType
Just (Nothing, []) -> convUnsupported $ "invalid record update with " ++ prettyUpdFields "non-record-field"
_ -> convUnsupported $ "invalid mixed-data-type record updates with " ++ prettyUpdFields "the given field"
ctors :: [Qualid] <- maybe (convUnsupported "invalid unknown record type") pure =<< lookupConstructors recType
let loc :: e -> Located e
loc = mkGeneralLocated "generated"
toLPat_ :: Pat GhcRn -> LPat GhcRn
toLPat_ = toLPat "generated"
toHs = freshInternalName . T.unpack
let partialUpdateError :: Qualid -> m (Match GhcRn (Located (HsExpr GhcRn)))
partialUpdateError con = do
hsCon <- toHs (qualidToIdent con)
hsError <- toHs "GHC.Err.error"
pure $ GHC.Match
{ m_ctxt = LambdaExpr
, m_pats = [ toLPat_ . ConPatIn (loc hsCon)
. RecCon $ HsRecFields { rec_flds = []
, rec_dotdot = Nothing } ]
, m_grhss = GRHSs { grhssGRHSs = [ loc . GRHS NOEXT [] . loc $
HsApp NOEXT
(loc . HsVar NOEXT . loc $ hsError)
(loc . HsLit NOEXT . GHC.HsString (SourceText "") $ fsLit "Partial record update") ]
, grhssLocalBinds = loc (EmptyLocalBinds NOEXT)
#if __GLASGOW_HASKELL__ >= 806
, grhssExt = NOEXT
#endif
}
#if __GLASGOW_HASKELL__ >= 806
, m_ext = NOEXT
#endif
}
matches <- for ctors $ \con ->
lookupConstructorFields con >>= \case
Just (RecordFields fields) | all (`elem` fields) $ M.keysSet updates -> do
let addFieldOcc :: HsRecField' GHC.Name arg -> HsRecField GhcRn arg
addFieldOcc field@HsRecField{hsRecFieldLbl = L s lbl} =
let rdrLbl = mkOrig <$> nameModule <*> nameOccName $ lbl
l = L s (fieldOcc (L s rdrLbl) lbl)
in field{ hsRecFieldLbl = l }
useFields fields = HsRecFields { rec_flds = map (fmap addFieldOcc) fields
, rec_dotdot = Nothing }
(fieldPats, fieldVals) <- fmap (bimap useFields useFields . unzip) . for fields $ \field -> do
fieldVar <- gensym (qualidBase field)
hsField <- toHs (qualidToIdent field)
hsFieldVar <- toHs fieldVar
let mkField arg = loc $ HsRecField { hsRecFieldLbl = loc hsField
, hsRecFieldArg = arg
, hsRecPun = False }
pure ( mkField . toLPat_ . GHC.VarPat NOEXT . loc $ hsFieldVar
, mkField . fromMaybe (loc . HsVar NOEXT $ loc hsField) -- NOT `fieldVar` – this was punned
$ M.findWithDefault (Just . loc . HsVar NOEXT $ loc hsFieldVar) field updates )
hsCon <- toHs (qualidToIdent con)
#if __GLASGOW_HASKELL__ >= 806
let r = RecordCon NOEXT (loc hsCon) fieldVals
#else
let r = RecordCon (loc hsCon) PlaceHolder noPostTcExpr fieldVals
#endif
pure GHC.Match { m_ctxt = LambdaExpr
, m_pats = [ toLPat_ . ConPatIn (loc hsCon) $ RecCon fieldPats ]
, m_grhss = GRHSs { grhssGRHSs = [ loc . GRHS NOEXT [] . loc $ r ]
, grhssLocalBinds = loc (EmptyLocalBinds NOEXT)
#if __GLASGOW_HASKELL__ >= 806
, grhssExt = NOEXT
#endif
}
#if __GLASGOW_HASKELL__ >= 806
, m_ext = NOEXT
#endif
}
Just _ ->
partialUpdateError con
Nothing ->
convUnsupported "invalid unknown constructor in record update"
#if __GLASGOW_HASKELL__ >= 806
convertExpr . HsCase NOEXT recVal $
MG { mg_alts = loc $ map loc matches
, mg_ext = NOEXT
, mg_origin = Generated }
#else
convertExpr . HsCase recVal $
MG { mg_alts = loc $ map loc matches
, mg_arg_tys = []
, mg_res_ty = PlaceHolder
, mg_origin = Generated }
#endif
#if __GLASGOW_HASKELL__ >= 808
convertExpr_ (ExprWithTySig NOEXTP e sigWcTy) =
#elif __GLASGOW_HASKELL__ == 806
convertExpr_ (ExprWithTySig sigWcTy e) =
#else
convertExpr_ (ExprWithTySig e sigWcTy) =
#endif
HasType <$> convertLExpr e <*> convertLHsSigWcType PreserveUnusedTyVars sigWcTy
convertExpr_ (ArithSeq _postTc _overloadedLists info) =
-- TODO: Special-case infinite lists?
-- TODO: `enumFrom{,Then}{,To}` is really…?
-- TODO: Add Coq syntax sugar? Something like
--
-- Notation "[ :: from '..' ]" := (enumFrom from).
-- Notation "[ :: from , next '..' ]" := (enumFromThen from next).
-- Notation "[ :: from '..' to ]" := (enumFromTo from to).
-- Notation "[ :: from , next '..' to ]" := (enumFromThenTo from next to).
--
-- Only `'..'` doesn't work for some reason.
case info of
From low -> App1 "GHC.Enum.enumFrom" <$> convertLExpr low
FromThen low next -> App2 "GHC.Enum.enumFromThen" <$> convertLExpr low <*> convertLExpr next
FromTo low high -> App2 "GHC.Enum.enumFromTo" <$> convertLExpr low <*> convertLExpr high
FromThenTo low next high -> App3 "GHC.Enum.enumFromThenTo" <$> convertLExpr low <*> convertLExpr next <*> convertLExpr high
convertExpr_ (HsSCC NOEXTP _ _ e) =
convertLExpr e
convertExpr_ (HsCoreAnn NOEXTP _ _ e) =
convertLExpr e
convertExpr_ (HsBracket{}) =
convUnsupported "Template Haskell brackets"
convertExpr_ (HsRnBracketOut{}) =
convUnsupported "`HsRnBracketOut' constructor"
convertExpr_ (HsTcBracketOut{}) =
convUnsupported "`HsTcBracketOut' constructor"
convertExpr_ (HsSpliceE{}) =
convUnsupported "Quasiquoters and Template Haskell splices"
convertExpr_ (HsProc{}) =
convUnsupported "`proc' expressions"
convertExpr_ HsStatic{} =
convUnsupported "static pointers"
convertExpr_ (HsTick NOEXTP _ e) =
convertLExpr e
convertExpr_ (HsBinTick NOEXTP _ _ e) =
convertLExpr e
convertExpr_ (HsTickPragma NOEXTP _ _ _ e) =
convertLExpr e
convertExpr_ (HsWrap{}) =
convUnsupported "`HsWrap' constructor"
convertExpr_ (HsConLikeOut{}) =
convUnsupported "`HsConLikeOut' constructor"
convertExpr_ (ExplicitSum{}) =
convUnsupported "`ExplicitSum' constructor"
#if __GLASGOW_HASKELL__ >= 806
convertExpr_ (HsOverLit _ (XOverLit v)) = noExtCon v
convertExpr_ (XExpr v) = noExtCon v
#else
convertExpr_ (HsAppTypeOut _ _) =
convUnsupported "`HsAppTypeOut' constructor"
convertExpr_ (ExprWithTySigOut e sigWcTy) =
HasType <$> convertLExpr e <*> convertLHsSigWcType PreserveUnusedTyVars sigWcTy
convertExpr_ (ExplicitPArr _ _) =
convUnsupported "explicit parallel arrays"
convertExpr_ (PArrSeq _ _) =
convUnsupported "parallel array arithmetic sequences"
#endif
#if __GLASGOW_HASKELL__ < 810
convertExpr_ HsArrApp{} =
convUnsupported "arrow application command"
convertExpr_ HsArrForm{} =
convUnsupported "arrow command formation"
convertExpr_ EWildPat{} =
convUnsupported "wildcard pattern in expression"
convertExpr_ EAsPat{} =
convUnsupported "as-pattern in expression"
convertExpr_ EViewPat{} =
convUnsupported "view-pattern in expression"
convertExpr_ ELazyPat{} =
convUnsupported "lazy pattern in expression"
#endif
--------------------------------------------------------------------------------
-- Module-local
convert_section :: LocalConvMonad r m => Maybe (LHsExpr GhcRn) -> LHsExpr GhcRn -> Maybe (LHsExpr GhcRn) -> m Term
convert_section ml opE mr = do
let -- We need this type signature, and I think it's because @let@ isn't being
-- generalized.
hs :: ConversionMonad r m => Qualid -> m (HsExpr GhcRn)
hs = fmap (HsVar NOEXT . mkGeneralLocated "generated") . freshInternalName . T.unpack . qualidToIdent
coq = mkBinder Coq.Explicit . Ident
arg <- Bare <$> gensym "arg"
let orArg = maybe (fmap noLoc $ hs arg) pure
l <- orArg ml
r <- orArg mr
#if __GLASGOW_HASKELL__ >= 806
Fun [coq arg] <$> convertExpr (OpApp defaultFixity l opE r)
#else
-- TODO RENAMER look up fixity?
Fun [coq arg] <$> convertExpr (OpApp l opE defaultFixity r)
#endif
--------------------------------------------------------------------------------
convertLExpr :: LocalConvMonad r m => LHsExpr GhcRn -> m Term
convertLExpr = convertExpr . unLoc
--------------------------------------------------------------------------------
convertFunction :: LocalConvMonad r m
=> Set (NonEmpty NormalizedPattern)
-> MatchGroup GhcRn (LHsExpr GhcRn)
-> m (Binders, Term)
convertFunction _ mg | Just alt <- isTrivialMatch mg = convTrivialMatch alt
convertFunction skipEqns mg = do
let n_args = matchGroupArity mg
args <- replicateM n_args (genqid "arg") >>= maybe err pure . nonEmpty
let argBinders = (mkBinder Coq.Explicit . Ident) <$> args
match <- convertMatchGroup skipEqns (Qualid <$> args) mg
pure (argBinders, match)
where
err = convUnsupported "convertFunction: Empty argument list"
isTrivialMatch :: MatchGroup GhcRn (LHsExpr GhcRn) -> Maybe (Match GhcRn (LHsExpr GhcRn))
isTrivialMatch (MG { mg_alts = L _ [L _ alt] }) = trivMatch alt where
trivMatch :: Match GhcRn (LHsExpr GhcRn) -> Maybe (Match GhcRn (LHsExpr GhcRn))
trivMatch alt = if all trivLPat (m_pats alt) then Just alt else Nothing
trivPat :: Pat GhcRn -> Bool
trivPat (GHC.WildPat _) = False
trivPat (GHC.VarPat NOEXTP _) = True
trivPat (GHC.BangPat NOEXTP p) = trivLPat p
trivPat (GHC.LazyPat NOEXTP p) = trivLPat p
trivPat (GHC.ParPat NOEXTP p) = trivLPat p
trivPat _ = False
trivLPat = trivPat . unLPat
isTrivialMatch _ = Nothing
-- TODO: Unify with `isTrivialMatch` to return a `Maybe (Binders, Term)`
convTrivialMatch :: LocalConvMonad r m =>
Match GhcRn (LHsExpr GhcRn) -> m (Binders, Term)
convTrivialMatch alt = do
(MultPattern pats, _, rhs) <- convertMatch alt
<&> maybe (error "internal error: convTrivialMatch: not a trivial match!") id
names <- mapM patToName pats
let argBinders = (mkBinder Explicit) <$> names
body <- rhs patternFailure
return (argBinders, body)
patToName :: LocalConvMonad r m => Pattern -> m Name
patToName UnderscorePat = pure UnderscoreName
patToName (QualidPat qid) = pure $ Ident qid
patToName _ = convUnsupported "patToArg: not a trivial pat"
--------------------------------------------------------------------------------
isTrueLExpr :: GhcMonad m => LHsExpr GhcRn -> m Bool
isTrueLExpr (L _ (HsVar NOEXTP x)) = ((||) <$> (== "otherwise") <*> (== "True")) <$> ghcPpr x
isTrueLExpr (L _ (HsTick NOEXTP _ e)) = isTrueLExpr e
isTrueLExpr (L _ (HsBinTick NOEXTP _ _ e)) = isTrueLExpr e
isTrueLExpr (L _ (HsPar NOEXTP e)) = isTrueLExpr e
isTrueLExpr _ = pure False
--------------------------------------------------------------------------------
-- TODO: Unify `buildTrivial` and `buildNontrivial`?
convertPatternBinding :: LocalConvMonad r m
=> LPat GhcRn -> LHsExpr GhcRn
-> (Term -> (Term -> Term) -> m a)
-> (Term -> Qualid -> (Term -> Term -> Term) -> m a)
-> (Qualid -> m a)
-> Term
-> m a
convertPatternBinding hsPat hsExp buildTrivial buildNontrivial buildSkipped fallback =
runPatternT (convertLPat hsPat) >>= \case
Left skipped -> buildSkipped skipped
Right (pat, guards) -> do
exp <- convertLExpr hsExp
ib <- ifThenElse
refutability pat >>= \case
Trivial tpat | null guards ->
buildTrivial exp $ Fun [mkBinder Coq.Explicit $ maybe UnderscoreName Ident tpat]
nontrivial -> do
cont <- genqid "cont"
arg <- genqid "arg"
-- TODO: Use SSReflect's `let:` in the `SoleConstructor` case?
-- (Involves adding a constructor to `Term`.)
let fallbackMatches
| SoleConstructor <- nontrivial = []
| otherwise = [ Equation [MultPattern [UnderscorePat]] fallback ]
guarded tm | null guards = tm
| otherwise = ib LinearIf (foldr1 (App2 "andb") guards) tm fallback
buildNontrivial exp cont $ \body rest ->
Let cont [mkBinder Coq.Explicit $ Ident arg] Nothing
(Coq.Match [MatchItem (Qualid arg) Nothing Nothing] Nothing $
Equation [MultPattern [pat]] (guarded rest) : fallbackMatches)
body
convertDoBlock :: LocalConvMonad r m => [ExprLStmt GhcRn] -> m Term
convertDoBlock allStmts = do
case fmap unLoc <$> unsnoc allStmts of
Just (stmts, lastStmt -> Just e) -> foldMap (Endo . toExpr . unLoc) stmts `appEndo` convertLExpr e
Just _ -> convUnsupported "invalid malformed `do' block"
Nothing -> convUnsupported "invalid empty `do' block"
where
#if __GLASGOW_HASKELL__ >= 806
lastStmt (BodyStmt _ e _ _) = Just e
#else
lastStmt (BodyStmt e _ _ _) = Just e
#endif
lastStmt (LastStmt NOEXTP e _ _) = Just e
lastStmt _ = Nothing
toExpr x rest = toExpr_ x rest >>= rewriteExpr
#if __GLASGOW_HASKELL__ >= 806
toExpr_ (BodyStmt _ e _bind _guard) rest =
#else
toExpr_ (BodyStmt e _bind _guard _PlaceHolder) rest =
#endif
monThen <$> convertLExpr e <*> rest
#if __GLASGOW_HASKELL__ >= 806
toExpr_ (BindStmt _ pat exp _bind _fail) rest =
#else
toExpr_ (BindStmt pat exp _bind _fail PlaceHolder) rest =
#endif
convertPatternBinding
pat exp
(\exp' fun -> monBind exp' . fun <$> rest)
(\exp' cont letCont -> letCont (monBind exp' (Qualid cont)) <$> rest)
(\skipped -> convUnsupported $
"binding against the skipped constructor `" ++ showP skipped ++ "' in `do' notation")
(missingValue `App1` HsString "Partial pattern match in `do' notation")
toExpr_ (LetStmt NOEXTP (L _ binds)) rest =
convertLocalBinds binds rest
toExpr_ (RecStmt{}) _ =
convUnsupported "`rec' statements in `do` blocks"
toExpr_ _ _ =
convUnsupported "impossibly fancy `do' block statements"
monBind e1 e2 = mkInfix e1 "GHC.Base.>>=" e2
monThen e1 e2 = mkInfix e1 "GHC.Base.>>" e2
convertListComprehension :: LocalConvMonad r m => [ExprLStmt GhcRn] -> m Term
convertListComprehension allStmts = case fmap unLoc <$> unsnoc allStmts of
Just (stmts, LastStmt NOEXTP e _applicativeDoInfo _returnInfo) ->
foldMap (Endo . toExpr . unLoc) stmts `appEndo`
(App2 (Var "cons") <$> convertLExpr e <*> pure (Var "nil"))
Just _ ->
convUnsupported "invalid malformed list comprehensions"
Nothing ->
convUnsupported "invalid empty list comprehension"
where
#if __GLASGOW_HASKELL__ >= 806
toExpr (BodyStmt _ e _bind _guard) rest =
#else
toExpr (BodyStmt e _bind _guard _PlaceHolder) rest =
#endif
isTrueLExpr e >>= \case
True -> rest
False -> ifThenElse <*> pure LinearIf
<*> convertLExpr e
<*> rest
<*> pure (Var "nil")
-- TODO: `concatMap` is really…?
#if __GLASGOW_HASKELL__ >= 806
toExpr (BindStmt _ pat exp _bind _fail) rest =
#else
toExpr (BindStmt pat exp _bind _fail PlaceHolder) rest =
#endif
convertPatternBinding
pat exp
(\exp' fun -> App2 concatMapT <$> (fun <$> rest) <*> pure exp')
(\exp' cont letCont -> letCont (App2 concatMapT (Qualid cont) exp') <$> rest)
(\skipped -> pure $ App1 (Qualid "GHC.Skip.nil_skipped") (String $ textP skipped))
(Var "nil")
-- `GHC.Skip.nil_skipped` always returns `[]`, but it has a note about
-- what constructor was skipped.
toExpr (LetStmt NOEXTP (L _ binds)) rest =
convertLocalBinds binds rest
toExpr _ _ =
convUnsupported "impossibly fancy list comprehension conditions"
concatMapT :: Term
concatMapT = "Coq.Lists.List.flat_map"
--------------------------------------------------------------------------------
-- Could this pattern be considered a 'catch all' or exhaustive pattern?
isWildCoq :: Pattern -> Bool
isWildCoq UnderscorePat = True
isWildCoq (QualidPat _) = True
isWildCoq (AsPat p _) = isWildCoq p
isWildCoq (ArgsPat qid nep) = qid == (Bare "pair") && all isWildCoq nep
isWildCoq _ = False
{-
= ArgsPat Qualid (NE.NonEmpty Pattern)
| ExplicitArgsPat Qualid (NE.NonEmpty Pattern)
| InfixPat Pattern Op Pattern
| AsPat Pattern Ident
| InScopePat Pattern Ident
| QualidPat Qualid
| UnderscorePat
| NumPat HsToCoq.Coq.Gallina.Num
| StringPat T.Text
| OrPats (NE.NonEmpty OrPattern)
-}
-- This function, used by both convertMatchGroup for the various matches,
-- as well as in convertMatch for the various guarded RHS, implements
-- fall-though semantics, by binding each item to a jump point and passing
-- the right failure jump target to the prevoius item.
chainFallThroughs :: LocalConvMonad r m =>
[Term -> m Term] -> -- The matches, in syntax order
Term -> -- The final failure value
m Term
chainFallThroughs cases failure = go (reverse cases) failure where
go (m:ls) next_case = do
this_match <- m next_case
bindIn "j" this_match $ \failure -> go ls failure
go [] failure = pure failure
-- A match group contains multiple alternatives, and each can have guards, and
-- there is fall-through semantics. But often we know that if one pattern fall-through,
-- then the next pattern will not match. In that case, we want to bind them in the same
-- match-with clause, in the hope of obtaining a full pattern match
--
-- The plan is:
-- * Convert each alternative individually into a pair of a pattern and a RHS.
-- The RHS is a (shallow) function that takes the fall-through target.
-- This is done by convertMatch
-- * Group patterns that are mutually exclusive, and put them in match-with clauses.
-- Add a catch-all case if that group is not complete already.
-- * Chain these groups.
convertMatchGroup :: LocalConvMonad r m
=> Set (NonEmpty NormalizedPattern)
-> NonEmpty Term
-> MatchGroup GhcRn (LHsExpr GhcRn)
-> m Term
convertMatchGroup skipEqns args (MG { mg_alts = L _ alts }) = do
allConvAlts <- traverse (convertMatch . unLoc) alts
let convAlts = [alt | Just alt@(MultPattern pats, _, _) <- allConvAlts
, (normalizePattern <$> pats) `notElem` skipEqns ]
-- TODO: Group
convGroups <- groupMatches convAlts
let scrut = args <&> \arg -> MatchItem arg Nothing Nothing
let matches = buildMatch scrut <$> convGroups
chainFallThroughs matches patternFailure
#if __GLASGOW_HASKELL__ >= 806
convertMatchGroup _ _ (XMatchGroup v) = noExtCon v
#endif
data HasGuard = HasGuard | HasNoGuard deriving (Eq, Ord, Enum, Bounded, Show, Read)
groupMatches :: forall r m a. ConversionMonad r m =>
[(MultPattern, HasGuard, a)] -> m [[(MultPattern, a)]]
groupMatches pats = map (map snd) . go <$> mapM summarize pats
where
-- Gather some summary information on the alternatives
-- - do they have guards
-- - what is their PatternSummary
summarize :: (MultPattern, HasGuard, a) -> m ([PatternSummary], HasGuard, (MultPattern, a))
summarize (mp,hg,x) = do
s <- multPatternSummary mp
return (s,hg,(mp,x))
go :: forall x. [([PatternSummary], HasGuard, x)] -> [[([PatternSummary], x)]]
go [] = pure []
go ((ps,hg,x):xs) = case go xs of
-- Append to a group if it has no guard
(g:gs) | HasNoGuard <- hg -> ((ps,x):g) : gs
-- Append to a group, if mutually exclusive with all members
| all (mutExcls ps . fst) g -> ((ps,x):g) : gs
-- Otherwise, start a new group
gs -> ((ps,x):[]) : gs
convertMatch :: LocalConvMonad r m =>
Match GhcRn (LHsExpr GhcRn) -> -- the match
m (Maybe (MultPattern, HasGuard, Term -> m Term)) -- the pattern, hasGuards, the right-hand side
convertMatch GHC.Match{..} =
(runPatternT $ maybe (convUnsupported "no-pattern case arms") pure . nonEmpty
=<< traverse convertLPat m_pats) <&> \case
Left _skipped -> Nothing
Right (pats, guards) ->
let extraGuards = map BoolGuard guards
rhs = convertGRHSs extraGuards m_grhss
hg | null extraGuards = hasGuards m_grhss
| otherwise = HasGuard
in Just (MultPattern pats, hg, rhs)
#if __GLASGOW_HASKELL__ >= 806
convertMatch (XMatch v) = noExtCon v
#endif
buildMatch :: ConversionMonad r m =>
NonEmpty MatchItem -> [(MultPattern, Term -> m Term)] -> Term -> m Term
-- This short-cuts wildcard matches (avoid introducing a match-with alltogether)
buildMatch _ [(pats,mkRhs)] failure
| isUnderscoreMultPattern pats = mkRhs failure
buildMatch scruts eqns failure = do
-- Pass the failure
eqns' <- forM eqns $ \(pat,mkRhs) -> (pat,) <$> mkRhs failure
is_complete <- isCompleteMultiPattern (map fst eqns')
pure $ Coq.Match scruts Nothing $
[ Equation [pats] rhs | (pats, rhs) <- eqns' ] ++
[ Equation [MultPattern (UnderscorePat <$ scruts)] failure | not is_complete ]
-- Only add a catch-all clause if the the patterns can fail
--------------------------------------------------------------------------------
hasGuards :: GRHSs b e -> HasGuard
hasGuards (GRHSs NOEXTP [ L _ (GRHS NOEXTP [] _) ] _) = HasNoGuard
hasGuards _ = HasGuard
convertGRHS :: LocalConvMonad r m
=> [ConvertedGuard m]
-> GRHS GhcRn (LHsExpr GhcRn)
-> ExceptT Qualid m (Term -> m Term)
convertGRHS extraGuards (GRHS NOEXTP gs rhs) = do
convGuards <- (extraGuards ++) <$> convertGuard gs
rhs <- convertLExpr rhs
pure $ \failure -> guardTerm convGuards rhs failure
#if __GLASGOW_HASKELL__ >= 806
convertGRHS _ (XGRHS v) = noExtCon v
#endif
convertLGRHSList :: LocalConvMonad r m
=> [ConvertedGuard m]
-> [LGRHS GhcRn (LHsExpr GhcRn)]
-> Term
-> m Term
convertLGRHSList extraGuards lgrhs failure = do
let rhss = unLoc <$> lgrhs
convRhss <- rights <$> traverse (runExceptT . convertGRHS extraGuards) rhss
chainFallThroughs convRhss failure
convertGRHSs :: LocalConvMonad r m
=> [ConvertedGuard m]
-> GRHSs GhcRn (LHsExpr GhcRn)
-> Term
-> m Term
convertGRHSs extraGuards GRHSs{..} failure =
convertLocalBinds (unLoc grhssLocalBinds) $
convertLGRHSList extraGuards grhssGRHSs failure
#if __GLASGOW_HASKELL__ >= 806
convertGRHSs _ (XGRHSs v) _ = noExtCon v
#endif
--------------------------------------------------------------------------------
data ConvertedGuard m = OtherwiseGuard
| BoolGuard Term
| PatternGuard Pattern Term
| LetGuard (m Term -> m Term)
convertGuard :: LocalConvMonad r m => [GuardLStmt GhcRn] -> ExceptT Qualid m [ConvertedGuard m]
convertGuard [] = pure []
convertGuard gs = collapseGuards <$> traverse (toCond . unLoc) gs where
#if __GLASGOW_HASKELL__ >= 806
toCond (BodyStmt _ e _bind _guard) =
#else
toCond (BodyStmt e _bind _guard _PlaceHolder) =
#endif
isTrueLExpr e >>= \case
True -> pure [OtherwiseGuard]
False -> (:[]) . BoolGuard <$> convertLExpr e
toCond (LetStmt NOEXTP (L _ binds)) =
pure . (:[]) . LetGuard $ convertLocalBinds binds
#if __GLASGOW_HASKELL__ >= 806
toCond (BindStmt _ pat exp _bind _fail) = do
#else
toCond (BindStmt pat exp _bind _fail PlaceHolder) = do
#endif
(pat', guards) <- runWriterT (convertLPat pat)
exp' <- convertLExpr exp
pure $ PatternGuard pat' exp' : map BoolGuard guards
toCond _ =
convUnsupported "impossibly fancy guards"
-- We optimize the code a bit, and combine
-- successive boolean guards with andb
collapseGuards = foldr addGuard [] . concat
-- TODO: Add multi-pattern-guard case
addGuard g [] =
[g]
addGuard (BoolGuard cond') (BoolGuard cond : gs) =
BoolGuard (App2 (Var "andb") cond' cond) : gs
addGuard g' (g:gs) =
g':g:gs
-- Returns a function waiting for the "else case"
guardTerm :: LocalConvMonad r m =>
[ConvertedGuard m] ->
Term -> -- The guarded expression
Term -> -- the failure expression
m Term
guardTerm gs rhs failure = go gs where
go [] =
pure rhs
go (OtherwiseGuard : gs) =
go gs
-- A little innocent but useful hack: Detect the pattern
-- | foo `seq` False = …
-- And hard-code that it fails
go (BoolGuard (App2 "GHC.Prim.seq" _ p) : gs) = go (BoolGuard p : gs)
go (BoolGuard "false" : _) = pure failure
go (BoolGuard cond : gs) =
ifThenElse <*> pure LinearIf <*> pure cond <*> go gs <*> pure failure
-- if the pattern is exhaustive, don't include an otherwise case
go (PatternGuard pat exp : gs) | isWildCoq pat = do
guarded' <- go gs
pure $ Coq.Match [MatchItem exp Nothing Nothing] Nothing
[ Equation [MultPattern [pat]] guarded' ]
go (PatternGuard pat exp : gs) = do
guarded' <- go gs
pure $ Coq.Match [MatchItem exp Nothing Nothing] Nothing
[ Equation [MultPattern [pat]] guarded'
, Equation [MultPattern [UnderscorePat]] failure ]
go (LetGuard bind : gs) =
bind $ go gs
--------------------------------------------------------------------------------
-- Does not detect recursion/introduce `fix`
convertTypedBinding :: LocalConvMonad r m => Maybe Term -> HsBind GhcRn -> m (Maybe ConvertedBinding)
convertTypedBinding _convHsTy VarBind{} = convUnsupported "[internal] `VarBind'"
convertTypedBinding _convHsTy AbsBinds{} = convUnsupported "[internal?] `AbsBinds'"
convertTypedBinding _convHsTy PatSynBind{} = convUnsupported "pattern synonym bindings"
#if __GLASGOW_HASKELL__ >= 806
convertTypedBinding _ (XHsBindsLR v) = noExtCon v
#endif
convertTypedBinding _convHsTy PatBind{..} = do -- TODO use `_convHsTy`?
-- TODO: Respect `skipped'?
-- TODO: what if we need to rename this definition? (i.e. for a class member)
ax <- view currentModuleAxiomatized
if ax
then
liftIO $ Nothing <$ putStrLn "skipping a pattern binding in an axiomatized module" -- TODO: FIX HACK
-- convUnsupported "pattern bindings in axiomatized modules"
else
runPatternT (convertLPat pat_lhs) >>= \case
Left _skipped -> pure Nothing
Right (pat, guards) -> Just . ConvertedPatternBinding pat <$> convertGRHSs (map BoolGuard guards) pat_rhs patternFailure
convertTypedBinding convHsTy FunBind{..} = do
name <- var ExprNS (unLoc fun_id)
-- Skip it? Axiomatize it?
definitionTask name >>= \case
SkipIt ->
pure . Just $ SkippedBinding name
RedefineIt def ->
pure . Just $ RedefinedBinding name def
AxiomatizeIt axMode ->
let missingType = case axMode of
SpecificAxiomatize -> convUnsupported "axiomatizing definitions without type signatures"
GeneralAxiomatize -> pure bottomType
in Just . ConvertedAxiomBinding name <$> maybe missingType pure convHsTy
TranslateIt -> do
let (tvs, coqTy) =
-- The @forall@ed arguments need to be brought into scope
let peelForall (Forall tvs body) = first (NEL.toList tvs ++) $ peelForall body
peelForall ty = ([], ty)
in maybe ([], Nothing) (second Just . peelForall) convHsTy
-- in maybe ([], Nothing) (second Just . peelForall) (Just $ Qualid $ Bare "test")
let tryCollapseLet defn = do
view (edits.collapsedLets.contains name) >>= \case
True -> collapseLet name defn
& maybe (convUnsupported "collapsing non-`let x=… in x` lets") pure
False -> pure defn
defn <-
tryCollapseLet =<<
if all (null . m_pats . unLoc) . unLoc $ mg_alts fun_matches
then case unLoc $ mg_alts fun_matches of
[L _ (GHC.Match NOEXTP _ [] grhss)] -> convertGRHSs [] grhss patternFailure
_ -> convUnsupported "malformed multi-match variable definitions"
else do
skipEqns <- view $ edits.skippedEquations.at name.non mempty
uncurry Fun <$> convertFunction skipEqns fun_matches
addScope <- maybe id (flip InScope) <$> view (edits.additionalScopes.at (SPValue, name))
pure . Just . ConvertedDefinitionBinding $ ConvertedDefinition name tvs coqTy (addScope defn)
collapseLet :: Qualid -> Term -> Maybe Term
collapseLet outer (Let x args _oty defn (Qualid x')) | x == x' =
Just . maybeFun args $ case defn of
Fix (FixOne (FixBody f args' _mord _oty body)) -> Fun args' $ subst1 f (Qualid outer) body
_ -> defn
collapseLet _ _ =
Nothing
wfFix :: ConversionMonad r m => TerminationArgument -> FixBody -> m Term
wfFix Deferred (FixBody ident argBinders Nothing Nothing rhs)
= pure $ App1 (Qualid deferredFixN) $ Fun (mkBinder Explicit (Ident ident) NEL.<| argBinders ) rhs
where
deferredFixN = qualidMapBase (<> T.pack (show (NEL.length argBinders)))
"GHC.DeferredFix.deferredFix"
wfFix (WellFoundedTA order) (FixBody ident argBinders Nothing Nothing rhs)
= do (rel, measure) <- case order of
MeasureOrder_ measure Nothing -> pure ("Coq.Init.Peano.lt", measure)
MeasureOrder_ measure (Just rel) -> pure (rel, measure)
WFOrder_ rel arg -> pure (rel, Qualid arg)
pure . appList (Qualid wfFixN) $ map PosArg
[ rel
, Fun argBinders measure
, Underscore
, Fun (argBinders NEL.|> mkBinder Explicit (Ident ident)) rhs
]
where
wfFixN = qualidMapBase (<> T.pack (show (NEL.length argBinders)))
"GHC.Wf.wfFix"
wfFix Corecursive fb = pure . Cofix $ FixOne fb
wfFix StructOrderTA{} (FixBody ident _ _ _ _) = convUnsupportedIn
"well-founded recursion does not include structural recursion"
"fixpoint" (showP ident)
wfFix _ fb = convUnsupportedIn "well-founded recursion cannot handle annotations or types"
"fixpoint"
(showP $ fb^.fixBodyName)
--------------------------------------------------------------------------------
-- find the first name in a pattern binding
patBindName :: ConversionMonad r m => Pat GhcRn -> m Qualid
patBindName p = case p of
WildPat _ -> convUnsupported' ("no name in binding pattern")
GHC.VarPat NOEXTP (L _ hsName) -> var ExprNS hsName
LazyPat NOEXTP p -> lpatBindName p
GHC.AsPat NOEXTP (L _ hsName) _ -> var ExprNS hsName
ParPat NOEXTP p -> lpatBindName p
BangPat NOEXTP p -> lpatBindName p
#if __GLASGOW_HASKELL__ >= 806
ListPat _ (p:_) -> lpatBindName p
TuplePat _ (p:_) _ -> lpatBindName p
#else
ListPat (p:_) _ _ -> lpatBindName p
TuplePat (p:_) _ _ -> lpatBindName p
#endif
_ -> convUnsupported' ("Cannot find name in pattern: " ++ GHC.showSDocUnsafe (GHC.ppr p))
lpatBindName :: ConversionMonad r m => LPat GhcRn -> m Qualid
lpatBindName = patBindName . unLPat
unLPat :: LPat GhcRn -> Pat GhcRn
toLPat :: String -> Pat GhcRn -> LPat GhcRn
#if __GLASGOW_HASKELL__ == 808
unLPat = id
toLPat _ = id
#else
unLPat = unLoc
toLPat = mkGeneralLocated
#endif
hsBindName :: ConversionMonad r m => HsBind GhcRn -> m Qualid
hsBindName defn = case defn of
FunBind{fun_id = L _ hsName} -> var ExprNS hsName
PatBind{pat_lhs = p} -> lpatBindName p
_ -> convUnsupported' ( "non-function top level bindings: " ++ GHC.showSDocUnsafe (GHC.ppr defn))
-- | Warn and immediately return 'Nothing' for unsupported top-level bindings.
withHsBindName
:: ConversionMonad r m => HsBind GhcRn -> (Qualid -> m (Maybe a)) -> m (Maybe a)
withHsBindName b continue = case b of
FunBind{fun_id = L _ hsName} -> var ExprNS hsName >>= continue
PatBind{pat_lhs = p} ->
warnConvUnsupported' (getLoc p) "top-level pattern binding" $> Nothing
PatSynBind NOEXTP PSB{psb_id = i} ->
warnConvUnsupported' (getLoc i) "pattern synonym" $> Nothing
VarBind{} -> convUnsupported' "[internal] `VarBind' can't be a top-level binding"
AbsBinds{} -> convUnsupported' "[internal] `AbsBinds' can't be a top-level binding"
#if __GLASGOW_HASKELL__ >= 806
PatSynBind NOEXTP (XPatSynBind v) -> noExtCon v
XHsBindsLR v -> noExtCon v
#endif
-- This is where we switch from the global monad to the local monad
convertTypedModuleBinding :: ConversionMonad r m => Maybe Term -> HsBind GhcRn -> m (Maybe ConvertedBinding)
convertTypedModuleBinding ty defn =
withHsBindName defn $ \name ->
withCurrentDefinition name $ convertTypedBinding ty defn
convertTypedModuleBindings :: ConversionMonad r m
=> [LHsBind GhcRn]
-> Map Qualid Signature
-> (ConvertedBinding -> m a)
-> Maybe (HsBind GhcRn -> GhcException -> m a)
-> m [a]
convertTypedModuleBindings = convertMultipleBindings convertTypedModuleBinding
-- | A variant of convertTypedModuleBinding that ignores the name in the HsBind
-- and uses the provided one instead
--
-- It also does not allow skipping or axiomatization, does not create fixpoints,
-- does not support a type, and always returns a binding (or fails with
-- convUnsupported).
--
-- It does, however, support redefinition.
convertMethodBinding :: ConversionMonad r m => Qualid -> HsBind GhcRn -> m ConvertedBinding
convertMethodBinding name VarBind{} = convUnsupportedIn "[internal] `VarBind'" "method" (showP name)
convertMethodBinding name AbsBinds{} = convUnsupportedIn "[internal?] `AbsBinds'" "method" (showP name)
convertMethodBinding name PatSynBind{} = convUnsupportedIn "pattern synonym bindings" "method" (showP name)
convertMethodBinding name PatBind{} = convUnsupportedIn "pattern bindings" "method" (showP name)
convertMethodBinding name FunBind{..} = withCurrentDefinition name $ do
definitionTask name >>= \case
SkipIt ->
convUnsupported "skipping instance method definitions (without `skip method')"
RedefineIt def ->
pure $ RedefinedBinding name def
AxiomatizeIt _ ->
convUnsupported "axiomatizing instance method definitions"
TranslateIt -> do
defn <-
if all (null . m_pats . unLoc) . unLoc $ mg_alts fun_matches
then case unLoc $ mg_alts fun_matches of
[L _ (GHC.Match NOEXTP _ [] grhss)] -> convertGRHSs [] grhss patternFailure
_ -> convUnsupported "malformed multi-match variable definitions"
else do
skipEqns <- view $ edits.skippedEquations.at name.non mempty
uncurry Fun <$> convertFunction skipEqns fun_matches
pure $ ConvertedDefinitionBinding $ ConvertedDefinition name [] Nothing defn
#if __GLASGOW_HASKELL__ >= 806
convertMethodBinding _ (XHsBindsLR v) = noExtCon v
#endif
convertTypedBindings :: LocalConvMonad r m
=> [LHsBind GhcRn] -> Map Qualid Signature
-> (ConvertedBinding -> m a)
-> Maybe (HsBind GhcRn -> GhcException -> m a)
-> m [a]
convertTypedBindings = convertMultipleBindings convertTypedBinding
convertMultipleBindings :: ConversionMonad r m
=> (Maybe Term -> HsBind GhcRn -> m (Maybe ConvertedBinding))
-> [LHsBind GhcRn]
-> Map Qualid Signature
-> (ConvertedBinding -> m a)
-> Maybe (HsBind GhcRn -> GhcException -> m a)
-> m [a]
convertMultipleBindings convertSingleBinding defns0 sigs build mhandler =
let defns = sortOn getLoc defns0
(handler, wrap) = case mhandler of
Just handler -> ( uncurry handler
, \defn -> ghandle $ pure . Left . (defn,))
Nothing -> ( const $ throwProgramError
"INTERNAL ERROR: convertMultipleBindings tried to both handle and ignore an exception"
-- Safe because the only place `Left' is introduced
-- is in the previous case branch
, flip const )
in traverse (either handler build) <=< addRecursion <=< fmap catMaybes . for defns $ \(L _ defn) ->
-- 'MaybeT' is responsible for handling the skipped definitions, and
-- nothing else
runMaybeT . wrap defn . fmap Right $ do
ty <- case defn of
FunBind{fun_id = L _ hsName} ->
fmap (fmap sigType) . (`lookupSig` sigs) =<< var ExprNS hsName
_ ->
pure Nothing
MaybeT $ convertSingleBinding ty defn
-- ALMOST a 'ConvertedDefinition', but:
-- (a) It's guaranteed to have arguments; and
-- (b) We store two types: the result type AFTER the argument types
-- ('rdResultType'), and the full type including the argument types
-- ('rdFullType')
data RecDef = RecDef { rdName :: !Qualid
, rdArgs :: !Binders
, rdStruct :: !(Maybe Order)
, rdResultType :: !(Maybe Term)
, rdFullType :: !(Maybe Term)
, rdBody :: !Term }
deriving (Eq, Ord, Show, Read)
-- CURRENT IMPLEMENTATION: If we can't move the type to arguments, then:
-- * If it was translated, fail-safe, and translate without the type
-- * If it was specified, abort
-- We can't unilaterally abort unless we can change type signatures.
rdToFixBody :: RecDef -> FixBody
rdToFixBody RecDef{..} = FixBody rdName rdArgs rdStruct rdResultType rdBody
rdToLet :: RecDef -> Term -> Term
rdToLet RecDef{..} = Let rdName (toList rdArgs) rdResultType rdBody
rdStripResultType :: RecDef -> RecDef
rdStripResultType rd = rd{rdResultType = Nothing}
splitInlinesWith :: Foldable f => Set Qualid -> f RecDef -> Maybe (Map Qualid RecDef, NonEmpty RecDef)
splitInlinesWith inlines =
bitraverse (pure . fold) nonEmpty .: mapPartitionEithers $ \rd@RecDef{..} ->
if rdName `elem` inlines
then Left $ M.singleton rdName rd
else Right rd
data RecType = Standalone | Mutual deriving (Eq, Ord, Enum, Bounded, Show, Read)
mutualRecursionInlining :: ConversionMonad r m => NonEmpty RecDef -> m (Map Qualid (RecType, RecDef))
mutualRecursionInlining mutGroup = do
-- TODO: Names of recursive functions in inlining errors
inlines <- view $ edits.inlinedMutuals
(lets, recs) <- splitInlinesWith inlines mutGroup
& maybe (editFailure "can't inline every function in a mutually-recursive group") pure
let rdFVs = getFreeVars . rdBody
letUses = rdFVs <$> lets
letDeps = transitiveClosure Reflexive letUses
orderedLets <- for (topoSortEnvironmentWith id letUses) $ \case
solo :| [] -> pure solo
_ :| _:_ -> editFailure "recursion forbidden amongst inlined mutually-recursive functions"
let recMap = flip foldMap recs $ \rd ->
let neededLets = foldMap (M.findWithDefault mempty ?? letDeps) $ rdFVs rd
inlinedDeps = filter (`elem` neededLets) orderedLets
in M.singleton (rdName rd)
(Mutual, rd{rdBody = foldr (rdToLet . (lets M.!)) (rdBody rd) inlinedDeps})
pure $ ((Standalone,) <$> lets) <> recMap
addRecursion :: ConversionMonad r m => [Either e ConvertedBinding] -> m [Either e ConvertedBinding]
addRecursion eBindings = do
fixedBindings <- M.fromList . fmap (view convDefName &&& id) . foldMap toList
<$> traverse fixConnComp (stronglyConnCompNE
[ (cd, cd^.convDefName, S.toAscList . getFreeVars $ cd^.convDefBody)
| Right (ConvertedDefinitionBinding cd) <- eBindings ])
pure . topoSortByVariablesBy ErrOrVars M.empty . flip map eBindings $ \case
Right (ConvertedDefinitionBinding cd) -> case M.lookup (cd^.convDefName) fixedBindings of
Just cd' -> Right $ ConvertedDefinitionBinding cd'
Nothing -> error "INTERNAL ERROR: lost track of converted definition during mutual recursion check"
untouched ->
untouched
where
fixConnComp (cd :| []) | cd^.convDefName `notElem` getFreeVars (cd^.convDefBody) =
pure $ cd :| []
fixConnComp cds = do
(commonArgs, cds) <- splitArgs cds
tbodies <- for cds fixConvertedDefinition
let bodies = fst <$> tbodies
let nonstructural = listToMaybe [t | (_, Just t) <- toList tbodies, isNonstructural t]
isNonstructural (StructOrderTA _) = False
isNonstructural _ = True
let getInfo = fmap $ rdName &&& rdFullType
(fixFor, recInfos, extraDefs) <- case (nonstructural, bodies) of
(Just order, body1 :| []) -> do
fixed <- wfFix order . rdToFixBody $ rdStripResultType body1
pure (const fixed, getInfo bodies, [])
(Just _, _ :| _ : _) ->
convUnsupportedIn "non-structural mutual recursion" "definitions"
(explainStrItems (showP . rdName) "" "," "and" "" "" bodies)
(Nothing, body1 :| []) ->
pure (const . Fix . FixOne $ rdToFixBody body1, getInfo bodies, [])
(Nothing, _ :| _ : _) -> do
mutRecInfo <- mutualRecursionInlining bodies
let (recs', lets) = flip mapPartitionEithers cds $ \cd ->
case M.lookup (cd^.convDefName) mutRecInfo of
Just (Standalone, _) -> Right $ cd & convDefArgs %~ (commonArgs ++)
Just (Mutual, rd) -> Left rd
Nothing -> error "INTERNAL ERROR: lost track of mutually-recursive function"
recs = fromMaybe (error "INTERNAL ERROR: \
\all mutually-recursive functions in this group vanished!")
$ nonEmpty recs'
let fixFor = case recs of
body1 :| [] ->
const . Fix . FixOne $ rdToFixBody body1
body1 :| body2 : bodies' ->
Fix . FixMany (rdToFixBody body1) (rdToFixBody <$> (body2 :| bodies'))
pure (fixFor, getInfo recs, lets)
let recDefs = recInfos <&> \(name,mty) ->
ConvertedDefinition { _convDefName = name
, _convDefArgs = commonArgs
, _convDefType = mty
, _convDefBody = fixFor name }
pure $ recDefs ++> extraDefs
fixConvertedDefinition ::
ConversionMonad r m => ConvertedDefinition -> m (RecDef, Maybe TerminationArgument)
fixConvertedDefinition (ConvertedDefinition{_convDefBody = Fun args body, ..}) = do
let fullType = maybeForall _convDefArgs <$> _convDefType
allArgs = _convDefArgs <++ args
(resultType, convArgs') = case fullType of
Just ty | Right (ty', args', UTIBIsTypeTooShort False) <- useTypeInBinders ty allArgs ->
(Just ty', args')
_ -> (Nothing, allArgs)
termination <- view (edits.termination.at _convDefName)
struct <- case termination of
Just (StructOrderTA (StructId_ n)) -> (pure . Just) (StructOrder n)
Just (StructOrderTA (StructPos_ i)) ->
case args ^? elementOf (traverse . binderNames) (i - 1) of
Just (Ident name) -> (pure . Just) (StructOrder name)
Just UnderscoreName ->
throwProgramError ("error: function " ++ showP _convDefName ++ ": its " ++ show i ++ "-th argument is unnamed")
Nothing -> throwProgramError ("error: function " ++ showP _convDefName ++ " has fewer than " ++ show i ++ " arguments")
_ -> pure Nothing
let b = RecDef
{ rdName = _convDefName
, rdArgs = convArgs'
, rdStruct = struct
, rdResultType = resultType
, rdFullType = fullType
, rdBody = body }
pure (b, termination)
fixConvertedDefinition cd =
convUnsupportedIn "recursion through non-lambda value" "definition" (showP $ cd^.convDefName)
splitArgs :: (ConversionMonad r m, Traversable t) => t ConvertedDefinition -> m ([Binder], t ConvertedDefinition)
splitArgs cds = do
polyrec <- findM (\rd -> view $ edits.polyrecs.at (_convDefName rd)) cds
case polyrec of
Nothing -> pure (splitCommonPrefixOf convDefArgs cds)
Just _ -> pure ([], cds)
--------------------------------------------------------------------------------
convertLocalBinds :: LocalConvMonad r m => HsLocalBinds GhcRn -> m Term -> m Term
#if __GLASGOW_HASKELL__ >= 806
convertLocalBinds (XHsLocalBindsLR v) _ = noExtCon v
convertLocalBinds (HsValBinds _ (ValBinds{})) _ =
convUnsupported "Unexpected ValBinds in post-renamer AST"
convertLocalBinds (HsValBinds _ (XValBindsLR (NValBinds recBinds lsigs))) body = do
#else
convertLocalBinds (HsValBinds (ValBindsIn{})) _ =
convUnsupported "Unexpected ValBindsIn in post-renamer AST"
convertLocalBinds (HsValBinds (ValBindsOut recBinds lsigs)) body = do
#endif
sigs <- convertLSigs lsigs
-- We are not actually using the rec_flag from GHC, because due to renamings
-- or `redefinition` edits, maybe the group is no longer recursive.
convDefss <- for recBinds $ \(_rec_flag, mut_group) ->
convertTypedBindings (bagToList mut_group) sigs pure Nothing
let convDefs = concat convDefss
let fromConvertedBinding cb body = case cb of
ConvertedDefinitionBinding (ConvertedDefinition{..}) ->
pure (Let _convDefName _convDefArgs _convDefType _convDefBody body)
ConvertedPatternBinding pat term -> do
is_complete <- isCompleteMultiPattern [MultPattern [pat]]
pure $ Coq.Match [MatchItem term Nothing Nothing] Nothing $
[ Equation [MultPattern [pat]] body] ++
[ Equation [MultPattern [UnderscorePat]] patternFailure | not is_complete ]
ConvertedAxiomBinding ax _ty ->
convUnsupported $ "local axiom `" ++ T.unpack (qualidToIdent ax) ++ "' unsupported"
RedefinedBinding _nm _sn -> convUnsupported "redefining local bindings"
SkippedBinding _nm -> convUnsupported "skipping local binding"
(foldrM fromConvertedBinding ?? convDefs) =<< body
convertLocalBinds (HsIPBinds NOEXTP _) _ =
convUnsupported "local implicit parameter bindings"
convertLocalBinds (EmptyLocalBinds NOEXTP) body =
body
--------------------------------------------------------------------------------
-- Create `let x := rhs in genBody x`
-- Unless the rhs is very small, in which case it creates `genBody rhs`
bindIn :: LocalConvMonad r m => Text -> Term -> (Term -> m Term) -> m Term
bindIn _ rhs@(Qualid _) genBody = genBody rhs
bindIn tmpl rhs genBody = do
j <- genqid tmpl
body <- genBody (Qualid j)
pure $ smartLet j rhs body
-- This prevents the pattern conversion code to create
-- `let j_24__ := … in j_24__`
-- and a few other common and obviously stupid forms
--
-- Originally, we avoided pushing the `rhs` past a binder. But it turned out
-- that we need to do that to get useful termination proof obligations out of
-- program fixpoint. So now we move the `rhs` past a binder if that binder is fresh (i.e. cannot be captured).
-- Let’s cross our fingers that we calculate all free variables properly.
smartLet :: Qualid -> Term -> Term -> Term
-- Move into the else branch
smartLet ident rhs (If is c Nothing t e)
| ident `S.notMember` getFreeVars c
, ident `S.notMember` getFreeVars t
= If is c Nothing t (smartLet ident rhs e)
-- Move into the scrutinee
smartLet ident rhs
(Coq.Match [MatchItem t Nothing Nothing] Nothing eqns)
| ident `S.notMember` getFreeVars eqns
= Coq.Match [MatchItem (smartLet ident rhs t) Nothing Nothing] Nothing eqns
-- Move into the last equation
-- (only if not mentioned in any earlier equation and only if no matched
-- variables is caught)
smartLet ident rhs
(Coq.Match scruts Nothing eqns)
| ident `S.notMember` getFreeVars (fmap NoBinding scruts)
, let intoEqns [] = Just []
intoEqns [Equation pats body] = do
let bound = S.fromList $ foldMap definedBy pats
guard $ ident `S.notMember` bound
guard $ S.null $ bound `S.intersection` getFreeVars rhs
return [Equation pats (smartLet ident rhs body)]
intoEqns (e:es) = do
guard $ ident `S.notMember` getFreeVars e
(e:) <$> intoEqns es
, Just eqns' <- intoEqns eqns
= Coq.Match scruts Nothing eqns'
smartLet ident rhs (Qualid v) | ident == v = rhs
smartLet ident rhs body = Let ident [] Nothing rhs body
patternFailure :: Term
patternFailure = "GHC.Err.patternFailure"
missingValue :: Term
missingValue = "missingValue"
-- | Program does not work nicely with if-then-else, so if we believe we are
-- producing a term that ends up in a Program Fixpoint or Program Definition,
-- then desguar if-then-else using case statements.
ifThenElse :: LocalConvMonad r m => m (IfStyle -> Term -> Term -> Term -> Term)
ifThenElse = useProgramHere >>= \case
False -> pure $ evalConstScrut IfBool
True -> pure $ evalConstScrut IfCase
where
-- Reduce `if true` and `if false`
evalConstScrut :: (IfStyle -> Term -> Term -> Term -> Term)
-> (IfStyle -> Term -> Term -> Term -> Term)
evalConstScrut _ _ "true" e _ = e
evalConstScrut _ _ "false" _ e = e
evalConstScrut ifComb is scrut e1 e2 = ifComb is scrut e1 e2
|
antalsz/hs-to-coq
|
src/lib/HsToCoq/ConvertHaskell/Expr.hs
|
Haskell
|
mit
| 60,967
|
module Handler.Quizcreator where
import Assets (unsignedProcentField, unsignedIntField, maybeInt,
maybeDouble, encodeExamAttributes, titleTextField,
noSpacesTextField, getAllExams)
import Data.Text (splitOn)
import Data.List.Split (chunksOf)
import Data.List (cycle)
import Import
import Widgets (titleWidget, iconWidget, publicExamWidget, postWidget,
errorWidget, spacingScript, privateExamWidget)
-- | Checks if exam attributes have already been submitted
-- If so, proceed to question input
-- If not, let the user submit them
getQuizcreatorR :: Handler Html
getQuizcreatorR = do
setUltDestCurrent
memail <- lookupSession "_ID"
(publicExams, privateExams) <- runDB $ getAllExams memail
mayAttributes <- lookupSession "examAttributes"
let generatePost = case mayAttributes of
(Just text) -> generateFormPost $ examForm $ toExamAttributes text
_ -> generateFormPost $ examAttributesMForm
(widget, enctype) <- generatePost
let middleWidget = postWidget enctype widget
defaultLayout $(widgetFile "quizcreator")
-- | Checks if exam attributes have already been submitted
-- If so, checks if questions have been submitted correctly and saves the exam in that case (shows error otherwise)
-- If not, submits entered input and redirects to question input
postQuizcreatorR :: Handler Html
postQuizcreatorR = do
mayAttributes <- lookupSession "examAttributes"
memail <- lookupSession "_ID"
(publicExams, privateExams) <- runDB $ getAllExams memail
case mayAttributes of
(Just text) -> do ((res, _), _) <- runFormPost $ examForm $ toExamAttributes text
case res of
(FormSuccess exam) -> do
deleteSession "examAttributes"
_ <- runDB $ insert $ exam memail
redirect HomeR
(_) -> do
let middleWidget = errorWidget "Exam parsing"
defaultLayout $ do $(widgetFile "quizcreator")
(_) -> do ((res, _), _) <- runFormPost examAttributesMForm
case res of
(FormSuccess (ExamAttributes title percent qCount)) -> do
setSession "examAttributes" $ encodeExamAttributes title percent qCount
redirect QuizcreatorR
(_) -> do
deleteSession "examAttributes"
redirect QuizcreatorR
-- | Generates enumerated exam form based on previously submitted exam attributes
examForm :: ExamAttributes -> Html -> MForm Handler ((FormResult (Maybe Text -> Exam)), Widget)
examForm (ExamAttributes title passPercentage questCount) token = do
qTextFields <- replicateM questCount (mreq noSpacesTextField "" Nothing)
aTextFields <- replicateM (4 * questCount) (mreq noSpacesTextField "" Nothing)
aBoolFields <- replicateM (4 * questCount) (mreq boolField "" (Just False))
let (qTextResults, qTextViews) = unzip qTextFields
(aTextResults, aTextViews) = unzip aTextFields
(aBoolResults, aBoolViews) = unzip aBoolFields
answerResList = zipWith (\(FormSuccess x) (FormSuccess y) -> Answer x y) aTextResults aBoolResults
questions = FormSuccess $ zipWith (\(FormSuccess q) as -> Question q as) qTextResults (chunksOf 4 answerResList)
exam = Exam title passPercentage <$> questions
answerViews = zipWith3 zip3 (chunksOf 4 aTextViews) (chunksOf 4 aBoolViews) (cycle [[1..4::Int]])
questionViews = zip3 qTextViews answerViews ([1..]::[Int])
widget = [whamlet|
#{token}
<table class=questCreator>
$forall (qView, aList,n) <- questionViews
<tr>
<td class=questionTD>_{MsgQuestion 1} _{MsgNr}. #{show n}:
<td style="color:black"> ^{fvInput qView}
$forall (tview, bview, c) <- aList
<tr>
<td class=smallWhite>_{MsgAnswer 1} _{MsgNr}.#{show c}:
<td style="color:black;"> ^{fvInput tview}
<td class=smallWhite>_{MsgIsCorrect}
<td class=smallWhite>^{fvInput bview}
<td>
<tr>
<td style="text-align:left;">
<a class=questionTD href=@{SessionMasterR}> _{MsgGetBack}
<td>
<td colspan=2 style="text-align:right;"><input type=submit value="_{MsgSubmitQuest questCount}">
|]
return (exam, widget)
-- | Generates exam attributes form
examAttributesMForm :: Html -> MForm Handler ((FormResult ExamAttributes), Widget)
examAttributesMForm token = do
(eTitleResult, eTitleView) <- mreq (titleTextField MsgExamTitle) "" Nothing
(ePassResult, ePassView) <- mreq (unsignedProcentField MsgInputNeg) "" (Just 50.0)
(eCountResult, eCountView) <- mreq (unsignedIntField MsgInputNeg)"" (Just 5)
let examAttributes = ExamAttributes <$> eTitleResult <*> ePassResult <*> eCountResult
widget = [whamlet|
#{token}
<table class=questCreator>
<tr>
<td class=smallWhite> _{MsgExamTitle}:
<td style="color:black"> ^{fvInput eTitleView}
<td class=smallWhite style="text-align:left;"> _{MsgErrExamTitle}
<tr>
<td class=smallWhite> _{MsgPassPercentage}:
<td span style="color:black"> ^{fvInput ePassView}
<td class=smallWhite style="text-align:left;"> _{MsgErrPassPercentage}
<tr>
<td class=smallWhite> _{MsgQuestionNum}:
<td span style="color:black"> ^{fvInput eCountView}
<td class=smallWhite style="text-align:left;"> _{MsgErrQuestionNum}
<tr>
<td>
<td style="text-align:right;"><input type=submit value="_{MsgStartExam}">
|]
return (examAttributes, widget)
-- | Reads exam attributes from cookie
toExamAttributes :: Text -> ExamAttributes
toExamAttributes ((splitOn "($)") -> [a, b, c]) = let (Just passPercentage) = maybeDouble $ unpack b
(Just questCount) = maybeInt $ unpack c
title = (unwords . words) a in
ExamAttributes title passPercentage questCount
toExamAttributes _ = ExamAttributes msg 0.0 0
where msg = "Error in cookie" :: Text
data ExamAttributes = ExamAttributes {
title :: Text
, passPercentage :: Double
, questCount :: Int
}
|
cirquit/quizlearner
|
quizlearner/Handler/Quizcreator.hs
|
Haskell
|
mit
| 7,317
|
module Handler.Home where
import Import
import Data.Maybe
import Yesod.Auth
getHomeR :: Handler Html
getHomeR = do
loggedIn <- isJust <$> maybeAuthId
defaultLayout $ do
setTitle "Home - Word Guesser"
$(widgetFile "home")
|
dphilipson/word_guesser_web
|
Handler/Home.hs
|
Haskell
|
mit
| 247
|
module Lexer where
import Text.Parsec.String (Parser)
import Text.Parsec.Language (emptyDef)
import Text.Parsec.Prim (many)
import qualified Text.Parsec.Token as Tok
lexer :: Tok.TokenParser ()
lexer = Tok.makeTokenParser style
where
ops = ["+","*","-","/",";","=",",","<",">","|",":"]
names = ["def","extern","if","then","else","in","for"
,"binary", "unary", "var"]
style = emptyDef {
Tok.commentLine = "#"
, Tok.reservedOpNames = ops
, Tok.reservedNames = names
}
integer = Tok.integer lexer
float = Tok.float lexer
parens = Tok.parens lexer
commaSep = Tok.commaSep lexer
semiSep = Tok.semiSep lexer
identifier = Tok.identifier lexer
whitespace = Tok.whiteSpace lexer
reserved = Tok.reserved lexer
reservedOp = Tok.reservedOp lexer
operator :: Parser String
operator = do
c <- Tok.opStart emptyDef
cs <- many $ Tok.opLetter emptyDef
return (c:cs)
|
TorosFanny/kaleidoscope
|
src/chapter6/Lexer.hs
|
Haskell
|
mit
| 959
|
module Main where
import LI11718
import qualified Tarefa3_2017li1g180 as T3
import System.Environment
import Text.Read
main = do
args <- getArgs
case args of
["movimenta"] -> do
str <- getContents
let params = readMaybe str
case params of
Nothing -> error "parâmetros inválidos"
Just (mapa,tempo,carro) -> print $ T3.movimenta mapa tempo carro
["testes"] -> print $ T3.testesT3
otherwise -> error "RunT3 argumentos inválidos"
|
hpacheco/HAAP
|
examples/plab/svn/2017li1g180/src/RunT3.hs
|
Haskell
|
mit
| 531
|
module Feature.Article.PG where
import ClassyPrelude
import Feature.Article.Types
import Feature.Auth.Types
import Feature.Common.Types
import Platform.PG
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.Types
addArticle :: PG r m => UserId -> CreateArticle -> Slug -> m ()
addArticle uId param slug =
void . withConn $ \conn -> execute conn qry
( slug, createArticleTitle param, createArticleDescription param
, createArticleBody param, uId, PGArray $ createArticleTagList param
)
where
qry = "insert into articles (slug, title, description, body, created_at, updated_at, author_id, tags) \
\values (?, ?, ?, ?, now(), now(), ?, ?)"
updateArticleBySlug :: PG r m => Slug -> UpdateArticle -> Slug -> m ()
updateArticleBySlug slug param newSlug =
void . withConn $ \conn -> execute conn qry (newSlug, updateArticleTitle param, updateArticleDescription param, updateArticleBody param, slug)
where
qry = "update articles \
\set slug = ?, title = coalesce(?, title), description = coalesce(?, description), \
\ body = coalesce(?, body), updated_at = now() \
\where slug = ?"
deleteArticleBySlug :: PG r m => Slug -> m ()
deleteArticleBySlug slug =
void . withConn $ \conn -> execute conn qry (Only slug)
where
qry = "delete from articles where slug = ?"
isArticleOwnedBy :: PG r m
=> UserId -> Slug -> m (Maybe Bool)
isArticleOwnedBy uId slug = do
result <- withConn $ \conn -> query conn qry (uId, slug)
case result of
[Only True] -> return $ Just True
[Only False] -> return $ Just False
_ -> return Nothing
where
qry = "select author_id = ? from articles where slug = ? limit 1"
favoriteArticleBySlug :: PG r m => UserId -> Slug -> m ()
favoriteArticleBySlug uId slug =
void . withConn $ \conn -> execute conn qry (uId, slug)
where
qry = "with cte as ( \
\ select id, ? from articles where slug = ? limit 1 \
\) \
\insert into favorites (article_id, favorited_by) (select * from cte) on conflict do nothing"
unfavoriteArticleBySlug :: PG r m => UserId -> Slug -> m ()
unfavoriteArticleBySlug uId slug =
void . withConn $ \conn -> execute conn qry (slug, uId)
where
qry = "with cte as ( \
\ select id from articles where slug = ? limit 1 \
\) \
\delete from favorites where article_id in (select id from cte) and favorited_by = ?"
findArticles :: PG r m
=> Maybe Slug -> Maybe Bool -> Maybe CurrentUser
-> ArticleFilter -> Pagination
-> m [Article]
findArticles maySlug mayFollowing mayCurrentUser articleFilter pagination =
withConn $ \conn -> query conn qry arg
where
qry = [sql|
with profiles as (
select
id, name, bio, image, exists(select 1 from followings where user_id = id and followed_by = ?) as following
from
users
),
formatted_articles as (
select
articles.id, slug, title, description, body, tags, created_at, updated_at,
exists(select 1 from favorites where article_id = articles.id and favorited_by = ?) as favorited,
(select count(1) from favorites where article_id = articles.id) as favorites_count,
profiles.name as pname, profiles.bio as pbio, profiles.image as pimage, profiles.following as pfollowing
from
articles join profiles on articles.author_id = profiles.id
)
select
cast (slug as text), title, description, body, cast (tags as text[]), created_at, updated_at,
favorited, favorites_count, cast (pname as text), pbio, pimage, pfollowing
from
formatted_articles
where
-- by slug (for find one)
coalesce(slug in ?, true) AND
-- by if user following author (for feed)
coalesce(pfollowing in ?, true) and
-- by tag (for normal filter)
(cast (tags as text[]) @> ?) and
-- by author (for normal filter)
coalesce (pname in ?, true) and
-- by fav by (for normal filter)
(? is null OR exists(
select 1
from favorites join users on users.id = favorites.favorited_by
where article_id = formatted_articles.id and users.name = ?)
)
order by id desc
limit greatest(0, ?) offset greatest(0, ?)
|]
curUserId = maybe (-1) snd mayCurrentUser
arg = ( curUserId, curUserId
-- ^ 2 slots for current user id
, In $ maybeToList maySlug
-- ^ 1 slot for slug
, In $ maybeToList $ mayFollowing
-- ^ 1 slot for following
, PGArray $ maybeToList $ articleFilterTag articleFilter
-- ^ 1 slot for tags
, In $ maybeToList $ articleFilterAuthor articleFilter
-- ^ 1 slot for author
, articleFilterFavoritedBy articleFilter, articleFilterFavoritedBy articleFilter
-- ^ 2 slots for favorited by user name
, paginationLimit pagination, paginationOffset pagination
-- ^ 2 slot for limit & offset
)
isArticleExist :: PG r m => Slug -> m Bool
isArticleExist slug = do
results <- withConn $ \conn -> query conn qry (Only slug)
return $ results == [Only True]
where
qry = "select true from articles where slug = ? limit 1"
allTags :: PG r m => m (Set Tag)
allTags = do
results <- withConn $ \conn -> query_ conn qry
return $ setFromList $ (\(Only tag) -> tag) <$> results
where
qry = "select cast(tag as text) from (select distinct unnest(tags) as tag from articles) tags"
|
eckyputrady/haskell-scotty-realworld-example-app
|
src/Feature/Article/PG.hs
|
Haskell
|
mit
| 5,884
|
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Hadoop.Protos.XAttrProtos.SetXAttrResponseProto (SetXAttrResponseProto(..)) where
import Prelude ((+), (/))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data SetXAttrResponseProto = SetXAttrResponseProto{}
deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable SetXAttrResponseProto where
mergeAppend SetXAttrResponseProto SetXAttrResponseProto = SetXAttrResponseProto
instance P'.Default SetXAttrResponseProto where
defaultValue = SetXAttrResponseProto
instance P'.Wire SetXAttrResponseProto where
wireSize ft' self'@(SetXAttrResponseProto)
= case ft' of
10 -> calc'Size
11 -> P'.prependMessageSize calc'Size
_ -> P'.wireSizeErr ft' self'
where
calc'Size = 0
wirePut ft' self'@(SetXAttrResponseProto)
= case ft' of
10 -> put'Fields
11 -> do
P'.putSize (P'.wireSize 10 self')
put'Fields
_ -> P'.wirePutErr ft' self'
where
put'Fields
= do
Prelude'.return ()
wireGet ft'
= case ft' of
10 -> P'.getBareMessageWith update'Self
11 -> P'.getMessageWith update'Self
_ -> P'.wireGetErr ft'
where
update'Self wire'Tag old'Self
= case wire'Tag of
_ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self
instance P'.MessageAPI msg' (msg' -> SetXAttrResponseProto) SetXAttrResponseProto where
getVal m' f' = f' m'
instance P'.GPB SetXAttrResponseProto
instance P'.ReflectDescriptor SetXAttrResponseProto where
getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList [])
reflectDescriptorInfo _
= Prelude'.read
"DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.hdfs.SetXAttrResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"XAttrProtos\"], baseName = MName \"SetXAttrResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"XAttrProtos\",\"SetXAttrResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}"
instance P'.TextType SetXAttrResponseProto where
tellT = P'.tellSubMessage
getT = P'.getSubMessage
instance P'.TextMsg SetXAttrResponseProto where
textPut msg = Prelude'.return ()
textGet = Prelude'.return P'.defaultValue
|
alexbiehl/hoop
|
hadoop-protos/src/Hadoop/Protos/XAttrProtos/SetXAttrResponseProto.hs
|
Haskell
|
mit
| 2,810
|
-----------------------------------------------------------------------------
--
-- Module : SGC.Object.Internal.Generic
-- Copyright :
-- License : MIT
--
-- Maintainer :
-- Stability :
-- Portability :
--
-- |
--
-- {-# OPTIONS_GHC -fprint-explicit-kinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE GADTs #-}
module SGC.Object.Internal.Generic (
GenericObject(..), TMVar(..), GObject
, ObjectValuesList(..), ObjectKV(..)
, newGenericObject
, module Export
-- * Internal
, ObjectConstsCtx(..), ObjectVarsCtx(..), MkVarKeys, MkConstKeys -- TODO: hide on re-export
, gSubObject
-- , BuildSubObject(..)
) where
import SGC.Object.Definitions as Export
import SGC.Object.SomeObject as Export
import SGC.Object.Internal.TypeMap
import Data.Type.Bool
import Data.Proxy
import Data.Typeable -- (Typeable)
import Data.Maybe (fromJust)
import Control.Applicative ( (<|>) )
import TypeNum.TypeFunctions -- (type (++))
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
data GenericObject base (consts :: [*]) (vars :: [*]) = GenericObject{
objBase :: base,
objConsts :: TMap consts,
objVars :: TMap vars
}
type GObject base (consts :: [*]) (vars :: [*]) m =
GenericObject base (MkConstKeys consts) (MkVarKeys vars m)
type family MkConstKeys (cs :: [*]) :: [*] where
MkConstKeys '[] = '[]
MkConstKeys (c ': cs) = ContextMapKey ObjectConstsCtx c ': MkConstKeys cs
type family MkVarKeys (vs :: [*]) (m :: * -> *) :: [*] where
MkVarKeys '[] m = '[]
MkVarKeys (v ': vs) m = ContextMapKey (ObjectVarsCtx m) v ': MkVarKeys vs m
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
infixl 5 :::
infixl 6 ::$
newGenericObject :: (ObjectValuesList2TMap consts, ObjectValuesList2TMap vars) =>
base
-> ObjectValuesList ObjectConstant consts
-> ObjectValuesList ObjectVariable vars
-> GenericObject base consts vars
newGenericObject base cs vs = GenericObject base (tMap cs) (tMap vs)
-----------------------------------------------------------------------------
data ObjectValueAccessType = ObjectConstant | ObjectVariable
data ObjectKV k = (::$) k (KeyValue k)
data ObjectValuesList (t :: ObjectValueAccessType) (kl :: [*]) :: * where
ObjectVals :: ObjectValuesList ObjectConstant '[]
ObjectVars :: ObjectValuesList ObjectVariable '[]
(:::) :: ObjectValuesList t kl -> ObjectKV k -> ObjectValuesList t (k ': kl)
-----------------------------------------------------------------------------
class ObjectValuesList2TMap (kl :: [*]) where
tMap :: ObjectValuesList t kl -> TMap kl
instance ObjectValuesList2TMap '[] where tMap _ = tmEmpty
instance ( TMChange ks k ~ TypeMapGrowth, ObjectKey k
, TMKeyType k ~ TypeMapKeyUser
, ObjectValuesList2TMap ks
) =>
ObjectValuesList2TMap (k ': ks) where
tMap (t ::: (k ::$ v)) = tmUpdate (tMap t) k (TMSetValue v)
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
type instance HasConst' (GenericObject base consts vars) c =
TMContains consts (ContextMapKey ObjectConstsCtx c)
type instance HasVar' (GenericObject base consts vars) v m =
TMContains vars (ContextMapKey (ObjectVarsCtx m) v)
-----------------------------------------------------------------------------
data TMVar m v = TMVar {
tmVarRead :: m v
, tmVarWrite :: v -> m ()
, tmVarUpdate :: (v -> v) -> m ()
}
-----------------------------------------------------------------------------
newtype Id a = Id a
fromId (Id x) = x
instance Functor Id where fmap f = Id . f . fromId
instance Applicative Id where pure = Id
(<*>) f = Id . fromId f . fromId
instance Monad Id where (>>=) x = ($ fromId x)
-----------------------------------------------------------------------------
data ObjectConstsCtx = ObjectConstsCtx
data ObjectVarsCtx (m :: * -> *) = ObjectVarsCtx
instance (TypeMap tm) => TypeMapContext ObjectConstsCtx tm where
type CtxKeyValue ObjectConstsCtx = Id
instance (TypeMap tm, Typeable m) =>
TypeMapContext (ObjectVarsCtx m) tm where
type CtxKeyValue (ObjectVarsCtx m) = m
instance ( ObjectKey c, TypeMap cs
, HasConst (GenericObject base cs vs) c
) =>
ObjectConst (GenericObject base cs vs) c
where getConst v = fromId . flip (tmCtxGet ObjectConstsCtx) v . objConsts
instance ( ObjectKey v, Monad m, Typeable m, TypeMap vs
, HasVar (GenericObject base cs vs) v m
) =>
ObjectVar (GenericObject base cs vs) v m where
readVar = withVar tmVarRead
writeVar k v = withVar (`tmVarWrite` v) k
updateVar k f = withVar (`tmVarUpdate` f) k
withVar :: ( ObjectKey k, Typeable m, TypeMap vs ) =>
(TMVar m (KeyValue k) -> m b) -> k -> GenericObject base cs vs -> m b
withVar f k obj = f $ tmCtxGet ObjectVarsCtx (objVars obj) k
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
instance (TypeMap cs, TypeMap vs) =>
CreateSomeObject (GenericObject base cs vs) base where
someObject obj = SomeObject obj objBase
-----------------------------------------------------------------------------
instance (TypeMap cs) => ObjectMayHaveConst (GenericObject base cs vs) where
tryGetConst c = fmap fromId . flip (tmCtxFind ObjectConstsCtx) c . objConsts
instance (TypeMap cs, TypeMap vs, Monad m, Typeable m) =>
ObjectMayHave (GenericObject base cs vs) m where
tryReadVar = withVar' tmVarRead
tryWriteVar k v = withVar' (`tmVarWrite` v) k
tryUpdateVar k v = withVar' (`tmVarUpdate` v) k
tryReadValue k o = fmap return (tryGetConst k o) <|> tryReadVar k o
withVar' :: ( ObjectKey k, Typeable m, TypeMap vs ) =>
(TMVar m (KeyValue k) -> m b) -> k -> GenericObject base cs vs -> Maybe (m b)
withVar' f k obj = f <$> tmCtxFind ObjectVarsCtx (objVars obj) k
-----------------------------------------------------------------------------
-- subObject :: ( TypeSubMap (MkConstKeys cs'), TypeSubMap (MkVarKeys vs' m)
-- , TypeMap cs, TypeMap vs
-- ) =>
-- Proxy cs' -> Proxy vs' -> Proxy m
-- -> GenericObject base cs vs
-- -> Maybe (SomeObject NoCtx m '[ Has Consts (MkConstKeys cs')
-- , Has Vars (MkVarKeys vs' m)])
-- subObject cs' vs' m' obj = someObject <$> subObject' cs' vs' m' obj
-- cs <- subTMap (proxyMkConstKeys cs') $ objConsts obj
-- vs <- subTMap (proxyMkVarKeys m' vs') $ objVars obj
-- return . someObject $ GenericObject (objBase obj) cs vs
--
-- subObject' :: ( TypeSubMap (MkConstKeys cs'), TypeSubMap (MkVarKeys vs' m)
-- , TypeMap cs, TypeMap vs
-- , obj ~ GenericObject base (MkConstKeys cs') (MkVarKeys vs' m)
-- -- , MergeConstraints' ( ValueForEach Consts obj (MkConstKeys cs') m ++
-- -- ValueForEach Vars obj (MkVarKeys vs' m) m)
-- -- ()
-- ) =>
-- Proxy cs' -> Proxy vs' -> Proxy m
-- -> GenericObject base cs vs
-- -> Maybe obj
--
-- subObject' cs' vs' m' obj = undefined
gSubObject :: ( TypeSubMap (MkConstKeys cs')
, TypeSubMap (MkVarKeys vs' m)
, TypeMap cs, TypeMap vs
, obj ~ GenericObject base (MkConstKeys cs') (MkVarKeys vs' m)
-- , MergeConstraints' (ValueForEach Consts obj (MkConstKeys cs') m) ()
-- , MergeConstraints' (ValueForEach Vars obj (MkVarKeys vs' m) m) ()
, ObjectHas obj m Consts cs', ObjectHas obj m Vars vs'
) =>
Proxy cs' -> Proxy vs' -> Proxy m
-> GenericObject base cs vs
-> Maybe obj -- (GenericObject base (MkConstKeys cs') (MkVarKeys vs' m)) -- (GObject base cs' vs' m)
gSubObject cs' vs' m' obj = do
cs <- subTMap (proxyMkConstKeys cs') $ objConsts obj
vs <- subTMap (proxyMkVarKeys m' vs') $ objVars obj
return $ GenericObject (objBase obj) cs undefined
proxyMkConstKeys :: Proxy (xs :: [*]) -> Proxy (MkConstKeys xs)
proxyMkVarKeys :: Proxy (m :: * -> *) -> Proxy (xs :: [*]) -> Proxy (MkVarKeys xs m)
proxyMkConstKeys = const Proxy
proxyMkVarKeys _ = const Proxy
-----------------------------------------------------------------------------
-- class BuildSubObject (cs' :: [*]) (vs' :: [*]) (m :: * -> *) obj' obj where
-- buildSubObject :: Proxy cs' -> Proxy vs' -> Proxy m -> obj' -> Maybe obj
--
-- instance (ObjectHas obj m Consts cs', ObjectHas obj m Vars vs') =>
-- BuildSubObject cs' vs' m obj' obj where
class BuildSomeObject baseC (has :: [(ObjectValueType, [*])]) (m :: * -> *) where
buildSomeObject :: ( baseC base, TypeMap cs, TypeMap vs ) =>
GenericObject base cs vs
-> Proxy has -> Proxy m
-> SomeObject baseC m has'
-> Maybe (SomeObject baseC m (has' ++ has))
-- instance BuildSomeObject baseC '[] m where
-- buildSomeObject obj _ _ = Just $ someObject obj
--
-- instance BuildSomeObject baseC ('(t, ks) ': hasMore) m where
--
--
-- class BuildSomeObject' baseC (t :: ObjectValueType) (ks :: [*]) (m :: * -> *) where
-- buildSomeObject' :: () =>
-- GenericObject base cs vs
-- -> t -> Proxy ks -> Proxy m
-- -> Maybe (SomeObject baseC m has)
-- uniteSomeObjects :: SomeObject baseC m x -> SomeObject baseC m y
-- -> SomeObject baseC m (x ++ y)
-- uniteSomeObjects (SomeObject x get) (SomeObject y _) =
-- SomeObject (fromJust $ cast x) get
-----------------------------------------------------------------------------
|
fehu/hsgc
|
SGC/Object/Internal/Generic.hs
|
Haskell
|
mit
| 10,150
|
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-|
Handles the "Language.LSP.Types.TextDocumentDidChange" \/
"Language.LSP.Types.TextDocumentDidOpen" \/
"Language.LSP.Types.TextDocumentDidClose" messages to keep an in-memory
`filesystem` of the current client workspace. The server can access and edit
files in the client workspace by operating on the "VFS" in "LspFuncs".
-}
module Language.LSP.VFS
(
VFS(..)
, VirtualFile(..)
, virtualFileText
, virtualFileVersion
-- * Managing the VFS
, initVFS
, openVFS
, changeFromClientVFS
, changeFromServerVFS
, persistFileVFS
, closeVFS
, updateVFS
-- * manipulating the file contents
, rangeLinesFromVfs
, PosPrefixInfo(..)
, getCompletionPrefix
-- * for tests
, applyChanges
, applyChange
, changeChars
) where
import Control.Lens hiding ( parts )
import Control.Monad
import Data.Char (isUpper, isAlphaNum)
import Data.Text ( Text )
import qualified Data.Text as T
import Data.List
import Data.Ord
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Rope.UTF16 ( Rope )
import qualified Data.Rope.UTF16 as Rope
import qualified Language.LSP.Types as J
import qualified Language.LSP.Types.Lens as J
import System.FilePath
import Data.Hashable
import System.Directory
import System.IO
import System.IO.Temp
import System.Log.Logger
-- ---------------------------------------------------------------------
{-# ANN module ("hlint: ignore Eta reduce" :: String) #-}
{-# ANN module ("hlint: ignore Redundant do" :: String) #-}
-- ---------------------------------------------------------------------
data VirtualFile =
VirtualFile {
_lsp_version :: !Int -- ^ The LSP version of the document
, _file_version :: !Int -- ^ This number is only incremented whilst the file
-- remains in the map.
, _text :: !Rope -- ^ The full contents of the document
} deriving (Show)
type VFSMap = Map.Map J.NormalizedUri VirtualFile
data VFS = VFS { vfsMap :: !(Map.Map J.NormalizedUri VirtualFile)
, vfsTempDir :: !FilePath -- ^ This is where all the temporary files will be written to
} deriving Show
---
virtualFileText :: VirtualFile -> Text
virtualFileText vf = Rope.toText (_text vf)
virtualFileVersion :: VirtualFile -> Int
virtualFileVersion vf = _lsp_version vf
---
initVFS :: (VFS -> IO r) -> IO r
initVFS k = withSystemTempDirectory "haskell-lsp" $ \temp_dir -> k (VFS mempty temp_dir)
-- ---------------------------------------------------------------------
-- | Applies the changes from a 'J.DidOpenTextDocument' to the 'VFS'
openVFS :: VFS -> J.Message 'J.TextDocumentDidOpen -> (VFS, [String])
openVFS vfs (J.NotificationMessage _ _ params) =
let J.DidOpenTextDocumentParams
(J.TextDocumentItem uri _ version text) = params
in (updateVFS (Map.insert (J.toNormalizedUri uri) (VirtualFile version 0 (Rope.fromText text))) vfs
, [])
-- ---------------------------------------------------------------------
-- ^ Applies a 'DidChangeTextDocumentNotification' to the 'VFS'
changeFromClientVFS :: VFS -> J.Message 'J.TextDocumentDidChange -> (VFS,[String])
changeFromClientVFS vfs (J.NotificationMessage _ _ params) =
let
J.DidChangeTextDocumentParams vid (J.List changes) = params
J.VersionedTextDocumentIdentifier (J.toNormalizedUri -> uri) version = vid
in
case Map.lookup uri (vfsMap vfs) of
Just (VirtualFile _ file_ver str) ->
let str' = applyChanges str changes
-- the client shouldn't be sending over a null version, only the server.
in (updateVFS (Map.insert uri (VirtualFile (fromMaybe 0 version) (file_ver + 1) str')) vfs, [])
Nothing ->
-- logs $ "haskell-lsp:changeVfs:can't find uri:" ++ show uri
-- return vfs
(vfs, ["haskell-lsp:changeVfs:can't find uri:" ++ show uri])
updateVFS :: (VFSMap -> VFSMap) -> VFS -> VFS
updateVFS f vfs@VFS{vfsMap} = vfs { vfsMap = f vfsMap }
-- ---------------------------------------------------------------------
applyCreateFile :: J.CreateFile -> VFS -> VFS
applyCreateFile (J.CreateFile uri options _ann) =
updateVFS $ Map.insertWith
(\ new old -> if shouldOverwrite then new else old)
(J.toNormalizedUri uri)
(VirtualFile 0 0 (Rope.fromText ""))
where
shouldOverwrite :: Bool
shouldOverwrite = case options of
Nothing -> False -- default
Just (J.CreateFileOptions Nothing Nothing ) -> False -- default
Just (J.CreateFileOptions Nothing (Just True) ) -> False -- `ignoreIfExists` is True
Just (J.CreateFileOptions Nothing (Just False)) -> True -- `ignoreIfExists` is False
Just (J.CreateFileOptions (Just True) Nothing ) -> True -- `overwrite` is True
Just (J.CreateFileOptions (Just True) (Just True) ) -> True -- `overwrite` wins over `ignoreIfExists`
Just (J.CreateFileOptions (Just True) (Just False)) -> True -- `overwrite` is True
Just (J.CreateFileOptions (Just False) Nothing ) -> False -- `overwrite` is False
Just (J.CreateFileOptions (Just False) (Just True) ) -> False -- `overwrite` is False
Just (J.CreateFileOptions (Just False) (Just False)) -> False -- `overwrite` wins over `ignoreIfExists`
applyRenameFile :: J.RenameFile -> VFS -> VFS
applyRenameFile (J.RenameFile oldUri' newUri' options _ann) vfs =
let oldUri = J.toNormalizedUri oldUri'
newUri = J.toNormalizedUri newUri'
in case Map.lookup oldUri (vfsMap vfs) of
-- nothing to rename
Nothing -> vfs
Just file -> case Map.lookup newUri (vfsMap vfs) of
-- the target does not exist, just move over
Nothing -> updateVFS (Map.insert newUri file . Map.delete oldUri) vfs
Just _ -> if shouldOverwrite
then updateVFS (Map.insert newUri file . Map.delete oldUri) vfs
else vfs
where
shouldOverwrite :: Bool
shouldOverwrite = case options of
Nothing -> False -- default
Just (J.RenameFileOptions Nothing Nothing ) -> False -- default
Just (J.RenameFileOptions Nothing (Just True) ) -> False -- `ignoreIfExists` is True
Just (J.RenameFileOptions Nothing (Just False)) -> True -- `ignoreIfExists` is False
Just (J.RenameFileOptions (Just True) Nothing ) -> True -- `overwrite` is True
Just (J.RenameFileOptions (Just True) (Just True) ) -> True -- `overwrite` wins over `ignoreIfExists`
Just (J.RenameFileOptions (Just True) (Just False)) -> True -- `overwrite` is True
Just (J.RenameFileOptions (Just False) Nothing ) -> False -- `overwrite` is False
Just (J.RenameFileOptions (Just False) (Just True) ) -> False -- `overwrite` is False
Just (J.RenameFileOptions (Just False) (Just False)) -> False -- `overwrite` wins over `ignoreIfExists`
-- NOTE: we are ignoring the `recursive` option here because we don't know which file is a directory
applyDeleteFile :: J.DeleteFile -> VFS -> VFS
applyDeleteFile (J.DeleteFile uri _options _ann) =
updateVFS $ Map.delete (J.toNormalizedUri uri)
applyTextDocumentEdit :: J.TextDocumentEdit -> VFS -> IO VFS
applyTextDocumentEdit (J.TextDocumentEdit vid (J.List edits)) vfs = do
-- all edits are supposed to be applied at once
-- so apply from bottom up so they don't affect others
let sortedEdits = sortOn (Down . editRange) edits
changeEvents = map editToChangeEvent sortedEdits
ps = J.DidChangeTextDocumentParams vid (J.List changeEvents)
notif = J.NotificationMessage "" J.STextDocumentDidChange ps
let (vfs',ls) = changeFromClientVFS vfs notif
mapM_ (debugM "haskell-lsp.applyTextDocumentEdit") ls
return vfs'
where
editRange :: J.TextEdit J.|? J.AnnotatedTextEdit -> J.Range
editRange (J.InR e) = e ^. J.range
editRange (J.InL e) = e ^. J.range
editToChangeEvent :: J.TextEdit J.|? J.AnnotatedTextEdit -> J.TextDocumentContentChangeEvent
editToChangeEvent (J.InR e) = J.TextDocumentContentChangeEvent (Just $ e ^. J.range) Nothing (e ^. J.newText)
editToChangeEvent (J.InL e) = J.TextDocumentContentChangeEvent (Just $ e ^. J.range) Nothing (e ^. J.newText)
applyDocumentChange :: J.DocumentChange -> VFS -> IO VFS
applyDocumentChange (J.InL change) = applyTextDocumentEdit change
applyDocumentChange (J.InR (J.InL change)) = return . applyCreateFile change
applyDocumentChange (J.InR (J.InR (J.InL change))) = return . applyRenameFile change
applyDocumentChange (J.InR (J.InR (J.InR change))) = return . applyDeleteFile change
-- ^ Applies the changes from a 'ApplyWorkspaceEditRequest' to the 'VFS'
changeFromServerVFS :: VFS -> J.Message 'J.WorkspaceApplyEdit -> IO VFS
changeFromServerVFS initVfs (J.RequestMessage _ _ _ params) = do
let J.ApplyWorkspaceEditParams _label edit = params
J.WorkspaceEdit mChanges mDocChanges _anns = edit
case mDocChanges of
Just (J.List docChanges) -> applyDocumentChanges docChanges
Nothing -> case mChanges of
Just cs -> applyDocumentChanges $ map J.InL $ HashMap.foldlWithKey' changeToTextDocumentEdit [] cs
Nothing -> do
debugM "haskell-lsp.changeVfs" "No changes"
return initVfs
where
changeToTextDocumentEdit acc uri edits =
acc ++ [J.TextDocumentEdit (J.VersionedTextDocumentIdentifier uri (Just 0)) (fmap J.InL edits)]
applyDocumentChanges :: [J.DocumentChange] -> IO VFS
applyDocumentChanges = foldM (flip applyDocumentChange) initVfs . sortOn project
-- for sorting [DocumentChange]
project :: J.DocumentChange -> J.TextDocumentVersion -- type TextDocumentVersion = Maybe Int
project (J.InL textDocumentEdit) = textDocumentEdit ^. J.textDocument . J.version
project _ = Nothing
-- ---------------------------------------------------------------------
virtualFileName :: FilePath -> J.NormalizedUri -> VirtualFile -> FilePath
virtualFileName prefix uri (VirtualFile _ file_ver _) =
let uri_raw = J.fromNormalizedUri uri
basename = maybe "" takeFileName (J.uriToFilePath uri_raw)
-- Given a length and a version number, pad the version number to
-- the given n. Does nothing if the version number string is longer
-- than the given length.
padLeft :: Int -> Int -> String
padLeft n num =
let numString = show num
in replicate (n - length numString) '0' ++ numString
in prefix </> basename ++ "-" ++ padLeft 5 file_ver ++ "-" ++ show (hash uri_raw) ++ ".hs"
-- | Write a virtual file to a temporary file if it exists in the VFS.
persistFileVFS :: VFS -> J.NormalizedUri -> Maybe (FilePath, IO ())
persistFileVFS vfs uri =
case Map.lookup uri (vfsMap vfs) of
Nothing -> Nothing
Just vf ->
let tfn = virtualFileName (vfsTempDir vfs) uri vf
action = do
exists <- doesFileExist tfn
unless exists $ do
let contents = Rope.toString (_text vf)
writeRaw h = do
-- We honour original file line endings
hSetNewlineMode h noNewlineTranslation
hSetEncoding h utf8
hPutStr h contents
debugM "haskell-lsp.persistFileVFS" $ "Writing virtual file: "
++ "uri = " ++ show uri ++ ", virtual file = " ++ show tfn
withFile tfn WriteMode writeRaw
in Just (tfn, action)
-- ---------------------------------------------------------------------
closeVFS :: VFS -> J.Message 'J.TextDocumentDidClose -> (VFS, [String])
closeVFS vfs (J.NotificationMessage _ _ params) =
let J.DidCloseTextDocumentParams (J.TextDocumentIdentifier uri) = params
in (updateVFS (Map.delete (J.toNormalizedUri uri)) vfs,["Closed: " ++ show uri])
-- ---------------------------------------------------------------------
{-
data TextDocumentContentChangeEvent =
TextDocumentContentChangeEvent
{ _range :: Maybe Range
, _rangeLength :: Maybe Int
, _text :: String
} deriving (Read,Show,Eq)
-}
-- | Apply the list of changes.
-- Changes should be applied in the order that they are
-- received from the client.
applyChanges :: Rope -> [J.TextDocumentContentChangeEvent] -> Rope
applyChanges = foldl' applyChange
-- ---------------------------------------------------------------------
applyChange :: Rope -> J.TextDocumentContentChangeEvent -> Rope
applyChange _ (J.TextDocumentContentChangeEvent Nothing Nothing str)
= Rope.fromText str
applyChange str (J.TextDocumentContentChangeEvent (Just (J.Range (J.Position sl sc) _to)) (Just len) txt)
= changeChars str start len txt
where
start = Rope.rowColumnCodeUnits (Rope.RowColumn sl sc) str
applyChange str (J.TextDocumentContentChangeEvent (Just (J.Range (J.Position sl sc) (J.Position el ec))) Nothing txt)
= changeChars str start len txt
where
start = Rope.rowColumnCodeUnits (Rope.RowColumn sl sc) str
end = Rope.rowColumnCodeUnits (Rope.RowColumn el ec) str
len = end - start
applyChange str (J.TextDocumentContentChangeEvent Nothing (Just _) _txt)
= str
-- ---------------------------------------------------------------------
changeChars :: Rope -> Int -> Int -> Text -> Rope
changeChars str start len new = mconcat [before, Rope.fromText new, after']
where
(before, after) = Rope.splitAt start str
after' = Rope.drop len after
-- ---------------------------------------------------------------------
-- TODO:AZ:move this to somewhere sane
-- | Describes the line at the current cursor position
data PosPrefixInfo = PosPrefixInfo
{ fullLine :: !T.Text
-- ^ The full contents of the line the cursor is at
, prefixModule :: !T.Text
-- ^ If any, the module name that was typed right before the cursor position.
-- For example, if the user has typed "Data.Maybe.from", then this property
-- will be "Data.Maybe"
, prefixText :: !T.Text
-- ^ The word right before the cursor position, after removing the module part.
-- For example if the user has typed "Data.Maybe.from",
-- then this property will be "from"
, cursorPos :: !J.Position
-- ^ The cursor position
} deriving (Show,Eq)
getCompletionPrefix :: (Monad m) => J.Position -> VirtualFile -> m (Maybe PosPrefixInfo)
getCompletionPrefix pos@(J.Position l c) (VirtualFile _ _ ropetext) =
return $ Just $ fromMaybe (PosPrefixInfo "" "" "" pos) $ do -- Maybe monad
let headMaybe [] = Nothing
headMaybe (x:_) = Just x
lastMaybe [] = Nothing
lastMaybe xs = Just $ last xs
curLine <- headMaybe $ T.lines $ Rope.toText
$ fst $ Rope.splitAtLine 1 $ snd $ Rope.splitAtLine l ropetext
let beforePos = T.take c curLine
curWord <-
if | T.null beforePos -> Just ""
| T.last beforePos == ' ' -> Just "" -- don't count abc as the curword in 'abc '
| otherwise -> lastMaybe (T.words beforePos)
let parts = T.split (=='.')
$ T.takeWhileEnd (\x -> isAlphaNum x || x `elem` ("._'"::String)) curWord
case reverse parts of
[] -> Nothing
(x:xs) -> do
let modParts = dropWhile (not . isUpper . T.head)
$ reverse $ filter (not .T.null) xs
modName = T.intercalate "." modParts
return $ PosPrefixInfo curLine modName x pos
-- ---------------------------------------------------------------------
rangeLinesFromVfs :: VirtualFile -> J.Range -> T.Text
rangeLinesFromVfs (VirtualFile _ _ ropetext) (J.Range (J.Position lf _cf) (J.Position lt _ct)) = r
where
(_ ,s1) = Rope.splitAtLine lf ropetext
(s2, _) = Rope.splitAtLine (lt - lf) s1
r = Rope.toText s2
-- ---------------------------------------------------------------------
|
alanz/haskell-lsp
|
lsp-types/src/Language/LSP/VFS.hs
|
Haskell
|
mit
| 16,541
|
{- Copyright (C) 2014 Calvin Beck
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
{-# LANGUAGE OverloadedStrings #-}
module SurvivalPlot.Parser (parseDistributions, parseIntervals, Curve (..), TestInfo (..)) where
import Control.Applicative
import Data.Attoparsec.Text
data Curve = Curve { curvePoints :: [Double]
, tValue :: (Double,Double) -- Not really sure what to do for OUT_OF_RANGE
}
deriving (Show)
data TestInfo = TestInfo { concordance :: Double
, l1Loss :: Double
, l2Loss :: Double
, raeLoss :: Double
, l1LogLoss :: Double
, l2LogLoss :: Double
, logLikelihoodLoss :: Double
}
-- | MTLR Model data type
data Model = Model { numTimePoints :: Integer -- ^ Number of time points in the interval.
, timePoints :: [Double] -- ^ Time points in the interval.
, rForSomeReason :: Integer -- ^ I have no idea what is this even?
, dimension :: Integer -- ^ Number of features in the model.
, features :: [(Integer, Double)] -- ^ Feature, value pairs
}
-- | Parse a time intervals file.
parseIntervals :: Parser [Double]
parseIntervals = (many1 (double <* endOfLine)) <|> (do model <- parseModel; return (timePoints model))
-- | Parse an MTLR test distribution.
parseDistributions :: Parser ([Curve], TestInfo)
parseDistributions = do curves <- parseCurves
info <- parseTestInfo
endOfInput
return (curves, info)
-- | Parse PSSP model.
parseModel :: Parser Model
parseModel = do string "m:"
tps <- decimal
endOfLine'
timeInterval <- parseTimeInterval
endOfLine'
string "r:"
r <- decimal
endOfLine'
string "DIM:"
dim <- decimal
endOfLine'
feats <- many parseKeyWeight
many endOfLine'
endOfInput <?> "End of input not reached. Probably some bad padding at the end, or bad features."
return (Model tps timeInterval r dim feats)
-- | Parse the comma separated time points for the interval.
parseTimeInterval :: Parser [Double]
parseTimeInterval =
do point <- double
others <- (do char ',' *> parseTimeInterval) <|> (return [])
return (point : others)
-- | Parse a key:double pair for model weights.
parseKeyWeight :: Parser (Integer, Double)
parseKeyWeight = do key <- decimal
char ':'
value <- double
endOfLine'
return (key, value)
-- | Newline parser to handle all sorts of horrible.
endOfLine' :: Parser ()
endOfLine' = endOfLine <|> (char '\r' *> return ())
-- | Parse MTLR test error information.
parseTestInfo :: Parser TestInfo
parseTestInfo = do string "#concordance index: "
conc <- doubleInf
endOfLine
string "#avg l1-loss: "
l1 <- doubleInf
endOfLine
string "#avg l2-loss: "
l2 <- doubleInf
endOfLine
string "#avg rae-loss: "
rae <- doubleInf
endOfLine
string "#avg l1-log-loss: "
l1Log <- doubleInf
endOfLine
string "#avg l2-log-loss: "
l2Log <- doubleInf
endOfLine
string "#avg log-likelihood loss: "
logLikelihood <- doubleInf
endOfLine
return (TestInfo conc l1 l2 rae l1Log l2Log logLikelihood)
doubleInf :: Parser Double
doubleInf = double <|> (string "inf" *> (return 0))
-- | Parse all curves in a file.
parseCurves :: Parser [Curve]
parseCurves = many1 parseCurveLine
-- | Parse a single curve.
parseCurveLine :: Parser Curve
parseCurveLine = do points <- parsePoints
t <- parseTValue
return (Curve (drop 2 points) t)
-- | Get all points for a curve.
parsePoints :: Parser [Double]
parsePoints = do point <- double
otherPoints <- (char ',' *> skipSpace *> parsePoints) <|> return []
skipSpace
return (point:otherPoints)
-- | Parse the weird scary "t" values.
parseTValue :: Parser (Double,Double)
parseTValue = do string ", t:"
t1 <- double <|> (string "OUT_OF_RANGE" *> return 0)
char ':'
t2 <- double <|> (string "OUT_OF_RANGE" *> return 0)
endOfLine
return (t1, t2)
|
Chobbes/SurvivalPlot
|
SurvivalPlot/Parser.hs
|
Haskell
|
mit
| 6,096
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Web.Scotty
-- Bare
main :: IO ()
main = scotty 3000 $ do
get "/" $ text "Hello Haskeller on Heroku with Stackage!"
|
yogeshsajanikar/heroku-haskell-stackage-tutorial
|
src/Main.hs
|
Haskell
|
mit
| 180
|
module Main where
import qualified Data.Map as M
import Morse
import Test.QuickCheck
allowedChars :: String
allowedChars = M.keys letterToMorse
allowedMorse :: [Morse]
allowedMorse = M.elems letterToMorse
charGen :: Gen Char
charGen = elements allowedChars
morseGen :: Gen Morse
morseGen = elements allowedMorse
prop_thereAndBackAgain :: Property
prop_thereAndBackAgain =
forAll charGen
(\c -> (charToMorse c >>= morseToChar) == Just c)
main :: IO ()
main = quickCheck prop_thereAndBackAgain
|
deciduously/Haskell-First-Principles-Exercises
|
4-Getting real/14-Testing/code/morse/tests/tests.hs
|
Haskell
|
mit
| 536
|
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module JsonSettings where
import Data.Yaml
import Data.Aeson
import qualified Data.ByteString.Lazy as BS
import Data.Functor
jsonSettingsMain :: IO ()
jsonSettingsMain = do
s <- either (error.show) id <$> decodeFileEither "gipeda.yaml"
let o = object [ "settings" .= (s :: Object) ]
BS.putStr (Data.Aeson.encode o)
|
nomeata/gipeda
|
src/JsonSettings.hs
|
Haskell
|
mit
| 382
|
module GHCJS.DOM.SQLError (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/SQLError.hs
|
Haskell
|
mit
| 38
|
module Cenary.Crypto.Keccak where
import Crypto.Hash (Digest, Keccak_256, hash)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Monoid ((<>))
import Text.Read (readMaybe)
keccak256 :: (Read b, Num b) => String -> Maybe b
keccak256 = readMaybe
. ("0x" <>)
. take 8
. show
. hash'
. BS8.pack
where
-- | Let's help out the compiler a little
hash' :: BS.ByteString -> Digest Keccak_256
hash' = hash
|
yigitozkavci/ivy
|
src/Cenary/Crypto/Keccak.hs
|
Haskell
|
mit
| 540
|
module Main where
import Prelude hiding (getContents, putStr)
import Data.Fortran.Unformatted (fromUnformatted)
import Data.ByteString.Lazy (getContents, putStr)
import Control.Monad (liftM)
main :: IO ()
main = liftM fromUnformatted getContents >>= putStr
|
albertov/funformatted
|
Main.hs
|
Haskell
|
mit
| 259
|
data Expr = Val Int | Div
eval :: Expr -> Int
eval (Val n) = n
eval (`Div` x y) = eval x / eval y
safediv :: Int -> Int -> Maybe Int
safediv n m = if m == 0 then
Nothing
else
Just (n / m)
|
ChristopherElliott/Portfolio
|
haskell/src/utility.hs
|
Haskell
|
mit
| 249
|
{-# LANGUAGE ViewPatterns #-}
module Data.MemoizingTable where
{--
Captures the idea that you get information on your data sets incrementally. So
you start with the known lookups, add the ones you don't know yet, refine those,
then add the refined lookups to the known sets.
--}
import Prelude hiding (init)
import Control.Arrow ((&&&))
import Control.Monad.State
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Tuple (swap)
-- Our memoizing table, partitioning what we know against what we do know
data MemoizingTable a b =
MT { fromTable :: Map a b, readIndex :: Map b a, newValues :: Set b }
deriving Show
type MemoizingState m a key val =
StateT (MemoizingTable key val, Map key [val]) m a
-- creates a new memoizing table
init :: Ord a => Ord b => (Map a b, Map b a) -> MemoizingTable a b
init = flip (uncurry MT) Set.empty
-- partitions a datum: do we know it? If not, add it to new information
-- for later processing
triage :: Ord a => Ord b => b -> MemoizingTable a b -> MemoizingTable a b
triage k (MT mapi mapk n00b) =
MT mapi mapk ((if containsKey k mapk then id else Set.insert k) n00b)
where containsKey k = Set.member k . Map.keysSet
-- triaging with state
type MemoizingS m a b c = StateT (MemoizingTable a b, Map a [b]) m c
triageM :: Monad m => Ord a => Ord b => a -> [b] -> MemoizingS m a b ()
triageM idx vals = get >>= \(mt0, reserve) ->
put ((foldr triage mt0 &&& flip (Map.insert idx) reserve) vals)
-- When we get indices for the new information, we update the memoizing table
update :: Ord a => Ord b => [(a,b)] -> MemoizingTable a b -> MemoizingTable a b
update (bifurcate -> (mi, mk)) (MT mi' mk' _) =
init (merge mi mi', merge mk mk')
where merge m1 = Map.fromList . (Map.toList m1 ++) . Map.toList
bifurcate :: Ord a => Ord b => [(a,b)] -> (Map a b, Map b a)
bifurcate = (Map.fromList &&& Map.fromList . map swap)
-- To start of a memoizing table from a single list:
start :: Ord a => Ord b => [(a, b)] -> MemoizingTable a b
start = init . bifurcate
|
geophf/1HaskellADay
|
exercises/HAD/Data/MemoizingTable.hs
|
Haskell
|
mit
| 2,106
|
module Render.Setup where
import Data.IORef ( IORef, newIORef )
import Foreign ( newArray )
import Graphics.UI.GLUT hiding (Sphere, Plane)
import Geometry.Object
import Render.Antialias
data State = State { zoomFactor :: IORef GLfloat }
type Image = PixelData (Color3 GLfloat)
fstSphere :: Surface
fstSphere = Sphere 1 (-4, 0, -7) (Material (0.2, 0, 0) (1, 0, 0) (0, 0, 0) 0 0)
sndSphere :: Surface
sndSphere = Sphere 2 (0, 0, -7) (Material (0, 0.2, 0) (0, 0.5, 0) (0.5, 0.5, 0.5) 32 0)
thdSphere :: Surface
thdSphere = Sphere 1 (4, 0, -7) (Material (0, 0, 0.2) (0, 0, 1) (0, 0, 0) 0 0.8)
plane :: Surface
plane = Plane (0, 1, 0) (0, -2, 0) (Material (0.2, 0.2, 0.2) (1, 1, 1) (0, 0, 0) 0 0.5)
scene :: Scene
scene = [fstSphere, sndSphere, thdSphere, plane]
makeState :: IO State
makeState = do
z <- newIORef 1
return $ State { zoomFactor = z }
sceneImageSize :: Size
sceneImageSize = Size 512 512
display :: Image -> DisplayCallback
display pixelData = do
clear [ ColorBuffer ]
-- resolve overloading, not needed in "real" programs
let rasterPos2i = rasterPos :: Vertex2 GLint -> IO ()
rasterPos2i (Vertex2 0 0)
drawPixels sceneImageSize pixelData
flush
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D 0 (fromIntegral w) 0 (fromIntegral h)
matrixMode $= Modelview 0
loadIdentity
rayTrace :: Size -> GLsizei -> IO Image
rayTrace (Size w h) n =
fmap (PixelData RGB Float) $
newArray [ c |
i <- [ 0 .. w - 1 ],
j <- [ 0 .. h - 1 ],
let c = convertToFloatColor $ boxFilter scene (fromIntegral j) (fromIntegral i) ]
createShadedImage :: IO Image
createShadedImage = do
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
rowAlignment Unpack $= 1
rayTrace sceneImageSize 0x8
|
dongy7/raytracer
|
src/Render/Setup.hs
|
Haskell
|
mit
| 1,970
|
module Search
( search
, searchComplex
, searchProxim
) where
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import qualified Postings as PS
import Control.Monad.Free
import Data.Maybe (fromMaybe)
import Data.Text.Encoding (decodeUtf8)
import Index
import Query
testIndex :: InMemoryIndex
testIndex = addTerm (T.pack "Name")
(T.pack "teresa") 1 [0,2]
(addTerm (T.pack "Name")
(T.pack "tony") 1 [1]
(addTerm (T.pack "Name")
(T.pack "casa") 1 [3] empty))
toText :: B.ByteString -> T.Text
toText = decodeUtf8
--------------------------------------------------------------------------------
-- Query interpreters
--------------------------------------------------------------------------------
runQuery :: Query QTerm -> InMemoryIndex -> PS.Postings
runQuery (Free (And e1 e2)) imi = PS.intersection (runQuery e1 imi) (runQuery e2 imi)
runQuery (Free (Or e1 e2)) imi = PS.union (runQuery e1 imi) (runQuery e2 imi)
runQuery (Free (Exp (QT fname x))) imi = fromMaybe PS.empty (Index.lookup (toText fname) (toText x) imi)
runQuery (Free (Wild (QT fname x))) imi = fromMaybe PS.empty (wildcard (toText fname) (toText x) imi)
runQuery (Free (Not e1)) imi = runQuery e1 imi
runQuery (Pure ()) _ = PS.empty
runProximityQuery :: Int -> Query QTerm -> InMemoryIndex -> PS.Postings
runProximityQuery n (Free (And e1 e2)) imi = PS.separatedBy n (runProximityQuery n e1 imi)
(runProximityQuery n e2 imi)
runProximityQuery n (Free (Or e1 e2)) imi = PS.union (runProximityQuery n e1 imi)
(runProximityQuery n e2 imi)
runProximityQuery _ (Free (Exp (QT fname x))) imi = fromMaybe PS.empty (Index.lookup (toText fname) (toText x) imi)
runProximityQuery _ (Free (Wild (QT fname x))) imi = fromMaybe PS.empty (wildcard (toText fname) (toText x) imi)
runProximityQuery n (Free (Not e1)) imi = runProximityQuery n e1 imi
runProximityQuery _ (Pure ()) _ = PS.empty
--------------------------------------------------------------------------------
-- Search API
--------------------------------------------------------------------------------
search :: InMemoryIndex -> B.ByteString -> B.ByteString -> Either String PS.Postings
search imi defField bs = runSimpleQParser defField bs >>= (\q -> return $ runQuery q imi)
searchComplex :: InMemoryIndex -> B.ByteString -> B.ByteString -> Either String PS.Postings
searchComplex imi defField bs = runComplexQParser defField bs >>= (\q -> return $ runQuery q imi)
searchProxim :: Int -> InMemoryIndex -> B.ByteString -> B.ByteString -> Either String PS.Postings
searchProxim d imi defField bs = runSimpleQParser defField bs >>= (\q -> return $ runProximityQuery d q imi)
|
jagg/search
|
src/Search.hs
|
Haskell
|
apache-2.0
| 2,975
|
{-# LANGUAGE OverloadedStrings #-}
module Forms.Post where
import Model.CoreTypes
import Data.Time
import Text.Blaze.Html (Html)
import Text.Digestive hiding (Post)
import Text.Digestive.Bootstrap
postForm :: Monad m => UTCTime -> Form Html m Post
postForm now =
Post <$> "title" .: text Nothing
<*> "date" .: stringRead "Couldn't parse as UTCTime" (Just now)
<*> "content" .: text Nothing
postFormSpec :: FormMeta
postFormSpec =
FormMeta
{ fm_method = POST
, fm_target = "/write"
, fm_elements =
[ FormElement "title" (Just "Title") InputText
, FormElement "date" (Just "Date") InputText
, FormElement "content" (Just "Content") $ InputTextArea (Just 30) (Just 10)
]
, fm_submitText = "Publish"
}
|
julienchurch/julienchurch.com
|
app/Forms/Post.hs
|
Haskell
|
apache-2.0
| 780
|
module Example.SingleCounter where
import Control.Monad
import Control.Monad.Crdt
import Control.Monad.Reader
import Data.Crdt.Counter
action :: Crdt Counter ()
action = do
Counter c <- ask
when (c < 10) $ do
update $ CounterUpdate 1
action
main = putStrLn $ unlines $ fmap (show . runCrdt action . Counter) [0..12]
|
edofic/crdt
|
src/Example/SingleCounter.hs
|
Haskell
|
apache-2.0
| 331
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Tersus.Cluster.TersusService where
-- | TersusService
-- Contains all the functions and datatypes that control a server side Tersus Application
-- Author: Ernesto Rodriguez
import Prelude
import Control.Distributed.Process
import Control.Monad.IO.Class
import Control.Monad (forever)
import Data.Typeable.Internal (Typeable)
import Tersus.Global
import Control.Monad.Maybe
import Control.Exception (Exception,throw)
import Data.Time.Clock (getCurrentTime,UTCTime)
import Database.Redis hiding (msgChannel)
import Data.Binary (Binary)
-- tersus
import Tersus.Cluster.Types
import Tersus.Cluster.MessageFrontend (broadcastNotificationsProcess)
import Tersus.DataTypes
-- | Exceptions that can result from server side applications
-- | NoStateException: raised if an application that dosen't use acid state tries to access it's acid state
data TersusServiceExceptions = NoStateException deriving (Show,Typeable)
instance Exception TersusServiceExceptions
-- | Represents a tersus server side app.
data TersusServerApp = TersusServerApp
{
-- | The Tersus Application that represents this app. This is here for messaging purposes
-- so normal tersus apps can communicate with it as if it were a tersus app.
applicationRep :: TApplication,
-- | The user that is `running` the app. It's just here because it's easier to integrate
-- it to the current app implementation
userRep :: User,
-- | The function that is executed every time a message is received by the application
msgFun :: TMessage -> TersusServiceM (),
-- | A optional function that is executed every time a message delivery status is
-- obtained
ackwFun :: Maybe (MessageResultEnvelope -> TersusServiceM ()),
-- | Function that is called when the session of a AppInstance expires
expireFun :: Maybe ([AppInstance] -> TersusServiceM ())
}
-- | The datatype that contains all necesary data to run a Tersus Server application
-- this datatype also represents the `state` of the application.
data TersusService = TersusService
{
-- | The port to receive messages and the port other applications use to
-- to send messages to this app
msgChannel :: MessagingPorts,
-- | The channel where message acknowlegements are received
ackwChannel :: AcknowledgementPorts,
-- | The redis connection for the database used by this application
serviceConnection :: Connection,
-- | The list of Tersus servers
tersusNode :: TersusClusterList,
-- | The Tersus Application that represents this app. This is here for messaging purposes
-- so normal tersus apps can communicate with it as if it were a tersus app.
serviceApplication :: TApplication,
-- | The channels that contain the send ports of the tersus applications
serviceSendChannels :: SendAddressTable,
-- | The channels that contain the receive ports of the tersus applications
serviceRecvChannels :: RecvAddressTable
}
-- | The monad on which a server side application runs. It passes a TersusService datatype
-- to represent the state and eventually collapses to a Process since they are intended to
-- be run with cloud haskell
data TersusServiceM a = TersusServiceM {runTersusServiceM :: TersusService -> Process (TersusService,a)}
instance Monad TersusServiceM where
-- | Apply runTersusServiceM to the first argument which is a monad to obtain a function that
-- goes from TersusService -> Process. Apply this function to the TersusService that will
-- be provided as ts and pind the resulting Process to the new state and the result of the
-- monad. Apply k to the result to get a new TersusServiceM and use the runTersusServiceM
-- function applied to the result of applying k and the new TersusService state ts'
m >>= k = TersusServiceM (\ts -> (runTersusServiceM m) ts >>= \(ts',a) -> runTersusServiceM (k a) ts')
return a = TersusServiceM $ (\ts -> return (ts,a))
-- | Use the liftIO function of Process to lift an IO monad into the
-- Process monad, then the resulting value is binded and the provided
-- TersusService state ts is coupled with the value to get back into
-- the TersusServiceM
instance MonadIO TersusServiceM where
liftIO ioVal = TersusServiceM $ \ts -> (liftIO ioVal >>= \x -> return (ts,x))
-- | Run a TersusServiceM with the given TersusService state ts. Usually the initial
-- state which are all the messaging pipeings as defined in the datatype
evalTersusServiceM :: TersusService -> TersusServiceM a -> Process (TersusService,a)
evalTersusServiceM ts (TersusServiceM service) = service ts >>= \a -> return a
recvListenerFun :: (Typeable a, Binary a) => TersusService -> ReceivePort a -> [(a -> TersusServiceM ())] -> Process ()
recvListenerFun ts recvPort funs = forever $ do
recvVal <- receiveChan recvPort
mapM_ (\f -> evalTersusServiceM ts (f recvVal)) funs
-- | Initialize a process that runs the given server side application
makeTersusService :: TersusServerApp -> Connection -> TersusClusterList -> SendAddressTable -> RecvAddressTable -> Process (ProcessId)
makeTersusService tersusServerApp conn server sSendChannels sRecvChannels = do
(aSendPort,aRecvPort) <- newChan
(mSendPort,mRecvPort) <- newChan
let
serverApp = TersusService{
msgChannel = (mSendPort,mRecvPort),
ackwChannel = (aSendPort,aRecvPort),
serviceApplication = applicationRep tersusServerApp,
serviceConnection = conn,
tersusNode = server,
serviceSendChannels = sSendChannels,
serviceRecvChannels = sRecvChannels
}
tAppInstance = AppInstance{
username = nickname $ userRep tersusServerApp,
application = identifier $ applicationRep tersusServerApp
}
broadcastNotificationsProcess [Initialized tAppInstance (mSendPort,aSendPort,"hashPelado")] server
spawnLocal $ recvListenerFun serverApp mRecvPort [recvFunction $ msgFun tersusServerApp]
recvFunction :: (TMessage -> TersusServiceM ()) -> TMessageEnvelope -> TersusServiceM ()
recvFunction f (msg,ackwPort) = do
ts <- getTersusService
-- liftProcess $ sendChan ackwPort $ (
f $ msg
getTersusService :: TersusServiceM (TersusService)
getTersusService = TersusServiceM $ \ts -> return (ts,ts)
-- Default acknowledgement function ignores the message
-- acknowledgement
-- defaultAckwFun :: MessageResultEnvelope -> TersusServiceM ()
-- defaultAckwFun _ = return ()
-- notifyCreateProcess' (TersusService nChannel deliveryChannel mPorts aPorts appInstance clusterList) = do
-- liftIO $ atomically $ writeTChan nChannel (Initialized' appInstance)
-- return (TersusService nChannel deliveryChannel mPorts aPorts appInstance clusterList,())
-- notifyCreateProcess = TersusServiceM $ notifyCreateProcess'
-- getMessages' (TersusService nChannel deliveryChannel mailBox (sChan,rChan) appInstance) = do
-- msgs <- liftIO $ atomically $ readTVar mailBox
-- return ((TersusService nChannel deliveryChannel mailBox (sChan,rChan) appInstance),msgs)
-- getMessages = TersusServiceM getMessages'
liftProcess :: Process a -> TersusServiceM a
liftProcess p = TersusServiceM $ \ts -> p >>= \r -> return (ts,r)
-- getMessage' :: TersusService -> Process (TersusService,TMessageEnvelope)
-- getMessage' (TersusService sDeliveryChannel (mSendPort,mRecvPort) aPorts appInstance' sClusterList state) = do
-- msg <- receiveChan mRecvPort
-- return (TersusService sDeliveryChannel (mSendPort,mRecvPort) aPorts appInstance' sClusterList state,msg)
-- Get the next message delivered to this particular server side application.
-- Ie. message located in the delivery channle created for this app
-- getMessage :: TersusServiceM (TMessageEnvelope)
-- getMessage = TersusServiceM getMessage'
-- sendMessageInt :: TMessage -> TersusService -> Process (TersusService,())
-- sendMessageInt msg (TersusService sDeliveryChannel mPorts (aSendPort,aRecvPort) appInstance' sClusterList state) = do
-- liftIO $ atomically $ writeTChan sDeliveryChannel (msg,aSendPort)
-- return (TersusService sDeliveryChannel mPorts (aSendPort,aRecvPort) appInstance' sClusterList state,())
-- -- Send a message from a server side application it uses the message queue
-- -- form the server where it's actually running
-- sendMessage :: TMessage -> TersusServiceM ()
-- sendMessage msg = TersusServiceM $ sendMessageInt msg
-- -- | Send a message without timestamp, the timestamp will be added automatically
-- sendMessage' :: (UTCTime -> TMessage) -> TersusServiceM ()
-- sendMessage' pMsg = do
-- msg <- (liftIO getCurrentTime) >>= return.pMsg
-- sendMessage msg
-- acknowledgeMsg' :: TMessageEnvelope -> TersusService -> Process (TersusService,())
-- acknowledgeMsg' (msg,aPort) ts = do
-- sendChan aPort (generateHash msg, Delivered , getSendAppInstance msg)
-- return (ts,())
-- | Get the acid state of the given Tersus Server Application
-- getDb :: TersusServiceM (AcidState store)
-- getDb = TersusServiceM getDb'
-- where
-- getDb' tersusService = case memDb tersusService of
-- Nothing -> throw NoStateException
-- Just s -> return (tersusService,s)
-- Acknowledge a received message as received and infomr the
-- sender that the message was received
-- acknowledgeMsg :: (SafeCopy store) => TMessageEnvelope -> TersusServiceM store ()
-- acknowledgeMsg msgEnv = TersusServiceM $ acknowledgeMsg' msgEnv
{-
type MaybeQuery = MaybeT (SqlPersist IO)
{-maybeGetBy :: forall (m :: * -> *) val. (PersistEntity val,
PersistUnique
(PersistEntityBackend val) m) =>
Unique val (PersistEntityBackend val)
-> MaybeT
(PersistEntityBackend val m) (Database.Persist.Store.Entity val)-}
maybeGetBy criterion = MaybeT $ getBy criterion
maybeGet :: forall a (backend :: (* -> *) -> * -> *) (m :: * -> *). (PersistEntity a, PersistStore backend m) => Key backend a -> MaybeT (backend m) a
maybeGet id' = MaybeT $ get id'
{-maybeSelectList :: forall val (m :: * -> *).
(PersistEntity val,
PersistQuery
(PersistEntityBackend val) m) =>
[Filter val]
-> [SelectOpt val]
-> MaybeT
(Database.Persist.Store.PersistEntityBackend val m)
[Database.Persist.Store.Entity val]-}
maybeSelectList l1 l2 = MaybeT $ selectList l1 l2 >>= \res -> case res of
[] -> return Nothing
a -> return $ Just a
-}
|
kmels/tersus
|
Tersus/Cluster/TersusService.hs
|
Haskell
|
bsd-2-clause
| 10,769
|
{- Copyright (c) 2008, Scott E. Dillard. All rights reserved. -}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Type level naturals. @Ni@ is a type, @ni@ an undefined value of that type,
-- for @i <- [0..19]@
module Data.Vec.Nat where
data N0
data Succ a
type N1 = Succ N0
type N2 = Succ N1
type N3 = Succ N2
type N4 = Succ N3
type N5 = Succ N4
type N6 = Succ N5
type N7 = Succ N6
type N8 = Succ N7
type N9 = Succ N8
type N10 = Succ N9
type N11 = Succ N10
type N12 = Succ N11
type N13 = Succ N12
type N14 = Succ N13
type N15 = Succ N14
type N16 = Succ N15
type N17 = Succ N16
type N18 = Succ N17
type N19 = Succ N18
n0 :: N0 ; n0 = undefined
n1 :: N1 ; n1 = undefined
n2 :: N2 ; n2 = undefined
n3 :: N3 ; n3 = undefined
n4 :: N4 ; n4 = undefined
n5 :: N5 ; n5 = undefined
n6 :: N6 ; n6 = undefined
n7 :: N7 ; n7 = undefined
n8 :: N8 ; n8 = undefined
n9 :: N9 ; n9 = undefined
n10 :: N10 ; n10 = undefined
n11 :: N11 ; n11 = undefined
n12 :: N12 ; n12 = undefined
n13 :: N13 ; n13 = undefined
n14 :: N14 ; n14 = undefined
n15 :: N15 ; n15 = undefined
n16 :: N16 ; n16 = undefined
n17 :: N17 ; n17 = undefined
n18 :: N18 ; n18 = undefined
n19 :: N19 ; n19 = undefined
-- | @nat n@ yields the @Int@ value of the type-level natural @n@.
class Nat n where nat :: n -> Int
instance Nat N0 where nat _ = 0
instance Nat a => Nat (Succ a) where nat _ = 1+(nat (undefined::a))
class Pred x y | x -> y, y -> x
instance Pred (Succ N0) N0
instance Pred (Succ n) p => Pred (Succ (Succ n)) (Succ p)
|
sedillard/Vec
|
Data/Vec/Nat.hs
|
Haskell
|
bsd-2-clause
| 1,798
|
module Emulator.Video.Util where
import Emulator.Memory
import Emulator.Types
import Control.Monad.IO.Class
import Data.Array.IArray
import Data.Bits
import Graphics.Rendering.OpenGL
import Utilities.Parser.TemplateHaskell
data ScreenObj =
BG [Tile] Priority Layer |
Sprite [Tile] Priority |
Hidden
deriving (Show, Read, Eq)
data Tile = Tile [HalfWord] QuadCoords
deriving (Show, Read, Eq)
type Layer = Int
type Priority = Int
type AddressIO m = (AddressSpace m, MonadIO m)
type AffineParameters = (GLdouble, GLdouble, GLdouble, GLdouble)
type AffineRefPoints = (GLdouble, GLdouble)
type PaletteFormat = Bool
type QuadCoords = ((GLdouble, GLdouble), (GLdouble, GLdouble), (GLdouble, GLdouble), (GLdouble, GLdouble))
type PixData = Array Address Byte
type TileMapBaseAddress = Address
type TileOffset = (GLdouble, GLdouble)
type TileSet = Array Address Byte
type TileSetBaseAddress = Address
type Centre = (GLdouble, GLdouble)
transformCoords :: [Tile] -> Centre -> AffineParameters -> [Tile]
transformCoords [] _ _ = []
transformCoords ((Tile pix coords):xs) centre params = Tile pix affCoords:transformCoords xs centre params
where
affCoords = affineCoords centre params coords
-- this will be the function that is used
affineCoords :: Centre -> AffineParameters -> QuadCoords -> QuadCoords
affineCoords (xCentre, yCentre) (pa, pb, pc, pd) coords = ((affx1, affy1), (affx2, affy2), (affx3, affy3), (affx4, affy4))
where
((x1, y1), (x2, y2), (x3, y3), (x4, y4)) = coords
affx1 = (pa * (x1 - xCentre)) + (pb * (y1 - yCentre)) + xCentre
affy1 = (pc * (x1 - xCentre)) + (pd * (y1 - yCentre)) + yCentre
affx2 = (pa * (x2 - xCentre)) + (pb * (y2 - yCentre)) + xCentre
affy2 = (pc * (x2 - xCentre)) + (pd * (y2 - yCentre)) + yCentre
affx3 = (pa * (x3 - xCentre)) + (pb * (y3 - yCentre)) + xCentre
affy3 = (pc * (x3 - xCentre)) + (pd * (y3 - yCentre)) + yCentre
affx4 = (pa * (x4 - xCentre)) + (pb * (y4 - yCentre)) + xCentre
affy4 = (pc * (x4 - xCentre)) + (pd * (y4 - yCentre)) + yCentre
bytesToHalfWord :: Byte -> Byte -> HalfWord
bytesToHalfWord lower upper = ((fromIntegral upper :: HalfWord) `shiftL` 8) .|. ((fromIntegral lower :: HalfWord) .&. 0xFF) :: HalfWord
-- If pixel format is 8bpp then the tileIndex read from the map is in steps of 40h
-- If pixel format is 4bpp then the tileIndex read from the map is in steps of 20h
convIntToAddr :: Int -> PaletteFormat -> Address
convIntToAddr n True = (0x00000040 * fromIntegral n)
convIntToAddr n _ = (0x00000020 * fromIntegral n)
-- If pixel format is 8bpp then TileSet is read in chunks of 40h
-- If not then TileSet is read in chunks of 20h
getTile :: PaletteFormat -> Address -> TileSet -> PixData
getTile True tileIdx tileSet = (ixmap (tileIdx, tileIdx + 0x0000003F) (id) tileSet :: PixData)
getTile _ tileIdx tileSet = (ixmap (tileIdx, tileIdx + 0x0000001F) (id) tileSet :: PixData)
convToFixedNum :: Byte -> Byte -> GLdouble
convToFixedNum low up
| sign = negate val
| otherwise = val
where
val = intPor + (fracPor / 256)
hword = bytesToHalfWord low up
fracPor = fromIntegral $ $(bitmask 7 0) hword
intPor = fromIntegral $ $(bitmask 14 8) hword
sign = testBit hword 15
referencePoint :: MWord -> GLdouble
referencePoint word
| sign = negate val
| otherwise = val
where
val = intPor + (frac / 256)
frac = fromIntegral $ $(bitmask 7 0) word :: GLdouble
intPor = fromIntegral $ $(bitmask 26 8) word :: GLdouble
sign = testBit word 27
affineParameters :: Address -> Address -> Address -> Address -> Array Address Byte -> AffineParameters
affineParameters addr0 addr1 addr2 addr3 mem = (pa, pb, pc, pd)
where
pa = convToFixedNum (mem!(addr0)) (mem!(addr0 + 0x00000001))
pb = convToFixedNum (mem!(addr1)) (mem!(addr1 + 0x00000001))
pc = convToFixedNum (mem!(addr2)) (mem!(addr2 + 0x00000001))
pd = convToFixedNum (mem!(addr3)) (mem!(addr3 + 0x00000001))
data BGControl = -- R/W. BGs 0-3
BGControl { bgPriority :: Int -- 0 = Highest
, characterBaseBlock :: TileSetBaseAddress -- =BG Tile Data. Indicates the start of tile counting
, mosaic :: Bool
, colorsPalettes :: Bool -- (0=16/16, 1=256/1)
, screenBaseBlock :: TileMapBaseAddress
, displayAreaFlow :: Bool -- BG 2 & BG 3 only
, screenSize :: Int }
deriving (Show, Read, Eq)
-- Reads a mem address that points to bgcnt register
recordBGControl :: AddressSpace m => Address -> m BGControl
recordBGControl addr = do
hword <- readAddressHalfWord addr
let bgCNT = BGControl (fromIntegral $ $(bitmask 1 0) hword)
(baseTileSetAddr (fromIntegral $ $(bitmask 3 2) hword))
(testBit hword 6)
(testBit hword 7)
(baseTileMapAddr (fromIntegral $ $(bitmask 12 8) hword))
(testBit hword 13)
(fromIntegral $ $(bitmask 15 14) hword)
return bgCNT
-- Gets the base memory addres for the tile
baseTileSetAddr :: Byte -> TileSetBaseAddress
baseTileSetAddr tileBase = 0x06000000 + (0x00004000 * (fromIntegral tileBase))
baseTileMapAddr :: Byte -> TileMapBaseAddress
baseTileMapAddr mapBase = 0x06000000 + (0x00000800 * (fromIntegral mapBase))
|
intolerable/GroupProject
|
src/Emulator/Video/Util.hs
|
Haskell
|
bsd-2-clause
| 5,315
|
module TinyASM.ByteCode (
ByteCode(..),
size,
compileByteCode
)
where
import Text.Printf (printf)
data ByteCode = BC1 Int
| BC2 Int Int
| BC3 Int Int Int
| BC4 Int Int Int Int
instance Show ByteCode where
show (BC1 op) = "ByteCode " ++ (showHex op)
show (BC2 op b) = (show $ BC1 op) ++ " " ++ (showHex b)
show (BC3 op b c) = (show $ BC2 op b) ++ " " ++ (showHex c)
show (BC4 op b c d) = (show $ BC3 op b c) ++ " " ++ (showHex d)
size :: ByteCode -> Int
size (BC1 _) = 1
size (BC2 _ _) = 2
size (BC3 _ _ _) = 3
size (BC4 _ _ _ _) = 4
compileByteCode :: ByteCode -> [Int]
compileByteCode (BC1 op) = [op]
compileByteCode (BC2 op b) = [op, b]
compileByteCode (BC3 op b c) = [op, b, c]
compileByteCode (BC4 op b c d) = [op, b, c, d]
showHex :: Int -> String
showHex = printf "0x%02x"
|
ocus/TinyASM_Haskell
|
library/TinyASM/ByteCode.hs
|
Haskell
|
bsd-3-clause
| 877
|
{-
Copyright (c) 2013, Genome Research Limited
Author: Nicholas Clarke <nicholas.clarke@sanger.ac.uk>
-}
module Hgc.Mount (
mkMountPoint
, mkFstabEntry
, mount
, umount
, SLM.MountFlag(..)
, Mount (..)
)
where
import System.Log.Logger
import System.Directory (canonicalizePath
, doesFileExist
, doesDirectoryExist
)
import System.FilePath
import qualified System.Linux.Mount as SLM
import Data.List (intercalate)
import Data.Maybe (catMaybes)
import qualified Data.ByteString.Char8 as B (pack)
import Hgc.Shell
data Mount = Mount
String -- ^ Mount from
FilePath -- ^ Mount to
String -- ^ Mount type
[SLM.MountFlag] -- ^ System independent mount options
[String] -- ^ System dependent mount options
-- | Convert SML option to a string suitable for use in
slmOptionString :: SLM.MountFlag -> Maybe String
slmOptionString opt = case opt of
SLM.Rdonly -> Just "ro"
SLM.Remount -> Just "remount"
SLM.Noatime -> Just "noatime"
SLM.Bind -> Just "bind"
_ -> Nothing
-- | Mount a filesystem.
mount :: Mount -> IO()
mount m @ (Mount from to typ opt1 opt2) =
debugM "hgc.mount" ("Mounting: " ++ mkFstabEntry m) >>
mkdir to >>
SLM.mount from to typ opt1 dd
where dd = B.pack . intercalate "," $ opt2
-- | Unmount a filesystem.
umount :: Mount -> IO ()
umount m@(Mount _ to _ _ _) =
debugM "hgc.mount" ("Unmounting: " ++ mkFstabEntry m) >>
SLM.umount to
mkFstabEntry :: Mount -> String
mkFstabEntry (Mount from to typ opt1 opt2) =
intercalate " " [from, to, typ, intercalate "," opts, "0", "0"]
where opts = (catMaybes $ map slmOptionString opt1) ++ opt2
-- Make a mount point in the container to mount on top of
mkMountPoint :: FilePath -- ^ Root mount point
-> FilePath -- ^ Thing to mount
-> IO (FilePath, FilePath) -- ^ Canoncal resource path, Created mountpoint relative to root
mkMountPoint mountLoc resource = do
resourceC <- canonicalizePath . dropTrailingPathSeparator $ resource
let resourceR = makeRelative "/" resource
isDir <- doesDirectoryExist resourceC
isFile <- doesFileExist resourceC
let mp = mountLoc </> resourceR
mkdir $ mountLoc </> (dropFileName resourceR)
case (isDir, isFile) of
(False, True) -> debugM "hgc.mount" ("Touching file mountpoint " ++ mp) >>
touch mp >> return (resourceC, resourceR)
(True, False) -> debugM "hgc.mount" ("Making directory mountpoint " ++ mp) >>
mkdir mp >> return (resourceC, resourceR)
(True, True) -> ioError . userError $
"Really weird: mount point is both file and directory: " ++ resourceC
(False, False) -> ioError . userError $
"Mount point does not exist or cannot be read: " ++ resourceC
|
wtsi-hgi/hgc-tools
|
Hgc/Mount.hs
|
Haskell
|
bsd-3-clause
| 2,815
|
-- tape something something something
module Tape where
import Zipper
type Tape = Zipper Integer
alterReg :: (Integer -> Integer) -> Tape -> Tape
alterReg f tape = replace (f (readReg tape)) tape
incrReg :: Tape -> Tape
incrReg t = alterReg incr t
where incr :: Integer -> Integer
incr n = n + 1
decrReg :: Tape -> Tape
decrReg t = alterReg decr t
where decr :: Integer -> Integer
decr n = n - 1
nextReg :: Tape -> Tape
nextReg tape =
case nextSafe tape of
Just tape' -> tape'
Nothing -> insertAfter 0 tape
prevReg :: Tape -> (Tape)
prevReg tape =
case prevSafe tape of
Just tape' -> tape'
Nothing -> insertBefore 0 tape
readReg :: Tape -> Integer
readReg tape =
case cursorSafe tape of
Just val -> val
Nothing -> error "Tape initialised incorrectly. Empty Tape can not be read."
writeReg :: Integer -> Tape -> Tape
writeReg = replace
|
rodneyp290/Brainfunc
|
src/Tape.hs
|
Haskell
|
bsd-3-clause
| 895
|
{-#LANGUAGE BangPatterns #-}
module Main where
import Control.Foldl (Fold(..),FoldM(..))
import qualified Control.Foldl as L
import qualified Control.FoldM as M
import Pipes
import qualified Pipes.Prelude as P
import qualified Data.Vector.Unboxed as V
-- import qualified Data.Vector.Generic as VG
-- import qualified Data.Vector.Fusion.Bundle as VB
import Streaming
import qualified Streaming.Prelude as S
import Criterion.Main
import Data.Functor.Identity
import Data.Foldable (find)
import Data.List (elemIndex)
main :: IO ()
main = do
let size :: Int
size = 10
vfold :: Fold Int a -> V.Vector Int -> a
vfold = \(Fold step begin done) v -> done (V.foldl step begin v)
{-#INLINE vfold #-}
vfoldM :: FoldM Identity Int a -> V.Vector Int -> a
vfoldM = \(FoldM step begin done) vec -> runIdentity (
begin >>= flip (V.foldM step) vec >>= done )
{-#INLINE vfoldM #-}
pfold :: Fold Int a -> Producer Int Identity () -> a
pfold = \f p -> runIdentity (L.purely P.fold f p)
{-#INLINE pfold #-}
pfoldM :: FoldM Identity Int a -> Producer Int Identity () -> a
pfoldM = \f p -> runIdentity (L.impurely P.foldM f p)
{-#INLINE pfoldM #-}
sfold :: Fold Int a -> Stream (Of Int) Identity () -> (Of a ())
sfold = \f p -> runIdentity (L.purely S.fold f p)
{-#INLINE sfold #-}
sfoldM :: FoldM Identity Int a -> Stream (Of Int) Identity () -> (Of a ())
sfoldM = \f p -> runIdentity (L.impurely S.foldM f p)
{-#INLINE sfoldM #-}
lfoldm :: FoldM Identity Int a -> [Int] -> a
lfoldm = \f p -> runIdentity (L.foldM f p)
{-#INLINE lfoldm #-}
p /// q = p (whnf q (replicate size (1::Int)))
{-#INLINE (///) #-}
p //// q = p (whnf q (V.replicate size (1::Int)))
{-#INLINE (////) #-}
p /\ q = p (whnf q (each (replicate size (1::Int)):: Producer Int Identity ()))
-- p /\ q = p (whnf q (P.replicateM size (Identity (1::Int))))
{-#INLINE (/\) #-}
p \/ q = p (whnf q (S.each (replicate size (1::Int)):: Stream (Of Int) Identity ()))
-- p /\ q = p (whnf q (P.replicateM size (Identity (1::Int))))
{-#INLINE (\/) #-}
defaultMain
[ bgroup "list"
[ bgroup "sum" [bench "prelude" /// sum
, bench "pure" /// L.fold L.sum
, bench "impure" /// M.fold M.sum
, bench "generalize" /// lfoldm (L.generalize L.sum)
]
, bgroup "product" [bench "prelude" /// product
, bench "pure" /// L.fold L.product
, bench "impure" /// M.fold M.product
, bench "generalize" /// lfoldm (L.generalize L.product)
]
, bgroup "null" [bench "prelude" /// null
, bench "pure" /// L.fold L.null
, bench "impure" /// M.fold M.null
, bench "generalize" /// lfoldm (L.generalize L.null)
]
, bgroup "length" [bench "prelude" /// length
, bench "pure" /// L.fold L.length
, bench "impure" /// M.fold M.length
, bench "generalize" /// lfoldm (L.generalize L.length)
]
, bgroup "minimum" [bench "prelude" /// minimum
, bench "pure" /// L.fold L.minimum
, bench "impure" /// M.fold M.minimum
, bench "generalize" /// lfoldm (L.generalize L.minimum)
]
, bgroup "maximum" [bench "prelude" /// maximum
, bench "pure" /// L.fold L.maximum
, bench "impure" /// M.fold M.maximum
, bench "generalize" /// lfoldm (L.generalize L.maximum)
]
, bgroup "any" [bench "prelude" /// any even
, bench "pure" /// L.fold (L.any even)
, bench "impure" /// M.fold (M.any even)
, bench "generalize" /// lfoldm (L.generalize (L.any even))
]
, bgroup "elem" [bench "prelude" /// elem 12
, bench "pure" /// L.fold (L.elem 12)
, bench "impure" /// M.fold (M.elem 12)
, bench "generalize" /// lfoldm (L.generalize (L.elem 12))
]
, bgroup "find" [bench "prelude" /// find even
, bench "pure" /// L.fold (L.find even)
, bench "impure" /// M.fold (M.find even)
, bench "generalize" /// lfoldm (L.generalize (L.find even))
]
, bgroup "index" [bench "prelude" /// (!! (size-1))
, bench "pure" /// L.fold (L.index (size-1))
, bench "impure" /// M.fold (M.index (size-1))
, bench "generalize" /// lfoldm (L.generalize (L.index (size-1)))
]
, bgroup "elemIndex" [bench "prelude" /// elemIndex (size-1)
, bench "pure" /// L.fold (L.elemIndex (size-1))
, bench "impure" /// M.fold (M.elemIndex (size-1))
, bench "generalize" /// lfoldm (L.generalize (L.elemIndex (size-1)))
]
]
, bgroup "vector"
[ bgroup "sum"
[bench "prelude" //// V.sum
, bench "pure" //// vfold L.sum
, bench "impure" //// vfoldM M.sum
, bench "generalize" //// vfoldM (L.generalize L.sum)
]
, bgroup "product" [bench "prelude" //// V.product
, bench "pure" //// vfold L.product
, bench "impure" //// vfoldM M.product
, bench "generalize" //// vfoldM (L.generalize L.product)
]
, bgroup "null" [bench "prelude" //// V.null
, bench "pure" //// vfold L.null
, bench "impure" //// vfoldM M.null
, bench "generalize" //// vfoldM (L.generalize L.null)
]
, bgroup "length" [bench "prelude" //// V.length
, bench "pure" //// vfold L.length
, bench "impure" //// vfoldM M.length
, bench "generalize" //// vfoldM (L.generalize L.length)
]
, bgroup "minimum" [bench "prelude" //// V.minimum
, bench "pure" //// vfold L.minimum
, bench "impure" //// vfoldM M.minimum
, bench "generalize" //// vfoldM (L.generalize L.minimum)
]
, bgroup "any" [bench "prelude" //// V.all even
, bench "pure" //// vfold (L.all even)
, bench "impure" //// vfoldM (M.all even)
, bench "generalize" //// vfoldM (L.generalize (L.all even))
]
, bgroup "elem" [bench "prelude" //// V.elem 12
, bench "pure" //// vfold (L.elem 12)
, bench "impure" //// vfoldM (M.elem 12)
, bench "generalize" //// vfoldM (L.generalize (L.elem 12))
]
, bgroup "find" [bench "prelude" //// V.find even
, bench "pure" //// vfold (L.find even)
, bench "impure" //// vfoldM (M.find even)
, bench "generalize" //// vfoldM (L.generalize (L.find even))
]
, bgroup "index" [bench "prelude" //// (V.! (size-1))
, bench "pure" //// vfold (L.index (size-1))
, bench "impure" //// vfoldM (M.index (size-1))
, bench "generalize" //// vfoldM (L.generalize (L.index (size-1)))
]
, bgroup "elemIndex" [bench "prelude" //// V.elemIndex (size-1)
, bench "pure" //// vfold (L.elemIndex (size-1))
, bench "impure" //// vfoldM (M.elemIndex (size-1))
, bench "generalize" //// vfoldM (L.generalize (L.elemIndex (size-1)))
]
]
, bgroup "pipes"
[ bgroup "sum"
[bench "prelude" /\ P.sum
, bench "pure" /\ pfold L.sum
, bench "impure" /\ pfoldM M.sum
, bench "generalize" /\ pfoldM (L.generalize L.sum)
]
, bgroup "product" [bench "prelude" /\ P.product
, bench "pure" /\ pfold L.product
, bench "impure" /\ pfoldM M.product
, bench "generalize" /\ pfoldM (L.generalize L.product)
]
, bgroup "null" [bench "prelude" /\ P.null
, bench "pure" /\ pfold L.null
, bench "impure" /\ pfoldM M.null
, bench "generalize" /\ pfoldM (L.generalize L.null)
]
, bgroup "length" [bench "prelude" /\ P.length
, bench "pure" /\ pfold L.length
, bench "impure" /\ pfoldM M.length
, bench "generalize" /\ pfoldM (L.generalize L.length)
]
, bgroup "minimum" [bench "prelude" /\ P.minimum
, bench "pure" /\ pfold L.minimum
, bench "impure" /\ pfoldM M.minimum
, bench "generalize" /\ pfoldM (L.generalize L.minimum)
]
]
--
, bgroup "streaming"
[ bgroup "sum"
[bench "prelude" \/ S.sum
, bench "pure" \/ sfold L.sum
, bench "impure" \/ sfoldM M.sum
, bench "generalize" \/ sfoldM (L.generalize L.sum)
]
, bgroup "product" [bench "prelude" \/ S.product
, bench "pure" \/ sfold L.product
, bench "impure" \/ sfoldM M.product
, bench "generalize" \/ sfoldM (L.generalize L.product)
]
, bgroup "length" [bench "prelude" \/ S.length
, bench "pure" \/ sfold L.length
, bench "impure" \/ sfoldM M.length
, bench "generalize" \/ sfoldM (L.generalize L.length)
]
, bgroup "minimum" [bench "prelude" \/ S.minimum
, bench "pure" \/ sfold L.minimum
, bench "impure" \/ sfoldM M.minimum
, bench "generalize" \/ sfoldM (L.generalize L.minimum)
]
]
]
|
michaelt/foldm
|
benchmarks/Bench.hs
|
Haskell
|
bsd-3-clause
| 10,913
|
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TupleSections #-}
--
-- | Copy all arguments to a function in to variables which are named the same
-- as the function's parameters. This is known as Grail Normal Form [1] and
-- is the ANF equivalent of phi-elimination on SSA.
--
-- 1. Grail: a functional form for imperative mobile code.
-- Lennart Beringer, Kenneth MacKenzie and Ian Stark
-- http://homepages.inf.ed.ac.uk/stark/graffi.pdf
--
module River.Core.Transform.Grail (
grailOfProgram
, grailOfTerm
, GrailError(..)
) where
import Data.Map (Map)
import qualified Data.Map as Map
import River.Bifunctor
import River.Core.Syntax
data GrailError n a =
GrailFunctionNotFound !a !n ![Atom n a]
| GrailCallArityMismatch !a !n ![Atom n a] ![n]
deriving (Eq, Ord, Show, Functor)
grailOfProgram :: Ord n => Program k p n a -> Either (GrailError n a) (Program k p n a)
grailOfProgram = \case
Program a tm ->
Program a <$> grailOfTerm Map.empty tm
grailOfTerm :: Ord n => Map n [n] -> Term k p n a -> Either (GrailError n a) (Term k p n a)
grailOfTerm env0 = \case
Return a tl ->
grailOfTail env0 tl $ pure . Return a
If a k i t e ->
If a k i
<$> grailOfTerm env0 t
<*> grailOfTerm env0 e
Let a ns tl0 tm ->
grailOfTail env0 tl0 $ \tl ->
Let a ns tl <$>
grailOfTerm env0 tm
LetRec a bs0 tm -> do
(env, bs) <- grailOfBindings env0 bs0
LetRec a bs <$>
grailOfTerm env tm
grailOfBindings ::
Ord n =>
Map n [n] ->
Bindings k p n a ->
Either (GrailError n a) (Map n [n], Bindings k p n a)
grailOfBindings env0 = \case
Bindings a bs ->
let
env1 =
Map.fromList $ fmap (second paramsOfBinding) bs
env =
env1 `Map.union` env0
in
(env,) . Bindings a <$>
traverse (secondA (grailOfBinding env)) bs
paramsOfBinding :: Binding k p n a -> [n]
paramsOfBinding = \case
Lambda _ ns _ ->
ns
grailOfBinding :: Ord n => Map n [n] -> Binding k p n a -> Either (GrailError n a) (Binding k p n a)
grailOfBinding env = \case
Lambda a ns tm ->
Lambda a ns <$> grailOfTerm env tm
grailOfTail ::
Ord n =>
Map n [n] ->
Tail p n a ->
(Tail p n a -> Either (GrailError n a) (Term k p n a)) ->
Either (GrailError n a) (Term k p n a)
grailOfTail env tl mkTerm =
case tl of
Copy a xs ->
mkTerm $ Copy a xs
Call a n xs ->
case Map.lookup n env of
Nothing ->
Left $ GrailFunctionNotFound a n xs
Just ns ->
if length ns /= length xs then
Left $ GrailCallArityMismatch a n xs ns
else
Let a ns (Copy a xs) <$>
mkTerm (Call a n $ fmap (Variable a) ns)
Prim a n xs ->
mkTerm $ Prim a n xs
|
jystic/river
|
src/River/Core/Transform/Grail.hs
|
Haskell
|
bsd-3-clause
| 2,817
|
module Main where
import AminoAcid (HydratedAminoAcid)
import AminoAcidPDB (pdbAminoParser)
import qualified Data.Text.IO as TIO (readFile)
import System.Environment (getArgs)
import Text.Parsec (parse)
main :: IO ()
main = do
args <- getArgs
contents <- TIO.readFile $ head args
result $ parse pdbAminoParser "pdb parser" contents
result :: (Show a) => Either a [HydratedAminoAcid] -> IO ()
result (Left err) = putStr "Parse error: " >> print err
result (Right pdbLines) = mconcat $ printLine <$> pdbLines
printLine :: HydratedAminoAcid -> IO ()
printLine = print
|
mosigo/haskell-sandbox
|
app/AminoParser.hs
|
Haskell
|
bsd-3-clause
| 649
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
module LA.Instances () where
import Data.Vector.Fixed
import LA.Algebra
import Prelude hiding (foldl, zipWith, map, replicate)
instance (Additive a, Vector v a) => Additive (v a) where
add = zipWith add ; {-# INLINE add #-}
neg = map neg ; {-# INLINE neg #-}
zero = replicate zero ; {-# INLINE zero #-}
instance (Multiplicative a, Vector v a) => Multiplicative (v a) where
mul = zipWith mul ; {-# INLINE mul #-}
one = replicate one ; {-# INLINE one #-}
instance (Additive a, Multiplicative a, Vector v a) => VectorSpace (v a) where
type Scalar (v a) = a
scale = flip (map . mul) ; {-# INLINE scale #-}
instance (Additive a, Multiplicative a, Vector v a) => InnerSpace (v a) where
dot a = foldl add zero . (a .*)
|
chalmers-kandidat14/LA
|
LA/Instances.hs
|
Haskell
|
bsd-3-clause
| 870
|
module Clean where
import Data.List.Split
import System.FilePath.Glob
import System.FilePath.Posix
import Data.List (intercalate)
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Data.Monoid
import Data.Maybe
import ID3.Simple
import System
import Data.Rated
import Util
data MetaData = MetaData {
artist :: Rated String
, title :: Rated String
} deriving (Show)
data Song = Song {
songFileName :: FilePath
}
type Cleaner = Song -> IO MetaData
-- MetaData is a monoid
instance Monoid MetaData where
(MetaData a1 t1) `mappend` (MetaData a2 t2) = MetaData (a1 <|> a2) (t1 <|> t2)
mempty = MetaData Junk Junk
-- Pretty print metadata
prettyMeta :: MetaData -> String
prettyMeta m@(MetaData artist title) = joined <?> show m
where
joined = joinStr " - " <$> unk artist <*> unk title
joinStr sep a b = a ++ sep ++ b
unk m = m <|> pure "Unknown"
-- Parse metadata from filename
filenameMeta :: Song -> MetaData
filenameMeta s' = MetaData artist title
where
s = songFileName s'
rate = Rate 1
fileName = snd . splitFileName $ s
stripRate = rate . stripMp3
dashSplit = map trim $ splitOn "-" fileName
stripMp3 name = case splitOn "." name of
[] -> name
[s] -> name
ss -> intercalate "." . init $ ss
(artist, title) = case dashSplit of
[] -> (Junk, Junk)
[t] -> (Junk, stripRate t)
[a, t] -> (rate a, stripRate t)
a:t:rest -> (rate a, rate t)
-- Convert an ID3Tag to MetaData
tagToMeta :: Tag -> MetaData
tagToMeta t = let rate = (\f -> maybeToRated 10 . f $ t) in
MetaData (rate getArtist)
(rate getTitle)
-- Parse metadata from id3
id3Meta :: Song -> IO MetaData
id3Meta song = readTag file >>= return . metaFromMaybeTag
where
file = songFileName song
metaFromMaybeTag Nothing = mempty
metaFromMaybeTag (Just t) = tagToMeta t
-- Get our data from many different sources
getMeta :: [Cleaner] -> Song -> IO MetaData
getMeta cleaners song = mconcat <$> mapM ($song) cleaners
|
jb55/hmetadata
|
Clean.hs
|
Haskell
|
bsd-3-clause
| 2,302
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main where
import Prelude hiding (lookup)
import Control.Applicative
import Control.Monad.IO.Class
import Control.Monad.Trans.Either
import Data.Aeson
import Data.ByteString.Char8 (ByteString, pack, unpack)
import qualified Data.ByteString.Base64 as BS64
import Data.List
import Data.Monoid
import Data.Proxy
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time
import Network.Wai.Handler.Warp
import Servant.API
import Servant.Common.Text
import Servant.Server
import Network.Wai (Request)
import Network.Wai.Middleware.Cors
import Network.Wai.Middleware.RequestLogger
import Network.HTTP.Types.Method
import qualified Crypto.Hash.SHA256 as SHA256
import OptionsApp
--------------------------------------------------------------------------------
-- | Packs username and password login requests into a consistent structure
data AuthPack = AuthPack {
username :: String,
password :: String
}
instance FromJSON AuthPack where
parseJSON (Object o) = AuthPack <$> o .: "username" <*> o .: "password"
-- | Results of login attempts: either you're authenticated, or you're not.
data AuthResult = Authenticated {
identity :: String,
token :: String,
expiry :: UTCTime
} | Unauthenticated
instance ToJSON AuthResult where
toJSON Authenticated{..} = object [ "success" .= True
, "identity" .= identity
, "token" .= token
, "expiry" .= expiry ]
toJSON Unauthenticated = object [ "success" .= False ]
-- | HTTP Headers
newtype HttpHeader = HttpHeader Text
deriving (Eq, Show, FromText, ToText)
-- | String denoting computing resources.
type CompResource = String
-- | Results of resource lookup.
data GetResourceResult = FoundResources [CompResource] | NoResources | NoUser deriving (Show)
instance ToJSON GetResourceResult where
toJSON (FoundResources r) = object [ "success" .= True
, "resources" .= r ]
toJSON NoResources = object [ "success" .= True
, "resources" .= ([] :: CompResource) ]
toJSON NoUser = object [ "success" .= False ]
--------------------------------------------------------------------------------
-- POST /auth
-- Authenticate a given consumer username & password
-- against a given resource
-- Returns a 201 Created
type MetaDataAPI = "auth" :> ReqBody AuthPack
:> Post AuthResult
-- GET /resource
-- Get resources for a current token
:<|> "resource" :> Header "authorization" HttpHeader
:> Get GetResourceResult
server :: Server MetaDataAPI
server = doAuth :<|> doGetResources
doAuth :: AuthPack -> EitherT (Int, String) IO AuthResult
doAuth ap = liftIO $ tryAuth ap
doGetResources :: Maybe HttpHeader -> EitherT (Int, String) IO GetResourceResult
doGetResources t = liftIO $ tryGetResources t
metaAPI :: Proxy MetaDataAPI
metaAPI = Proxy
--------------------------------------------------------------------------------
-- | Try and authenticate user against a hardcoded list of credentials
tryAuth :: AuthPack -> IO AuthResult
tryAuth AuthPack{..} =
case lookup username defaultUsers of
Just p ->
if p == password
then do
t <- getCurrentTime
return $ Authenticated username (makeKey username p) t
else return Unauthenticated
_ -> return Unauthenticated
-- | Make me a key.
-- Don't do this in production.
makeKey :: String -> String -> String
makeKey u p = unpack $ BS64.encode $ SHA256.hash $ pack $ u <> p
-- | Gets a username from a key using a stupid lousy slow method.
-- Don't do this in production.
isOkKey :: String -> IO (Maybe String)
isOkKey ('O':'A':'u':'t':'h':' ':k) = return $ lookup k allKeys
where
allKeys = map toKey defaultUsers
toKey (u,p) = (makeKey u p, u)
-- | Try and get resources that matches a user that owns a given token.
tryGetResources :: Maybe HttpHeader -> IO GetResourceResult
tryGetResources (Just (HttpHeader k)) = do
maybeUsername <- isOkKey (T.unpack k)
case maybeUsername of
Just u -> do
case lookup u defaultUserResources of
Just r -> do
return $ FoundResources r
_ -> return $ NoResources
_ -> return NoUser
tryGetResources _ = return NoUser
-- | Hardcoded credentials
defaultUsers :: [(String, String)]
defaultUsers = [ ("jim@anchor.net.au", "bob")
, ("hi@anchor.net.au", "there")
, ("jane@anchor.net.au", "doe")
, ("hoob@anchor.net.au", "adoob")]
-- | User resources
defaultUserResources :: [(String, [CompResource])]
defaultUserResources = [ ("jim@anchor.net.au", [ "server:banjo"
, "server:timpani"])
, ("jane@anchor.net.au", [ "server:gamelan"
, "server:theremin"
, "server:lfo"]) ]
--------------------------------------------------------------------------------
-- | Run app
main :: IO ()
main = do
putStrLn "Running on http://localhost:8080"
Network.Wai.Handler.Warp.run 8080 $
logStdoutDev $
cors myCors $
handleOptions $
serve metaAPI server
-- | My CORS policy
myCors :: Request -> Maybe CorsResourcePolicy
myCors _ = Just $ simpleCorsResourcePolicy {
corsOrigins = Just (["http://localhost:8000"], True)
, corsMethods = [methodGet, methodPost, methodOptions]
, corsRequestHeaders = ["Content-Type", "Authorization"]
, corsVaryOrigin = True
, corsRequireOrigin = True
}
|
anchor/purescript-ui-sandbox
|
server/Main.hs
|
Haskell
|
bsd-3-clause
| 6,265
|
module Main where
import Control.Exception
import Control.Monad
import System.FilePath
import System.Directory
import System.Process
import Control.Concurrent
import Data.List.Split
import qualified Data.HashTable.IO as H
import qualified Data.ByteString.Lazy as L
import Data.Time.Clock
import qualified Codec.Archive.Tar as Tar
import Network
import System.Environment
import System.IO
import System.IO.Unsafe
import Utils
-- hashtable of app identifiers and process handles
ht :: (H.BasicHashTable Int ProcessHandle)
{-# NOINLINE ht #-}
ht = unsafePerformIO $ H.new
tmpDir :: FilePath
tmpDir = "tmp"
main :: IO ()
main = do
portstr <- head `fmap` getArgs
let port = PortNumber $ toEnum $ read portstr
bracket (listenOn port) sClose $ \s -> do
exists <- doesDirectoryExist tmpDir
when exists $ removeDirectoryRecursive tmpDir
createDirectory tmpDir
htMutex <- newMVar 0
forever $ do
(h, _, _) <- accept s
forkIO $ handleConnection h htMutex
`finally` hClose h
handleConnection :: Handle -> MVar Int -> IO ()
handleConnection h htMutex = foreverOrEOF2 h $ do
cmd <- trim `fmap` hGetLine h
case cmd of
"statuses" -> do -- prints list of processes
statusList <- atomic htMutex $ H.toList ht
hPutStrLn h (show $ map fst statusList)
"launch" -> do -- prints pid
putStrLn "launch called!"
-- format:
-- shell cmd
-- identifier (as an int)
-- var1=val1
-- var2=val2
-- ...
--
-- num bytes
-- tar data
shellcmd <- trim `fmap` hGetLine h
putStrLn $ "SHELL: " ++ (show shellcmd)
identifier <- (read . trim) `fmap` hGetLine h
putStrLn $ "ID: " ++ (show (identifier :: Int))
envs <- readenvs h
nbytes <- read `fmap` hGetLine h
tarfile <- L.hGet h nbytes
let entries = Tar.read tarfile
Tar.unpack tmpDir entries
void $ forkIO $ startApp htMutex shellcmd envs tmpDir identifier 0
"kill" -> atomic htMutex $ do -- OK or NOT FOUND
-- format:
-- app identifier
key <- (read . trim) `fmap` hGetLine h
mPHandle <- H.lookup ht key
case mPHandle of
Nothing -> hPutStrLn h "NOT FOUND"
Just pHandle -> do
terminateProcess pHandle
H.delete ht key
hPutStrLn h "OK"
_ -> do
hPutStrLn h $ "INVALID COMMAND (" ++ cmd ++ ")"
startApp :: MVar Int
-> String -- Command
-> [(String, String)] -- Environment
-> FilePath -- cwd
-> Int -- Identifier
-> Int -- Retries
-> IO ()
startApp htMutex command envs cwdpath identifier retries = when (retries < 5) $ do
output <- openFile (cwdpath </> "log.out") AppendMode
err <- openFile (cwdpath </> "log.err") AppendMode
input <- openFile "/dev/null" ReadMode
let createProc = (shell command) { env = Just envs
, cwd = Just cwdpath
, std_in = UseHandle input
, std_out = UseHandle output
, std_err = UseHandle err }
pHandle <- atomic htMutex $ do
(_, _, _, pHandle) <- createProcess createProc
hClose output
hClose err
hClose input
H.insert ht identifier pHandle
return pHandle
startTime <- getCurrentTime
_ <- waitForProcess pHandle
endTime <- getCurrentTime
mPHandle <- withMVar htMutex $ \_ -> H.lookup ht identifier
case mPHandle of
Nothing -> removeDirectoryRecursive cwdpath
Just _ -> do
atomic htMutex $ H.delete ht identifier
removeFromController command identifier
let nextRetries = if (diffUTCTime endTime startTime < 30) then
retries + 1
else 0
startApp htMutex command envs cwdpath identifier nextRetries
-- Utils
removeFromController :: Show a => String -> a -> IO ()
removeFromController appname identifier = do
let hostname = "localhost" -- hostname of the app controller
port = PortNumber 1234 -- port of the app controller
h <- connectTo hostname port -- handle for the app controller
hPutStrLn h "remove"
hPutStrLn h appname
hPutStrLn h $ show identifier
readenvs :: Handle -> IO [(String,String)]
readenvs h = go h []
where go hand list = do
line <- trim `fmap` hGetLine hand
putStrLn line
if line == "" then
return $ reverse list
else go hand $ (parseEnv line):list
parseEnv :: String -> (String, String)
parseEnv envString =
let (key:value:[]) = splitOn "=" envString
in (key, value)
|
scslab/appdeploy
|
src/appdeployer.hs
|
Haskell
|
bsd-3-clause
| 4,973
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module TCRError where
import Control.Monad.Reader
import Control.Monad.Error
import Database.TokyoCabinet
(
TCM
, runTCM
, new
, OpenMode(..)
, TCDB
, HDB
, BDB
, FDB
)
import Database.TokyoCabinet.Storable
import qualified Database.TokyoCabinet as TC
newtype TCRError tc e a =
TCRError { runTCRError :: ErrorT e (ReaderT tc TCM) a}
deriving (Monad, MonadReader tc, MonadError e)
runTCRE :: TCRError tc e a -> tc -> TCM (Either e a)
runTCRE = runReaderT . runErrorT . runTCRError
liftT :: (Error e) => TCM a -> TCRError tc e a
liftT = TCRError . lift . lift
open :: (TCDB tc) => String -> [OpenMode] -> TCRError tc String ()
open name mode = do tc <- ask
res <- liftT $ TC.open tc name mode
if res then return () else throwError "open failed"
close :: (TCDB tc) => TCRError tc String ()
close = ask >>= liftT . TC.close >>= \res ->
if res then return () else throwError "close failed"
put :: (TCDB tc) => String -> String -> TCRError tc String ()
put key val = do tc <- ask
res <- liftT $ TC.put tc key val
if res then return () else throwError "put failed"
get :: (TCDB tc) => String -> TCRError tc String (Maybe String)
get key = do tc <- ask
liftT $ TC.get tc key
kvstore :: (TCDB tc) => [(String, String)] -> TCRError tc String ()
kvstore kv = do open "abcd.tch" [OREADER]
mapM_ (uncurry put) kv
close
main :: IO ()
main = runTCM $ do h <- new :: TCM BDB
let kv = [("foo", "100"), ("bar", "200")]
flip runTCRE h $ catchError (kvstore kv) (\e -> error e)
>> return ()
|
tom-lpsd/tokyocabinet-haskell
|
examples/TCRError.hs
|
Haskell
|
bsd-3-clause
| 1,773
|
-- 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.RU.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Ordinal.RU.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "RU Tests"
[ makeCorpusTest [This Ordinal] corpus
]
|
rfranek/duckling
|
tests/Duckling/Ordinal/RU/Tests.hs
|
Haskell
|
bsd-3-clause
| 600
|
module EFA.Example.Topology.LinearTwo where
import EFA.Application.Utility ( topologyFromEdges )
import qualified EFA.Graph.Topology.Node as Node
import qualified EFA.Graph.Topology as Topo
import qualified EFA.Report.Format as Format
data Node = Source | Crossing | Sink deriving (Eq, Ord, Enum, Show)
node0, node1, node2 :: Node
node0 = Source
node1 = Crossing
node2 = Sink
instance Node.C Node where
display Source = Format.literal "Quelle"
display Crossing = Format.literal "Kreuzung"
display Sink = Format.literal "Senke"
subscript = Format.integer . fromIntegral . fromEnum
dotId = Node.dotIdDefault
typ Source = Node.AlwaysSource
typ Crossing = Node.Crossing
typ Sink = Node.AlwaysSink
topology :: Topo.Topology Node
topology = topologyFromEdges [(Source, Crossing), (Crossing, Sink)]
|
energyflowanalysis/efa-2.1
|
src/EFA/Example/Topology/LinearTwo.hs
|
Haskell
|
bsd-3-clause
| 839
|
module SkeletonTemplates.IUnzipFilter2D
( iunzipFilter2DActor
) where
import AstMappings
import qualified AbsCAL as C
import qualified AbsRIPL as R
import Debug.Trace
import SkeletonTemplates.CalTypes
import Types
iunzipFilter2DActor :: String -> Dimension -> R.AnonFun -> R.AnonFun -> C.Type -> C.Type -> C.Actor
iunzipFilter2DActor actorName (Dimension width height) anonFun1 anonFun2 incomingType outgoingType =
let ioSig =
C.IOSg
[C.PortDcl inType (C.Ident "In1")]
[C.PortDcl outType (C.Ident "Out1")
,C.PortDcl outType (C.Ident "Out2")]
inType = incomingType
outType = outgoingType
functions =
[ C.UnitCode (C.UFunDecl maxFun)
, C.UnitCode (C.UFunDecl (kernelFun "applyKernel1" anonFun1))
, C.UnitCode (C.UFunDecl (kernelFun "applyKernel2" anonFun2))
, C.UnitCode (C.UFunDecl mkModFunctionMod)
]
-- , C.UnitCode (C.UFunDecl mkModFunctionModTwoArgs)]
actions =
[ C.ActionCode (populateBufferAction width)
, C.ActionCode (donePopulateBufferAction width)
, C.ActionCode (topLeftAction width)
, C.ActionCode (topRowAction width)
, C.ActionCode (topRightAction width)
, C.ActionCode (midLeftAction1 width height)
, C.ActionCode (midLeftAction2 width height)
, C.ActionCode (midLeftActionNoConsume1 width height)
, C.ActionCode (midLeftActionNoConsume2 width height)
, C.ActionCode (midAction1 width height)
, C.ActionCode (midAction2 width height)
, C.ActionCode (midActionNoConsume1 width height)
, C.ActionCode (midActionNoConsume2 width height)
, C.ActionCode (midRightAction1 width height)
, C.ActionCode (midRightAction2 width height)
, C.ActionCode (midRightActionNoConsume1 width height)
, C.ActionCode (midRightActionNoConsume2 width height)
, C.ActionCode (bottomLeftActionNoConsume1 width height)
, C.ActionCode (bottomLeftActionNoConsume2 width height)
, C.ActionCode (bottomRowActionNoConsume1 width height)
, C.ActionCode (bottomRowActionNoConsume2 width height)
, C.ActionCode (bottomRightActionNoConsume1 width height)
, C.ActionCode (bottomRightActionNoConsume2 width height)
]
in C.ActrSchd
(C.PathN [C.PNameCons (C.Ident "cal")])
[]
(C.Ident actorName)
[]
ioSig
(globalVars width)
(functions ++ actions)
fsmSchedule
[]
globalVars width
-- uint(size=16) bufferSize = imageWidth * 2 + 3;
=
[ C.GlobVarDecl
(C.VDeclExpIMut
(uintCalType 16)
(C.Ident "bufferSize")
[]
(C.BEAdd (C.BEMult (mkInt width) (mkInt 2)) (mkInt 3)))
-- uint(size=16) buffer[bufferSize];
, C.GlobVarDecl
(C.VDecl
(intCalType 16)
(C.Ident "buffer")
[C.BExp (C.EIdent (C.Ident "bufferSize"))])
-- uint(size=16) idx := 0;
, C.GlobVarDecl (C.VDeclExpMut (intCalType 16) (C.Ident "idx") [] (mkInt 0))
-- uint(size=16) populatePtr := 0;
, C.GlobVarDecl
(C.VDeclExpMut (intCalType 16) (C.Ident "populatePtr") [] (mkInt 0))
-- uint(size=16) processedMidRows := 0;
, C.GlobVarDecl
(C.VDeclExpMut (intCalType 16) (C.Ident "processedRows") [] (mkInt 0))
-- uint(size=32) consumed := 0;
, C.GlobVarDecl
(C.VDeclExpMut (uintCalType 32) (C.Ident "consumed") [] (mkInt 0))
, C.GlobVarDecl
(C.VDeclExpMut (uintCalType 16) (C.Ident "midPtr") [] (mkInt 0))
, C.GlobVarDecl
(C.VDeclExpMut (boolCalType) (C.Ident "isEven") [] (mkBool True))
]
fsmSchedule :: C.ActionSchedule
fsmSchedule =
C.SchedfsmFSM
(C.Ident "s0")
[ C.StTrans (C.Ident "s0") (C.Ident "populateBuffer") (C.Ident "s0")
, C.StTrans (C.Ident "s0") (C.Ident "donePopulateBuffer") (C.Ident "s1")
, C.StTrans (C.Ident "s1") (C.Ident "topLeft") (C.Ident "s2")
, C.StTrans (C.Ident "s2") (C.Ident "topRow") (C.Ident "s2")
, C.StTrans (C.Ident "s2") (C.Ident "topRight") (C.Ident "s3")
, C.StTrans (C.Ident "s3") (C.Ident "midLeft1") (C.Ident "s4")
, C.StTrans (C.Ident "s3") (C.Ident "midLeft2") (C.Ident "s4")
, C.StTrans (C.Ident "s3") (C.Ident "midLeftNoConsume1") (C.Ident "s4")
, C.StTrans (C.Ident "s3") (C.Ident "midLeftNoConsume2") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "mid1") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "mid2") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "midNoConsume1") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "midNoConsume2") (C.Ident "s4")
, C.StTrans (C.Ident "s4") (C.Ident "midRight1") (C.Ident "s5")
, C.StTrans (C.Ident "s4") (C.Ident "midRight2") (C.Ident "s5")
, C.StTrans (C.Ident "s4") (C.Ident "midRightNoConsume1") (C.Ident "s5")
, C.StTrans (C.Ident "s4") (C.Ident "midRightNoConsume2") (C.Ident "s5")
, C.StTrans (C.Ident "s5") (C.Ident "midLeft1") (C.Ident "s4")
, C.StTrans (C.Ident "s5") (C.Ident "midLeft2") (C.Ident "s4")
, C.StTrans (C.Ident "s5") (C.Ident "midLeftNoConsume1") (C.Ident "s4")
, C.StTrans (C.Ident "s5") (C.Ident "midLeftNoConsume2") (C.Ident "s4")
, C.StTrans (C.Ident "s5") (C.Ident "bottomLeftNoConsume1") (C.Ident "s6")
, C.StTrans (C.Ident "s5") (C.Ident "bottomLeftNoConsume2") (C.Ident "s6")
, C.StTrans (C.Ident "s6") (C.Ident "bottomRowNoConsume1") (C.Ident "s6")
, C.StTrans (C.Ident "s6") (C.Ident "bottomRowNoConsume2") (C.Ident "s6")
, C.StTrans (C.Ident "s6") (C.Ident "bottomRightNoConsume1") (C.Ident "s0")
, C.StTrans (C.Ident "s6") (C.Ident "bottomRightNoConsume2") (C.Ident "s0")
]
-- priorityBlock :: [C.PriorityBlock]
-- priorityBlock = [ C.PriOrd
-- [ C.PriInEQ (C.Ident "midLeftNoConsume") (C.Ident "midLeft") []
-- , C.PriInEQ (C.Ident "midNoConsume") (C.Ident "mid") []
-- , C.PriInEQ (C.Ident "midRightNoConsume") (C.Ident "midRight") []
-- ]
-- ]
maxFun :: C.FunctionDecl
maxFun = C.FDecl (C.Ident "max") args returnType localVars body
where
args =
[ (C.ArgPar (intCalType 16) (C.Ident "i"))
, (C.ArgPar (intCalType 16) (C.Ident "j"))
]
localVars = C.FNVarDecl
returnType = intCalType 16
body =
C.IfExpCons
(C.IfExpr
(C.BEGT (identCalExp "i") (identCalExp "j"))
(identCalExp "i")
(identCalExp "j"))
mkModFunctionMod :: C.FunctionDecl
mkModFunctionMod = C.FDecl (C.Ident "myMod") args returnType localVars body
where
args = [C.ArgPar (mkIntType 16) (C.Ident "x")]
localVars = C.FNVarDecl
returnType = mkIntType 16
body = C.IfExpCons (C.IfExpr ifCond ifThen ifElse)
ifCond =
C.BEGT
(C.EIdent (C.Ident "x"))
(C.BENeg (C.BEMult (mkInt 2) (mkVar "bufferSize")) (mkInt 1))
ifThen = C.BENeg (mkVar "x") (C.BEMult (mkInt 2) (mkVar "bufferSize"))
ifElse = C.IfExpCons (C.IfExpr elseCond elseThen elseElse)
elseCond = C.BEGT (mkVar "x") (C.BENeg (mkVar "bufferSize") (mkInt 1))
elseThen = C.BENeg (mkVar "x") (mkVar "bufferSize")
elseElse = mkVar "x"
kernelFun :: String -> R.AnonFun -> C.FunctionDecl
kernelFun kernelName (R.AnonFunC lambdaExps userDefinedFunc) =
C.FDecl (C.Ident kernelName) args returnType localVars body
where
args =
map
(\(R.ExpSpaceSepC (R.ExprVar (R.VarC lambdaIdent))) ->
(C.ArgPar (mkIntType 16) (idRiplToCal lambdaIdent)))
lambdaExps
localVars = C.FVarDecl [resultAssignment]
resultAssignment =
C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "result")
[]
(expRiplToCal userDefinedFunc))
returnType = mkIntType 16
body = C.IdBrSExpCons (C.Ident "max") [mkInt 0, C.EIdent (C.Ident "result")]
midLeftAction1 width height = midLeftAction (C.EIdent (C.Ident "isEven")) "applyKernel1" "midLeft1" "Out1" width height
midLeftAction2 width height = midLeftAction (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midLeft2" "Out2" width height
midLeftActionNoConsume1 width height = midLeftActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "midLeftNoConsume1" "Out1" width height
midLeftActionNoConsume2 width height = midLeftActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midLeftNoConsume2" "Out2" width height
midAction1 width height = midAction (C.EIdent (C.Ident "isEven")) "applyKernel1" "mid1" "Out1" width height
midAction2 width height = midAction (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "mid2" "Out2" width height
midActionNoConsume1 width height = midActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "midNoConsume1" "Out1" width height
midActionNoConsume2 width height = midActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midNoConsume2" "Out2" width height
midRightAction1 width height = midRightAction (C.EIdent (C.Ident "isEven")) "applyKernel1" "midRight1" "Out1" width height
midRightAction2 width height = midRightAction (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midRight2" "Out2" width height
midRightActionNoConsume1 width height = midRightActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "midRightNoConsume1" "Out1" width height
midRightActionNoConsume2 width height = midRightActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "midRightNoConsume2" "Out2" width height
bottomLeftActionNoConsume1 width height = bottomLeftActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "bottomLeftNoConsume1" "Out1" width height
bottomLeftActionNoConsume2 width height = bottomLeftActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "bottomLeftNoConsume2" "Out2" width height
bottomRowActionNoConsume1 width height = bottomRowActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "bottomRowNoConsume1" "Out1" width height
bottomRowActionNoConsume2 width height = bottomRowActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "bottomRowNoConsume2" "Out2" width height
bottomRightActionNoConsume1 width height = bottomRightActionNoConsume (C.EIdent (C.Ident "isEven")) "applyKernel1" "bottomRightNoConsume1" "Out1" width height
bottomRightActionNoConsume2 width height = bottomRightActionNoConsume (C.UENot (C.EIdent (C.Ident "isEven"))) "applyKernel2" "bottomRightNoConsume2" "Out2" width height
populateBufferAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "populateBuffer"]
head = C.ActnHeadGuarded [inPattern] [] [guardExp]
inPattern = C.InPattTagIds (C.Ident "In1") [C.Ident "x"]
guardExp =
C.BELT
(C.EIdent (C.Ident "populatePtr"))
(C.BEAdd (mkInt width) (mkInt 3))
stmts =
[ arrayUpdate "buffer" "populatePtr" "x"
, varIncr "consumed"
, varIncr "populatePtr"
]
donePopulateBufferAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "donePopulateBuffer"]
head = C.ActnHeadGuarded [] [] [guardExp]
guardExp =
C.BEEQ (identCalExp "populatePtr") (C.BEAdd (mkInt width) (mkInt 3))
stmts = [varSetInt "populatePtr" 0]
-- in1:[token]
streamInPattern = C.InPattTagIds (C.Ident "In1") [C.Ident "token"]
-- out1:[v] or out2:[v]
streamOutPattern portName =
C.OutPattTagIds (C.Ident portName) [C.OutTokenExp (identCalExp "v")]
mkBufferIdxAssignment lhsIdent idxExp =
C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident lhsIdent)
[]
(C.EIdentArr (C.Ident "buffer") [(C.BExp idxExp)]))
topLeftAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "topLeft"]
head = C.ActnHeadVars [streamInPattern] [streamOutPattern "Out1"] localVars
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment "p2" (identCalExp "idx")
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment "p4" (identCalExp "idx")
, mkBufferIdxAssignment "p5" (identCalExp "idx")
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BENeg (mkInt width) (mkInt 1))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BENeg (mkInt width) (mkInt 1))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident "applyKernel1")
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayUpdate "buffer" "consumed" "token"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
, varIncr "consumed"
]
topRowAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "topRow"]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern "Out1"]
[guardExp]
localVars
guardExp = C.BELT (mkVar "midPtr") (mkInt (width - 1))
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 3)))
, mkBufferIdxAssignment "p4" (identCalExp "idx")
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 3)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEAdd (mkInt width) (mkInt 1))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEAdd (mkInt width) (mkInt 2))))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident "applyKernel1")
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varIncr "consumed"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
, varIncr "processedRows"
]
topRightAction width = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident "topRight"]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern "Out1"]
[guardExp]
localVars
guardExp = C.BEEQ (mkVar "midPtr") (mkInt (width - 1))
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment "p4" (identCalExp "idx")
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEAdd (mkInt width) (mkInt 1))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEAdd (mkInt width) (mkInt 2))))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident "applyKernel1")
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varIncr "consumed"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varSetInt "midPtr" 0
, varSetInt "processedRows" 1
, varNot "isEven"
]
midLeftAction predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern outPortName]
guardExps
localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt 0)
, C.BELT (mkVar "processedRows") (mkInt (height - 1))
, C.BELT (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment "p2" (identCalExp "idx")
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varIncr "consumed"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
midLeftActionNoConsume predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt 0)
, C.BELT (mkVar "processedRows") (mkInt (height - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment "p2" (identCalExp "idx")
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ C.SemiColonSeparatedStmt
(C.AssignStt
(C.AssStmt
(C.Ident "idx")
(C.IdBrSExpCons (C.Ident "myMod") [mkVar "consumed"])))
, varIncr "midPtr"
]
midAction predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern outPortName]
guardExps
localVars
guardExps =
[ C.BELT (mkVar "midPtr") (mkInt (width - 1))
, C.BELT (mkVar "processedRows") (mkInt (height - 1))
, C.BELT (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 2)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 2)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varIncr "consumed"
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
midActionNoConsume predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BELT (mkVar "midPtr") (mkInt (width - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 2)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 2)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
midRightAction predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head =
C.ActnHeadGuardedVars
[streamInPattern]
[streamOutPattern outPortName]
guardExps
localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt (width - 1))
, C.BELT (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ arrayExpUpdate
"buffer"
(C.BExp (findIndexFunc (C.BEAdd (mkVar "idx") (mkVar "bufferSize"))))
("token")
, varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "consumed"
, varIncr "processedRows"
, varSetInt "midPtr" 0
, varNot "isEven"
]
midRightActionNoConsume predicateExp kernelName actionName outPortName width height = C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt (width - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc
(C.BEAdd (identCalExp "idx") (C.BEMult (mkInt 2) (mkInt width))))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd
(C.BEAdd
(identCalExp "idx")
(C.BEMult (mkInt 2) (mkInt width)))
(mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts = [ varIncr "processedRows"
, varSetInt "midPtr" 0
, varNot "isEven"
]
bottomLeftActionNoConsume predicateExp kernelName actionName outPortName width height =
C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt 0)
, C.BEEQ (mkVar "processedRows") (mkInt (height - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment "p2" (identCalExp "idx")
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
bottomRowActionNoConsume predicateExp kernelName actionName outPortName width height =
C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BELT (mkVar "midPtr") (mkInt (width - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 2)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 2)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 2)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ varSetExp "idx" (findIndexFunc (C.BEAdd (mkVar "idx") (mkInt 1)))
, varIncr "midPtr"
]
bottomRightActionNoConsume predicateExp kernelName actionName outPortName width height =
C.AnActn (C.ActnTagsStmts tag head stmts)
where
tag = C.ActnTagDecl [C.Ident actionName]
head = C.ActnHeadGuardedVars [] [streamOutPattern outPortName] guardExps localVars
guardExps =
[ C.BEEQ (mkVar "midPtr") (mkInt (width - 1))
, C.BEEQ (mkVar "consumed") (mkInt (width * height))
, predicateExp
]
localVars =
C.LocVarsDecl
[ mkBufferIdxAssignment "p1" (identCalExp "idx")
, mkBufferIdxAssignment
"p2"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p3"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt 1)))
, mkBufferIdxAssignment
"p4"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p5"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p6"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p7"
(findIndexFunc (C.BEAdd (identCalExp "idx") (mkInt width)))
, mkBufferIdxAssignment
"p8"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, mkBufferIdxAssignment
"p9"
(findIndexFunc
(C.BEAdd (C.BEAdd (identCalExp "idx") (mkInt width)) (mkInt 1)))
, C.LocVarDecl
(C.VDeclExpIMut
(intCalType 16)
(C.Ident "v")
[]
(C.IdBrSExpCons
(C.Ident kernelName)
(map
identCalExp
["p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"])))
]
stmts =
[ varSetInt "processedRows" 0
, varSetInt "idx" 0
, varSetInt "midPtr" 0
, varSetInt "consumed" 0
, varNot "isEven"
]
findIndexFunc offset = C.IdBrSExpCons (C.Ident "myMod") [offset]
|
robstewart57/ripl
|
src/SkeletonTemplates/IUnzipFilter2D.hs
|
Haskell
|
bsd-3-clause
| 38,100
|
{-|
Module : Types
Description : Type information, used internally by Obsídian.
Copyright : (c) Joel Svensson, 2014
License : BSD
Maintainer : bo.joel.svensson@gmail.com
Stability : experimental
-}
module Obsidian.Types where
---------------------------------------------------------------------------
-- Types
---------------------------------------------------------------------------
data Type
-- The allowed scalar types
= Bool
| Int | Word -- A bit problematic since the size of
-- of these are platform dependent
| Int8 | Int16 | Int32 | Int64
| Word8 | Word16 | Word32 | Word64
| Float | Double
-- Used by CUDA, C And OpenCL generators
| Volatile Type -- For warp local computations.
| Pointer Type -- Pointer to a @type@
| Global Type -- OpenCL thing
| Local Type -- OpenCL thing
deriving (Eq, Ord, Show)
typeSize Int8 = 1
typeSize Int16 = 2
typeSize Int32 = 4
typeSize Int64 = 8
typeSize Word8 = 1
typeSize Word16 = 2
typeSize Word32 = 4
typeSize Word64 = 8
typeSize Bool = 4
typeSize Float = 4
typeSize Double = 8
|
svenssonjoel/ObsidianGFX
|
Obsidian/Types.hs
|
Haskell
|
bsd-3-clause
| 1,157
|
module Main where
import HTIG
main :: IO ()
main = htig defaultConfig
|
nakamuray/htig
|
htig.hs
|
Haskell
|
bsd-3-clause
| 72
|
{-# LANGUAGE LiberalTypeSynonyms #-}
{-# LANGUAGE RankNTypes #-}
module Htn where
import qualified Data.Map as M
import Data.List (find, null, (\\))
class (Eq a, Ord a, Show a) => Term a
class (Eq a, Ord a, Show a) => PrimitiveTask a
class (Eq a, Ord a, Show a) => CompoundTask a
data Task a b = Primitive a
| Compound b
| Invalid String
deriving Show
data Domain a b c = Domain {
primitiveMap :: M.Map a [([c], [c])]
, compoundMap :: M.Map b [([c], [Task a b])]
}
instance (Show a, Show b, Show c) => Show (Domain a b c) where
show (Domain p c) = toStr p ++ toStr c
where toStr :: (Show a, Show b) => M.Map a [b] -> String
toStr = M.foldlWithKey (\str task list -> str ++ "-- " ++ show task ++ "\n" ++ unlines (map show list)) ""
htn :: (PrimitiveTask a, CompoundTask b, Term c) => Domain a b c -> [c] -> [Task a b] -> ([Task a b], [c])
htn domain condition tasks = htn' domain condition tasks []
htn' :: (PrimitiveTask a, CompoundTask b, Term c) => Domain a b c -> [c] -> [Task a b] -> [Task a b] -> ([Task a b], [c])
htn' _ cond [] plan = (plan, cond)
htn' domain [] _ plan = (plan ++ [Invalid "no condition"], [])
htn' domain condition (task@(Invalid _):tasks) plan = (plan ++ [task, Invalid $ "current condition: " ++ show condition], condition)
htn' domain condition (task@(Primitive pTask):tasks) plan = let newCondition = execute domain condition pTask
in htn' domain newCondition tasks $ plan ++ [task]
htn' domain condition (task@(Compound cTask):tasks) plan = let newTasks = breakdown domain condition cTask
in htn' domain condition (newTasks ++ tasks) plan
include :: (Ord a) => [a] -> [a] -> Bool
include cond1 cond2 = null $ cond2 \\ cond1
breakdown :: (PrimitiveTask a, CompoundTask b, Term c) => Domain a b c -> [c] -> b -> [Task a b]
breakdown domain condition task = case M.lookup task (compoundMap domain) of
Nothing -> [Invalid $ "definition is not found for " ++ show task]
Just list -> case find (\(pre, _) -> include condition pre) list of
Just (_, tasks) -> tasks
Nothing -> [Invalid $ "no condition is matched, current: " ++ show condition ++ ", task: " ++ show task]
execute :: (PrimitiveTask a, Term c) => Domain a b c -> [c] -> a -> [c]
execute domain condition task = case M.lookup task (primitiveMap domain) of
Nothing -> []
Just list -> case find (\(pre, _) -> include condition pre) list of
Just (pre, post) -> (condition \\ pre) ++ post
Nothing -> []
|
y-kamiya/ai-samples
|
src/Htn.hs
|
Haskell
|
bsd-3-clause
| 2,970
|
{-# LANGUAGE DefaultSignatures #-}
module Mahjong.Class where
import Foreign.C.Types
-- | Tile describes the properties of a tile.
class Tile a where
suit :: a -> Bool
suit = not . honor
honor :: a -> Bool
simple :: a -> Bool
simple = not . terminal
terminal :: a -> Bool
default terminal :: (Eq a, Bounded a) => a -> Bool
terminal a
| suit a
, a == minBound || a == maxBound = True
| otherwise = False
end :: a -> Bool
end a
| honor a || terminal a = True
| otherwise = False
-- | Enum and Bounded have a law that states that if succ a is equal to the
-- maxBound return an error and thus it's never a good idea to abuse these laws
-- for the type. Cycle on the other hand creates repeating infinite loops, which
-- is useful in the game of Mahjong for things like determining the dora or next
-- seat to be dealer.
--
-- For the use of mahjong these laws must hold:
-- If suit a == True
-- - next (toEnum 9) = (toEnum 1)
-- - prev (toEnum 1) = (toEnum 9)
-- If honor a == True
-- - next (toEnum 4) = (toEnum 1)
-- - prev (toEnum 1) = (toEnum 4)
class Cycle a where
-- | The next tile in the cycle.
next :: a -> a
-- Eq, Enum, and Bounded already define the behavior that we are requesting
-- without breaking the laws.
default next :: (Eq a, Enum a, Bounded a) => a -> a
next a | a == maxBound = minBound
| otherwise = succ a
-- | The previous tile in the cycle
prev :: a -> a
-- Eq, Enum, and Bounded already define the behavior that we are requesting
-- without breaking the laws.
default prev :: (Eq a, Enum a, Bounded a) => a -> a
prev a | a == minBound = maxBound
| otherwise = pred a
-- | Properties of suited tiles.
--
-- Since any suit tile is enumerated between 1-9 you can use type inference to
-- get any suit that you need from. If you have an Enum instance for the type it
-- can also be automatically derived for you.
class Suit a where
one, two, three, four, five, six, seven, eight, nine :: a
default one :: Enum a => a
one = toEnum 1
default two :: Enum a => a
two = toEnum 2
default three :: Enum a => a
three = toEnum 3
default four :: Enum a => a
four = toEnum 4
default five :: Enum a => a
five = toEnum 5
default six :: Enum a => a
six = toEnum 6
default seven :: Enum a => a
seven = toEnum 7
default eight :: Enum a => a
eight = toEnum 8
default nine :: Enum a => a
nine = toEnum 9
instance Suit Int
instance Suit Integer
instance Suit CInt
|
TakSuyu/mahjong
|
src/Mahjong/Class.hs
|
Haskell
|
mit
| 2,511
|
{-# OPTIONS_HADDOCK hide, prune #-}
module Handler.Mooc.FAQ
( getFAQR
) where
import Import
getFAQR :: Handler Html
getFAQR =
fullLayout Nothing "Frequently Asked Questions" $ do
setTitle "Qua-kit: FAQ"
toWidgetBody $
[hamlet|
<div class="row">
<div class="col-lg-8 col-md-9 col-sm-10 col-xs-12">
<div.card.card-red>
<div.card-main>
<div.card-inner>
In September-November 2016 we had the first run of our online course with qua-kit.
At that time we received a number of questions from students regarding the work of the system.
On this page you can find most common of them together with our answers.
Please, try to find an answer to your question here before asking it by mail or via edX platform.
<div class="col-lg-8 col-md-9 col-sm-10 col-xs-12">
<div.card>
<div.card-main>
<div.card-inner>
<ol id="outlineList">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-1>
I want other edX students to see and comment my design proposal!
<div.card-inner>
<p>
This is hard to force unless they want to, right?
<p>
As the first step, we would suggest to de-anonymize yourself
by changing your login name in qua-kit (upper right corner of the site pages).
If you put the same nickname at qua-kit as you have at edX,
it is easier for others to find you.
<p>
Second, try to write an interesting but concise description
of your proposal when submitting/updating a design.
Third, you can copy a direct link to your design submission
and publish it in edX discussion (or somewhere else?).
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-2>
I cannot move/rotate building blocks!
<div.card-inner>
<p>
A. Make sure you get familiar with the controls.
First, hold primary mouse button for panning, hold secondary mouse button (or primary + shift, or primary + ctrl) for rotating.
These rules work for camera and for buildings. To move/rotate a block you first need to click on it (so it becomes red) to activate,
and then drag using mouse to move/rotate.
<p>
B. Something may be wrong with your browser.
Make sure you use the latest version of chrome/firefox/safari (chrome is reported to work best).
If this does not work, we kindly ask you to submit an issue, so we could resolve it as soon as possible
(
<a href="@{FeedbackR}">@{FeedbackR}
).
When you report an issue, please specify following:
<ul>
<li>The browser you use (it will be very helpful if you can find out the version too).
<li>The Operating System (Linux/Windows/Mac?)
<li>Are you using mouse or touchpad?
<li>Are you able to only move or only rotate buildings, or nothing at all? Can you select a building by clicking on it (so it turns red)?
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-3>
I cannot use touchpad!
<div.card-inner>
<p>
Due to the different nature of touchpads on different operating
systems and browsers, it is difficult to make a touchpad behavior persistent across
all of them. Touchpad may work to some extent, but we strongly advise you to use
mouse controls.
<p>
On the other hand, if your screen supports multitouch, you
can move camera and blocks using it - in a much more convenient manner!
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-4>
I cannot see anything!
<div.card-inner>
<p>
Something may be wrong with your browser.
<p>
Make sure you use the latest version of chrome/firefox/safari
(chrome is reported to work best).
<p>
If this does not work, we kindly ask you to submit an issue,
so we could resolve it as soon as possible
(
<a href="@{FeedbackR}">@{FeedbackR}
).
<p>
When you report an issue, please specify following:
<ul>
<li> Which link do you use to start the exercise? Note, at least
for a first time, you must use “Go!” button on the exercise 1 page.
<li> The browser you use (it will be very helpful if you can
find out the version too).
<li> The Operating System (Linux/Windows/Mac?)
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-5>
How do I submit a design solution?
<div.card-inner>
<p>
When working on a design, in lower right corner you should
see a red "tools" button.
If you click on it, you should see a blue "submit" button.
Click on it, and you will see a submit dialog. Enter your
comments about the submission and press "submit" button.
You will be redirected to the main site page, and your design
will be saved.
<p>
You can come back and work on your design by using "menu ->
Work on a design" entry in qua-kit site.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-6>
I still cannot submit my design!
<div.card-inner>
<p>
We kindly ask you to submit an issue, so we could resolve
it as soon as possible
(
<a href="@{FeedbackR}">@{FeedbackR}
).
<p>
Could you please clarify following points? This is important
to find out exactly what your problem was.
<ul>
<li> Which link do you use to start the exercise? Note, at least
for a first time, you must use “Go!” button on the exercise 1 page.
<li> The browser you use (it will be very helpful if you can
find out the version too).
<li> The Operating System (Linux/Windows/Mac?)
<li> Are you able to move/rotate buildings?
<li> Do you have a blue submit button when you click on red
tools button?
<li> You do have a submit button, does the "submit design" dialog
window appear on click?
<li> What happens after you press "submit" in that window?
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-7>
I can only view a design, but not edit or submit it!
<div.card-inner>
<p>
This may happen if you use a wrong link to the editor
(or you are not logged in the system).
<p>
Make sure you use either of two ways:
<ul>
<li> Use a button "Go!" on the exercise page at edX
(it logs you in with edX credentials).
<li> If you are logged in currently (check it at upper left
corner of qua-kit site), you can use "menu" button
(upper left corner) -> "Work on a design".
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-8>
How do I find my submission after uploading it?
<div.card-inner>
<p>
All submissions are listed in the gallery
("menu" -> "Explore submissions"),
though it might be difficult to find your own submission, as there
a lot of them.
<p>
On the other hand, you can always open your design in the
editing mode.
Just go to "menu" near top-left corner of any page at qua-kit
and then click on "work on a design".
Alternatively, you can use the same "Go!"
button as the first time. Both ways redirect you to your last submission.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-9>
Some of my building blocks overlap. Is that ok?
<div.card-inner>
<p>
Yes. Although it is not an explicit feature, it is your decision
to shrink the total area of buildings by overlapping them.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-10>
What do orange lines mean?
<div.card-inner>
<p>
Orange lines are meant as a guidance. They depict surrounding
roads, zones, and buildings.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-11>
Which area should I use for placing building blocks?
<div.card-inner>
<p>
You should use an empty area in the center free of orange lines.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-12>
How can I see rating of my proposal
<div.card-inner>
<p>
You can look it up in the gallery ("menu" -> "Explore submissions").
<p>
Icons and numbers show per-criterion rating on 0-100% scale
(it is not a number of votes).
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-13>
Can I comment others?
<div.card-inner>
<p>
Yes. You can click "view" on a selected submission, then write
a comment in the viewer windows.
<p>
You will also have to put up- or down-vote on a single criterion
for this design.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-14>
How can I see if anybody left a comment on my design?
<div.card-inner>
<p>
Enter an editor mode ("menu" -> "Work on a design"), then
open menu -> control panel (cogwheel icon).
<p>
You can only respond in a form of changing the description
of your submission (when submitting a design update).
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-15>
Do I need to use all blocks provided at qua-kit design
template?
<div.card-inner>
<p>
Yes, you do. There is no way to remove or add a block from
the design.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-16>
Can I update my design after submitting it?
<div.card-inner>
<p>
Yes, you can.
<p>
Just go into an editor mode ("menu" -> "Work on a design")
at qua-kit site and continue your work.
<p>
You can change it as many times as you want until the end
of the course.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-17>
How can I indicate that I have completed the task or I
am still in progress?
<div.card-inner>
<p>
You cannot do so. All submissions are visible to everybody
right after you save them.
Therefore we strongly recommend you to finish the exercise
before the voting task starts (week 6).
At that time, you will vote for submissions of others.
<p>
Nevertheless, you still can update your design until the very
end of the course.
That is, you can respond to comments of other students by
addressing any issues they could have noticed.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-18>
How do I get the grade for the first (design) exercise?
<div.card-inner>
<p>
Right after you submit your design you get 60% of your grade
automatically.
<p>
Then, your design is open for commenting and voting.
In the second exercise other students vote for your designs
and this make a peer-reviewed rating of all designs.
Based on this rating, you get additional 0-40% (worst to best
designs) of your grade.
<p>
Please note, voting is a long process so your grade will not
change immediately.
Instead, it will be updated once a day until the course ends
(to take into account even latest user votes).
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-19>
How do I get the grade for the second (compare-vote) exercise?
<div.card-inner>
<p>
Right after you finish minimum number of comparisons, you
get 60% of your grade automatically.
<p>
Remaning 0-40% you get while others vote: if your comparisons
votes is similar to majority of other votes, your grade gets higher;
if your votes contradict the majority, your grade gets lower.
This is the essence of croud-sourcing approach and citizen
science: majority decides!
<p>
Note, your grade is updated once a day as long as we receive
other votes (to take into account even latest user votes).
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-20>
I have not finished my design, but get (not good) grades!
<div.card-inner>
<p>
This is a common situation. Look which criteria should you
address more, and submit a new, revised version.
<p>
Your old votes get giscounted as new versions of your design
appear.
That is, if you submit a new version and get good responses,
they count more than previous towards your final rating.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-21>
Can I have multiple submissions?
<div.card-inner>
<p>
No, only the last version of your design appears in qua-kit
gallery and is available for voting/grading.
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner>
<h5.h5 style="padding: 80px 0px 0px 0px; margin: -80px 0px 0px 0px;" #question-22>
What happens if I change my nickname at qua-kit?
<div.card-inner>
<p>
Nothing bad. Your design will still be connected to your account.
<p>
Your nickname appears in the submission gallery ("menu" ->
"Explore submissions").
Hence, if you change your nickname to match the one at edX,
it is easier to find and comment your design submission for others.
So, do it! :)
<script>
var newLine, el, ToC = "";
\$("div h5").each(function() {
el = $(this);
ToC +=
"<li style='color: #ff6f00'>" +
"<a href='#" + el.attr("id") + "'>" + el.text() +
"</a>" +
"</li>";
});
\$("#outlineList").html(ToC);
|]
|
achirkin/qua-kit
|
apps/hs/qua-server/src/Handler/Mooc/FAQ.hs
|
Haskell
|
mit
| 22,855
|
{-# LANGUAGE JavaScriptFFI #-}
import qualified GHCJS.Foreign as F
import GHCJS.Types
import GHCJS.Marshal
import GHCJS.Foreign (ToJSString(..), FromJSString(..), newObj, toJSBool, jsNull, jsFalse, jsTrue, mvarRef)
import Control.Concurrent (threadDelay)
import JavaScript.JQuery
import JavaScript.JQuery.Internal
import Data.Text (Text, pack, unpack)
import Control.Applicative
import Data.Maybe
import Control.Monad
import Data.Default
import Protocol (Request (..), Response (..))
main = do
setup
loop
setup = do
playerNameInput <- getElement "#add-player-input"
submitButton <- getElement "#add-player-submit"
click (handleNewPlayerName playerNameInput) def submitButton
handleNewPlayerName element _ = do
name <- getVal element
sendCommand $ AddPlayerRequest (unpack name)
return ()
getElement = select . pack
loop = do
updatePlayerList
threadDelay 1000000
loop
sendCommand :: Request -> IO AjaxResult
sendCommand command = do
os <- toJSRef (def { asMethod = POST } :: AjaxSettings)
jsCommand <- toJSRef $ show command
F.setProp (pack "data") jsCommand os
arr <- jq_ajax (toJSString "command") os
dat <- F.getProp (pack "data") arr
let d = if isNull dat then Nothing else Just (fromJSString dat)
status <- fromMaybe 0 <$> (fromJSRef =<< F.getProp (pack "status") arr)
return (AjaxResult status d)
updatePlayerList = do
result <- sendCommand PlayerListRequest
case arData result of
Nothing -> return ()
Just response -> do
case read $ unpack response of
(PlayerListResponse names) -> do
let nameList = concat $ map wrapLi names
element <- select $ pack "#current-players"
setHtml (pack nameList) element
return ()
_ -> putStrLn "Got an invalid response to command PlayerListRequest"
wrapLi x = "<li>" ++ x ++ "</li>"
|
MichaelBaker/sartorial-client
|
vendor/sartorial-server/vendor/sartorial-client/src/Main.hs
|
Haskell
|
mit
| 1,870
|
import X
(
#if !defined(TESTING)
X
#else
X(..)
#endif
-- f
, f
-- g
, g
, h
)
import Y
|
itchyny/vim-haskell-indent
|
test/module/import_comma_first.in.hs
|
Haskell
|
mit
| 100
|
import Criterion.Main
import Control.Monad.MWC
import Control.Monad.Reader
main :: IO ()
main = do
gen <- createSystemRandom
let wrap name f size
= bench name $ whnfIO $ replicateM_ 10000
$ runReaderT (f size) gen
defaultMain $ flip map [10, 100, 1000, 10000] $ \size -> bgroup (show size)
[ wrap "simple replicateM" uniformAsciiByteStringSimple size
, wrap "complex Word64" uniformAsciiByteStringComplex64 size
]
|
bitemyapp/snoy-extra
|
bench/mwc-bytestring.hs
|
Haskell
|
mit
| 475
|
<?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="hu-HU">
<title>Python Scripting</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>Keresés</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/jython/src/main/javahelp/org/zaproxy/zap/extension/jython/resources/help_hu_HU/helpset_hu_HU.hs
|
Haskell
|
apache-2.0
| 964
|
{- |
Module : Mongo.Pid.Removal
Description : Get Pid from Name
Copyright : (c) Plow Technology 2014
License : MIT
Maintainer : brent.phillips@plowtech.net
Stability : unstable
Portability : portable
<Uses a name to grab the pid to remove old pid alarms from mongo>
-}
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude #-}
import Mongo.Pid.Removal
import BasicPrelude
import Persist.Mongo.Settings
lst :: [Int]
lst = [111,122]
main = do
--conf <- readDBConf "mongoConfig.yml"
--removeMissingAlarms conf lst
|
plow-technologies/mongo-pid-removal
|
src/RemovalMain_flymake.hs
|
Haskell
|
bsd-3-clause
| 550
|
module Typed(
typed,
testPropertyI,
testPropertyD,
testPropertyZ,
testPropertyDZ,
immutableVector,
immutableMatrix,
) where
import Data.Complex( Complex )
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
import Numeric.LinearAlgebra.Vector( Vector )
import Numeric.LinearAlgebra.Matrix( Matrix )
typed :: e -> a e -> a e
typed _ = id
immutableVector :: Vector e -> Vector e
immutableVector = id
immutableMatrix :: Matrix e -> Matrix e
immutableMatrix = id
testPropertyI :: (Testable a)
=> TestName
-> (Int -> a)
-> Test
testPropertyI str prop =
testProperty str $ prop undefined
testPropertyDZ :: (Testable a, Testable b)
=> TestName
-> (Double -> a)
-> (Complex Double -> b)
-> Test
testPropertyDZ str propd propz =
testGroup str
[ testProperty "Double" $ propd undefined
, testProperty "Complex Double" $ propz undefined
]
testPropertyD :: (Testable a)
=> TestName
-> (Double -> a)
-> Test
testPropertyD str prop =
testProperty str $ prop undefined
testPropertyZ :: (Testable a)
=> TestName
-> (Complex Double -> a)
-> Test
testPropertyZ str prop =
testProperty str $ prop undefined
|
patperry/hs-linear-algebra
|
tests/Typed.hs
|
Haskell
|
bsd-3-clause
| 1,420
|
import Sound.Pd
import Control.Concurrent
import Control.Monad
import Linear.Extra
main :: IO ()
main = withPd $ \pd -> do
p1 <- makePatch pd "test/world"
forM_ (pdSources pd) $ \sourceID -> alSourcePosition sourceID ((V3 0 0 0) :: V3 Double)
--_ <- forkIO $ forM_ [200,210..1500] $ \freq -> do
-- send p1 "freq" $ Atom $ Float (freq)
-- threadDelay 100000
_ <- forkIO $ forM_ (map ((*2) . sin) [0,0.01..]) $ \pos -> do
--print $ "Listener now at " ++ show pos
--alListenerPosition ((V3 0 0 (pos*5)) :: V3 Double)
alListenerPosition (V3 0 0 (pos*5) :: V3 Double)
alListenerOrientation ((axisAngle (V3 0 1 0) 0) :: Quaternion Double)
threadDelay 10000
threadDelay 50000000
|
lukexi/pd-haskell
|
test/test-al.hs
|
Haskell
|
bsd-3-clause
| 750
|
--------------------------------------------------------------------------------
-- | Provides URL shortening through the bit.ly API
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Util.BitLy
( shorten
, textAndUrl
) where
--------------------------------------------------------------------------------
import Data.Text (Text)
import qualified Data.Text as T
import Text.XmlHtml
import Text.XmlHtml.Cursor
--------------------------------------------------------------------------------
import NumberSix.Message
import NumberSix.Util
import NumberSix.Util.Http
--------------------------------------------------------------------------------
shorten :: Text -> IO Text
shorten query = do
result <- httpScrape Xml url id $
fmap (nodeText . current) . findRec (byTagName "url")
return $ case result of
Just x -> x
Nothing -> url
where
url = "http://api.bit.ly/v3/shorten?login=jaspervdj" <>
"&apiKey=R_578fb5b17a40fa1f94669c6cba844df1" <>
"&longUrl=" <> urlEncode (httpPrefix query) <>
"&format=xml"
--------------------------------------------------------------------------------
textAndUrl :: Text -> Text -> IO Text
textAndUrl text url
| T.length long <= maxLineLength = return long
| otherwise = do
shortUrl <- shorten url
return $ join text shortUrl
where
join t u = if T.null t then u else t <> " >> " <> u
long = join text url
|
itkovian/number-six
|
src/NumberSix/Util/BitLy.hs
|
Haskell
|
bsd-3-clause
| 1,559
|
{-# LANGUAGE ScopedTypeVariables #-}
-- You can set the following VERBOSE environment variable to control
-- the verbosity of the output generated by this module.
module PackageTests.PackageTester
( PackageSpec(..)
, Success(..)
, Result(..)
-- * Running cabal commands
, cabal_configure
, cabal_build
, cabal_haddock
, cabal_test
, cabal_bench
, cabal_install
, unregister
, compileSetup
, run
-- * Test helpers
, assertConfigureSucceeded
, assertBuildSucceeded
, assertBuildFailed
, assertHaddockSucceeded
, assertTestSucceeded
, assertInstallSucceeded
, assertOutputContains
, assertOutputDoesNotContain
) where
import qualified Control.Exception.Extensible as E
import Control.Monad
import qualified Data.ByteString.Char8 as C
import Data.List
import Data.Maybe
import System.Directory (canonicalizePath, doesFileExist, getCurrentDirectory)
import System.Environment (getEnv)
import System.Exit (ExitCode(ExitSuccess))
import System.FilePath
import System.IO (hIsEOF, hGetChar, hClose)
import System.IO.Error (isDoesNotExistError)
import System.Process (runProcess, waitForProcess)
import Test.Tasty.HUnit (Assertion, assertFailure)
import Distribution.Compat.CreatePipe (createPipe)
import Distribution.Simple.BuildPaths (exeExtension)
import Distribution.Simple.Program.Run (getEffectiveEnvironment)
import Distribution.Simple.Utils (printRawCommandAndArgsAndEnv)
import Distribution.ReadE (readEOrFail)
import Distribution.Verbosity (Verbosity, flagToVerbosity, normal)
data PackageSpec = PackageSpec
{ directory :: FilePath
, distPref :: Maybe FilePath
, configOpts :: [String]
}
data Success = Failure
| ConfigureSuccess
| BuildSuccess
| HaddockSuccess
| InstallSuccess
| TestSuccess
| BenchSuccess
deriving (Eq, Show)
data Result = Result
{ successful :: Bool
, success :: Success
, outputText :: String
} deriving Show
nullResult :: Result
nullResult = Result True Failure ""
------------------------------------------------------------------------
-- * Running cabal commands
recordRun :: (String, ExitCode, String) -> Success -> Result -> Result
recordRun (cmd, exitCode, exeOutput) thisSucc res =
res { successful = successful res && exitCode == ExitSuccess
, success = if exitCode == ExitSuccess then thisSucc
else success res
, outputText =
(if null $ outputText res then "" else outputText res ++ "\n") ++
cmd ++ "\n" ++ exeOutput
}
cabal_configure :: PackageSpec -> FilePath -> IO Result
cabal_configure spec ghcPath = do
res <- doCabalConfigure spec ghcPath
record spec res
return res
doCabalConfigure :: PackageSpec -> FilePath -> IO Result
doCabalConfigure spec ghcPath = do
cleanResult@(_, _, _) <- cabal spec [] ["clean"] ghcPath
requireSuccess cleanResult
res <- cabal spec []
(["configure", "--user", "-w", ghcPath] ++ configOpts spec)
ghcPath
return $ recordRun res ConfigureSuccess nullResult
doCabalBuild :: PackageSpec -> FilePath -> IO Result
doCabalBuild spec ghcPath = do
configResult <- doCabalConfigure spec ghcPath
if successful configResult
then do
res <- cabal spec [] ["build", "-v"] ghcPath
return $ recordRun res BuildSuccess configResult
else
return configResult
cabal_build :: PackageSpec -> FilePath -> IO Result
cabal_build spec ghcPath = do
res <- doCabalBuild spec ghcPath
record spec res
return res
cabal_haddock :: PackageSpec -> [String] -> FilePath -> IO Result
cabal_haddock spec extraArgs ghcPath = do
res <- doCabalHaddock spec extraArgs ghcPath
record spec res
return res
doCabalHaddock :: PackageSpec -> [String] -> FilePath -> IO Result
doCabalHaddock spec extraArgs ghcPath = do
configResult <- doCabalConfigure spec ghcPath
if successful configResult
then do
res <- cabal spec [] ("haddock" : extraArgs) ghcPath
return $ recordRun res HaddockSuccess configResult
else
return configResult
unregister :: String -> FilePath -> IO ()
unregister libraryName ghcPkgPath = do
res@(_, _, output) <- run Nothing ghcPkgPath [] ["unregister", "--user", libraryName]
if "cannot find package" `isInfixOf` output
then return ()
else requireSuccess res
-- | Install this library in the user area
cabal_install :: PackageSpec -> FilePath -> IO Result
cabal_install spec ghcPath = do
buildResult <- doCabalBuild spec ghcPath
res <- if successful buildResult
then do
res <- cabal spec [] ["install"] ghcPath
return $ recordRun res InstallSuccess buildResult
else
return buildResult
record spec res
return res
cabal_test :: PackageSpec -> [(String, Maybe String)] -> [String] -> FilePath -> IO Result
cabal_test spec envOverrides extraArgs ghcPath = do
res <- cabal spec envOverrides ("test" : extraArgs) ghcPath
let r = recordRun res TestSuccess nullResult
record spec r
return r
cabal_bench :: PackageSpec -> [String] -> FilePath -> IO Result
cabal_bench spec extraArgs ghcPath = do
res <- cabal spec [] ("bench" : extraArgs) ghcPath
let r = recordRun res BenchSuccess nullResult
record spec r
return r
compileSetup :: FilePath -> FilePath -> IO ()
compileSetup packageDir ghcPath = do
wd <- getCurrentDirectory
r <- run (Just $ packageDir) ghcPath []
[ "--make"
-- HPC causes trouble -- see #1012
-- , "-fhpc"
, "-package-conf " ++ wd </> "../dist/package.conf.inplace"
, "Setup.hs"
]
requireSuccess r
-- | Returns the command that was issued, the return code, and the output text.
cabal :: PackageSpec -> [(String, Maybe String)] -> [String] -> FilePath -> IO (String, ExitCode, String)
cabal spec envOverrides cabalArgs_ ghcPath = do
let cabalArgs = case distPref spec of
Nothing -> cabalArgs_
Just dist -> ("--builddir=" ++ dist) : cabalArgs_
customSetup <- doesFileExist (directory spec </> "Setup.hs")
if customSetup
then do
compileSetup (directory spec) ghcPath
path <- canonicalizePath $ directory spec </> "Setup"
run (Just $ directory spec) path envOverrides cabalArgs
else do
-- Use shared Setup executable (only for Simple build types).
path <- canonicalizePath "Setup"
run (Just $ directory spec) path envOverrides cabalArgs
-- | Returns the command that was issued, the return code, and the output text
run :: Maybe FilePath -> String -> [(String, Maybe String)] -> [String] -> IO (String, ExitCode, String)
run cwd path envOverrides args = do
verbosity <- getVerbosity
-- path is relative to the current directory; canonicalizePath makes it
-- absolute, so that runProcess will find it even when changing directory.
path' <- do pathExists <- doesFileExist path
canonicalizePath (if pathExists then path else path <.> exeExtension)
menv <- getEffectiveEnvironment envOverrides
printRawCommandAndArgsAndEnv verbosity path' args menv
(readh, writeh) <- createPipe
pid <- runProcess path' args cwd menv Nothing (Just writeh) (Just writeh)
-- fork off a thread to start consuming the output
out <- suckH [] readh
hClose readh
-- wait for the program to terminate
exitcode <- waitForProcess pid
let fullCmd = unwords (path' : args)
return ("\"" ++ fullCmd ++ "\" in " ++ fromMaybe "" cwd, exitcode, out)
where
suckH output h = do
eof <- hIsEOF h
if eof
then return (reverse output)
else do
c <- hGetChar h
suckH (c:output) h
requireSuccess :: (String, ExitCode, String) -> IO ()
requireSuccess (cmd, exitCode, output) =
unless (exitCode == ExitSuccess) $
assertFailure $ "Command " ++ cmd ++ " failed.\n" ++
"output: " ++ output
record :: PackageSpec -> Result -> IO ()
record spec res = do
C.writeFile (directory spec </> "test-log.txt") (C.pack $ outputText res)
------------------------------------------------------------------------
-- * Test helpers
assertConfigureSucceeded :: Result -> Assertion
assertConfigureSucceeded result = unless (successful result) $
assertFailure $
"expected: \'setup configure\' should succeed\n" ++
" output: " ++ outputText result
assertBuildSucceeded :: Result -> Assertion
assertBuildSucceeded result = unless (successful result) $
assertFailure $
"expected: \'setup build\' should succeed\n" ++
" output: " ++ outputText result
assertBuildFailed :: Result -> Assertion
assertBuildFailed result = when (successful result) $
assertFailure $
"expected: \'setup build\' should fail\n" ++
" output: " ++ outputText result
assertHaddockSucceeded :: Result -> Assertion
assertHaddockSucceeded result = unless (successful result) $
assertFailure $
"expected: \'setup haddock\' should succeed\n" ++
" output: " ++ outputText result
assertTestSucceeded :: Result -> Assertion
assertTestSucceeded result = unless (successful result) $
assertFailure $
"expected: \'setup test\' should succeed\n" ++
" output: " ++ outputText result
assertInstallSucceeded :: Result -> Assertion
assertInstallSucceeded result = unless (successful result) $
assertFailure $
"expected: \'setup install\' should succeed\n" ++
" output: " ++ outputText result
assertOutputContains :: String -> Result -> Assertion
assertOutputContains needle result =
unless (needle `isInfixOf` (concatOutput output)) $
assertFailure $
" expected: " ++ needle ++ "\n" ++
" in output: " ++ output ++ ""
where output = outputText result
assertOutputDoesNotContain :: String -> Result -> Assertion
assertOutputDoesNotContain needle result =
when (needle `isInfixOf` (concatOutput output)) $
assertFailure $
"unexpected: " ++ needle ++
" in output: " ++ output
where output = outputText result
-- | Replace line breaks with spaces, correctly handling "\r\n".
concatOutput :: String -> String
concatOutput = unwords . lines . filter ((/=) '\r')
------------------------------------------------------------------------
-- Verbosity
lookupEnv :: String -> IO (Maybe String)
lookupEnv name =
(fmap Just $ getEnv name)
`E.catch` \ (e :: IOError) ->
if isDoesNotExistError e
then return Nothing
else E.throw e
-- TODO: Convert to a "-v" flag instead.
getVerbosity :: IO Verbosity
getVerbosity = do
maybe normal (readEOrFail flagToVerbosity) `fmap` lookupEnv "VERBOSE"
|
corngood/cabal
|
Cabal/tests/PackageTests/PackageTester.hs
|
Haskell
|
bsd-3-clause
| 10,883
|
{-# LANGUAGE PackageImports #-}
module Test17388 where
import "base" Prelude
import {-# Source #-} Foo.Bar
import {-# SOURCE #-} "base" Data.Data
import {-# SOURCE #-} qualified "base" Data.Data
|
sdiehl/ghc
|
testsuite/tests/ghc-api/annotations/Test17388.hs
|
Haskell
|
bsd-3-clause
| 203
|
import System.Exit (ExitCode(..), exitWith)
import System.Posix.Process
import System.Posix.Signals
main = do test1
test2
test3
test4
putStrLn "I'm happy."
test1 = do
-- Force SIGFPE exceptions to not be ignored. Under some
-- circumstances this test will be run with SIGFPE
-- ignored, see #7399
installHandler sigFPE Default Nothing
forkProcess $ raiseSignal floatingPointException
Just (pid, tc) <- getAnyProcessStatus True False
case tc of
Terminated sig _ | sig == floatingPointException -> return ()
_ -> error "unexpected termination cause"
test2 = do
forkProcess $ exitImmediately (ExitFailure 42)
Just (pid, tc) <- getAnyProcessStatus True False
case tc of
Exited (ExitFailure 42) -> return ()
_ -> error "unexpected termination cause (2)"
test3 = do
forkProcess $ exitImmediately ExitSuccess
Just (pid, tc) <- getAnyProcessStatus True False
case tc of
Exited ExitSuccess -> return ()
_ -> error "unexpected termination cause (3)"
test4 = do
forkProcess $ raiseSignal softwareStop
Just (pid, tc) <- getAnyProcessStatus True True
case tc of
Stopped sig | sig == softwareStop -> do
signalProcess killProcess pid
Just (pid, tc) <- getAnyProcessStatus True True
case tc of
Terminated sig _ | sig == killProcess -> return ()
_ -> error "unexpected termination cause (5)"
_ -> error "unexpected termination cause (4)"
|
jimenezrick/unix
|
tests/libposix/posix004.hs
|
Haskell
|
bsd-3-clause
| 1,565
|
module Goo (poop) where
class Zog a where
zoom :: a -> Int
-- Assume the relevant behavior for the method.
{-@ zoom :: (Zog a) => a -> Nat @-}
-- Uses the behavior of `zoom`
{-@ poop :: (Zog a) => a -> Nat @-}
poop x = zoom x
|
mightymoose/liquidhaskell
|
tests/pos/tyclass0.hs
|
Haskell
|
bsd-3-clause
| 231
|
{-# LANGUAGE ScopedTypeVariables #-}
-- !!! Error messages with scoped type variables
module Foo where
data Set a = Set a
unionSetB :: Eq a => Set a -> Set a -> Set a
unionSetB (s1 :: Set a) s2 = unionSets s1 s2
where
unionSets :: Eq a => Set a -> Set a -> Set a
unionSets a b = a
{- In GHC 4.04 this gave the terrible message:
None of the type variable(s) in the constraint `Eq a'
appears in the type `Set a -> Set a -> Set a'
In the type signature for `unionSets'
-}
|
ryantm/ghc
|
testsuite/tests/rename/should_fail/rnfail020.hs
|
Haskell
|
bsd-3-clause
| 492
|
-- !!! an example Simon made up
--
module ShouldSucceed where
f x = (x+1, x<3, g True, g 'c')
where
g y = if x>2 then [] else [y]
{-
Here the type-check of g will yield an LIE with an Ord dict
for x. g still has type forall a. a -> [a]. The dictionary is
free, bound by the x.
It should be ok to add the signature:
-}
f2 x = (x+1, x<3, g2 True, g2 'c')
where
-- NB: this sig:
g2 :: a -> [a]
g2 y = if x>2 then [] else [y]
{-
or to write:
-}
f3 x = (x+1, x<3, g3 True, g3 'c')
where
-- NB: this line:
g3 :: a -> [a]
g3 = (\ y -> if x>2 then [] else [y])::(a -> [a])
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_compile/tc081.hs
|
Haskell
|
bsd-3-clause
| 588
|
{-# LANGUAGE ParallelArrays #-}
{-# OPTIONS -fvectorise #-}
module Types ( Point, Line, points, xsOf, ysOf) where
import Data.Array.Parallel
import Data.Array.Parallel.Prelude.Double
type Point = (Double, Double)
type Line = (Point, Point)
points' :: [:Double:] -> [:Double:] -> [:Point:]
points' = zipP
points :: PArray Double -> PArray Double -> PArray Point
{-# NOINLINE points #-}
points xs ys = toPArrayP (points' (fromPArrayP xs) (fromPArrayP ys))
xsOf' :: [:Point:] -> [:Double:]
xsOf' ps = [: x | (x, _) <- ps :]
xsOf :: PArray Point -> PArray Double
{-# NOINLINE xsOf #-}
xsOf ps = toPArrayP (xsOf' (fromPArrayP ps))
ysOf' :: [:Point:] -> [:Double:]
ysOf' ps = [: y | (_, y) <- ps :]
ysOf :: PArray Point -> PArray Double
{-# NOINLINE ysOf #-}
ysOf ps = toPArrayP (ysOf' (fromPArrayP ps))
|
urbanslug/ghc
|
testsuite/tests/dph/quickhull/Types.hs
|
Haskell
|
bsd-3-clause
| 810
|
module Main where
import C
main = print ("hello world" ++ show (f 42))
|
ghc-android/ghc
|
testsuite/tests/ghci/prog002/D.hs
|
Haskell
|
bsd-3-clause
| 73
|
{-# LANGUAGE LambdaCase #-}
module Oden.Core.Expr where
import Oden.Core.Foreign
import Oden.Identifier
import Oden.Metadata
import Oden.SourceInfo
data NameBinding = NameBinding (Metadata SourceInfo) Identifier
deriving (Show, Eq, Ord)
data FieldInitializer e =
FieldInitializer (Metadata SourceInfo) Identifier e
deriving (Show, Eq, Ord)
data Literal
= Int Integer
| Float Double
| Bool Bool
| String String
| Unit
deriving (Show, Eq, Ord)
data Range e
= Range e e
| RangeTo e
| RangeFrom e
deriving (Show, Eq, Ord)
data Expr r t m
= Symbol (Metadata SourceInfo) Identifier t
| Subscript (Metadata SourceInfo) (Expr r t m) (Expr r t m) t
| Subslice (Metadata SourceInfo) (Expr r t m) (Range (Expr r t m)) t
| Application (Metadata SourceInfo) (Expr r t m) (Expr r t m) t
| NoArgApplication (Metadata SourceInfo) (Expr r t m) t
| ForeignFnApplication (Metadata SourceInfo) (Expr r t m) [Expr r t m] t
| Fn (Metadata SourceInfo) NameBinding (Expr r t m) t
| NoArgFn (Metadata SourceInfo) (Expr r t m) t
| Let (Metadata SourceInfo) NameBinding (Expr r t m) (Expr r t m) t
| Literal (Metadata SourceInfo) Literal t
| Tuple (Metadata SourceInfo) (Expr r t m) (Expr r t m) [Expr r t m] t
| If (Metadata SourceInfo) (Expr r t m) (Expr r t m) (Expr r t m) t
| Slice (Metadata SourceInfo) [Expr r t m] t
| Block (Metadata SourceInfo) [Expr r t m] t
| RecordInitializer (Metadata SourceInfo) [FieldInitializer (Expr r t m)] t
| MemberAccess (Metadata SourceInfo) m t
| MethodReference (Metadata SourceInfo) r t
| Foreign (Metadata SourceInfo) ForeignExpr t
deriving (Show, Eq, Ord)
typeOf :: Expr r t m -> t
typeOf expr = case expr of
Symbol _ _ t -> t
Subscript _ _ _ t -> t
Subslice _ _ _ t -> t
Application _ _ _ t -> t
NoArgApplication _ _ t -> t
ForeignFnApplication _ _ _ t -> t
Fn _ _ _ t -> t
NoArgFn _ _ t -> t
Let _ _ _ _ t -> t
Literal _ _ t -> t
If _ _ _ _ t -> t
Tuple _ _ _ _ t -> t
Slice _ _ t -> t
Block _ _ t -> t
RecordInitializer _ _ t -> t
MemberAccess _ _ t -> t
MethodReference _ _ t -> t
Foreign _ _ t -> t
-- | Applies a mapping function to the type of an expression.
mapType :: (t -> t) -> Expr r t m -> Expr r t m
mapType f = \case
Symbol meta i t -> Symbol meta i (f t)
Subscript meta s i t -> Subscript meta s i (f t)
Subslice meta s r t -> Subslice meta s r (f t)
Application meta func a t -> Application meta func a (f t)
NoArgApplication meta func t -> NoArgApplication meta func (f t)
ForeignFnApplication meta func a t -> ForeignFnApplication meta func a (f t)
Fn meta n b t -> Fn meta n b (f t)
NoArgFn meta b t -> NoArgFn meta b (f t)
Let meta n v b t -> Let meta n v b (f t)
Literal meta l t -> Literal meta l (f t)
If meta c t e t' -> If meta c t e (f t')
Slice meta e t -> Slice meta e (f t)
Tuple meta f' s r t -> Tuple meta f' s r (f t)
Block meta e t -> Block meta e (f t)
RecordInitializer meta vs t -> RecordInitializer meta vs (f t)
MemberAccess meta member t -> MemberAccess meta member (f t)
MethodReference meta ref t -> MethodReference meta ref (f t)
Foreign meta foreign' t -> Foreign meta foreign' (f t)
instance HasSourceInfo (Expr r t m) where
getSourceInfo expr = case expr of
Symbol (Metadata si) _ _ -> si
Subscript (Metadata si) _ _ _ -> si
Subslice (Metadata si) _ _ _ -> si
Application (Metadata si) _ _ _ -> si
NoArgApplication (Metadata si) _ _ -> si
ForeignFnApplication (Metadata si) _ _ _ -> si
Fn (Metadata si) _ _ _ -> si
NoArgFn (Metadata si) _ _ -> si
Let (Metadata si) _ _ _ _ -> si
Literal (Metadata si) _ _ -> si
If (Metadata si) _ _ _ _ -> si
Slice (Metadata si) _ _ -> si
Tuple (Metadata si) _ _ _ _ -> si
Block (Metadata si) _ _ -> si
RecordInitializer (Metadata si) _ _ -> si
MemberAccess (Metadata si) _ _ -> si
MethodReference (Metadata si) _ _ -> si
Foreign (Metadata si) _ _ -> si
setSourceInfo si expr = case expr of
Symbol _ i t -> Symbol (Metadata si) i t
Subscript _ s i t -> Subscript (Metadata si) s i t
Subslice _ s r t -> Subslice (Metadata si) s r t
Application _ f a t -> Application (Metadata si) f a t
NoArgApplication _ f t -> NoArgApplication (Metadata si) f t
ForeignFnApplication _ f a t -> ForeignFnApplication (Metadata si) f a t
Fn _ n b t -> Fn (Metadata si) n b t
NoArgFn _ b t -> NoArgFn (Metadata si) b t
Let _ n v b t -> Let (Metadata si) n v b t
Literal _ l t -> Literal (Metadata si) l t
If _ c t e t' -> If (Metadata si) c t e t'
Slice _ e t -> Slice (Metadata si) e t
Tuple _ f s r t -> Tuple (Metadata si) f s r t
Block _ e t -> Block (Metadata si) e t
RecordInitializer _ t vs -> RecordInitializer (Metadata si) t vs
MemberAccess _ m t -> MemberAccess (Metadata si) m t
MethodReference _ ref t -> MethodReference (Metadata si) ref t
Foreign _ f t -> Foreign (Metadata si) f t
|
oden-lang/oden
|
src/Oden/Core/Expr.hs
|
Haskell
|
mit
| 5,972
|
thousands = [y | z <- [1..1000],
y <- [[x, yy, z] | yy <- [1..1000], let x = (1000 - yy - z), x > 0, x < yy, yy < z]
]
isTriplet :: [Int] -> Bool
isTriplet xs = a^2 + b^2 == c^2
where
a = head xs
b = xs !! 1
c = xs !! 2
problem9 = product $ head [x | x <- thousands, isTriplet x]
|
danhaller/euler-haskell
|
9.hs
|
Haskell
|
mit
| 318
|
{-# LANGUAGE NoMonomorphismRestriction #-}
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
c1 = circle 0.5 # fc steelblue
c2 = circle 1 # fc orange
diagram :: Diagram B
diagram = beside (1 ^& 1) c1 c2 # showOrigin
main = mainWith $ frame 0.1 diagram
|
jeffreyrosenbluth/NYC-meetup
|
meetup/Atop6.hs
|
Haskell
|
mit
| 268
|
mpow :: Int -> Float -> Float
mpow 0 _ = 1
mpow n f = f * (mpow (n-1) f)
main = print (mpow 50 0.5)
|
lucas8/MPSI
|
ipt/recursive/misc/pow.hs
|
Haskell
|
mit
| 103
|
module ChatCore.ChatLog.File
( LogFileId (..)
, logFileForDate
, dayForLogFile
, logFileForToday
, logFileForLine
, logFileName
, parseLogFileId
, logFilesInDir
, ChatLogLine (..)
) where
import Control.Applicative
import Control.Error
import Data.Time
import System.Directory
import System.FilePath
import Text.Parsec
import Text.Printf
import ChatCore.ChatLog.Line
-- | Identifier for log files.
data LogFileId = LogFileId
{ lfDay :: Int
, lfMonth :: Int
, lfYear :: Integer
} deriving (Show, Read, Eq)
instance Ord LogFileId where
a <= b =
(lfYear a <= lfYear b) ||
(lfMonth a <= lfMonth b) ||
(lfDay a <= lfDay b)
-- {{{ Date <-> ID conversions
-- | Gets the log file ID for today.
logFileForToday :: IO LogFileId
logFileForToday = logFileForDate <$> getCurrentTime
-- | Gets the log file ID for the given date.
logFileForDate :: UTCTime -> LogFileId
logFileForDate date = LogFileId day month year
where
(year, month, day) = toGregorian $ utctDay date
-- | Gets the UTCTime day for the given log file.
dayForLogFile :: LogFileId -> Day
dayForLogFile (LogFileId day month year) = fromGregorian year month day
-- | Gets the log file ID that the given line should be written to.
logFileForLine :: ChatLogLine -> LogFileId
logFileForLine = logFileForDate . logLineTime
logFileName :: LogFileId -> String
logFileName l = printf "%04i-%02i-%02i.log" (lfYear l) (lfMonth l) (lfDay l)
-- | Parses a string to a `LogFileId`
parseLogFileId :: String -> Maybe LogFileId
parseLogFileId idStr = hush $ parse parser "Log File ID" idStr
where
parser = do
year <- numSize 4
_ <- char '-'
month <- numSize 2
_ <- char '-'
day <- numSize 2
_ <- string ".log"
return $ LogFileId day month year
-- Read n many digits and parse them as an integer.
numSize n = read <$> count n digit
-- }}}
-- {{{ Listing
-- | Gets a list of log files at the given path.
logFilesInDir :: FilePath -> IO [LogFileId]
logFilesInDir dir =
mapMaybe parseLogFileId <$> map takeFileName <$> getDirectoryContents dir
-- }}}
|
Forkk/ChatCore
|
ChatCore/ChatLog/File.hs
|
Haskell
|
mit
| 2,186
|
{-# LANGUAGE LambdaCase #-}
module Main where
import qualified $module$
import Control.Applicative
import Control.Monad
import Control.Concurrent.Timeout
import Data.Time.Clock.POSIX
import Data.Timeout
import System.IO
import Text.Printf
import Language.Haskell.Liquid.Types (GhcSpec)
import Test.Target
import Test.Target.Monad
import Test.Target.Util
main :: IO ()
main = do
spec <- getSpec "$file$"
withFile "_results/$module$.tsv" WriteMode $ \h -> do
hPutStrLn h "Function\tDepth\tTime(s)\tResult"
mapM_ (checkMany spec h) funs
putStrLn "done"
putStrLn ""
-- checkMany :: GhcSpec -> Handle -> IO [(Int, Double, Outcome)]
checkMany spec h (T f,sp) = putStrNow (printf "Testing %s..\n" sp) >> go 2
where
go 11 = return []
go n = checkAt n >>= \case
(d,Nothing) -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show TimeOut)
putStrLn s >> hFlush stdout
hPutStrLn h s >> hFlush h
return [(n,d,TimeOut)]
--NOTE: ignore counter-examples for the sake of exploring coverage
--(d,Just (Failed s)) -> return [(n,d,Completed (Failed s))]
(d,Just r) -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show (Complete r))
putStrLn s >> hFlush stdout
hPutStrLn h s >> hFlush h
((n,d,Complete r):) <$> go (n+1)
checkAt n = timed $ timeout time $ runGen spec "$file$" $ testFunIgnoringFailure f sp n
time = $timeout$ # Minute
getTime :: IO Double
getTime = realToFrac `fmap` getPOSIXTime
timed x = do start <- getTime
v <- x
end <- getTime
return (end-start, v)
putStrNow s = putStr s >> hFlush stdout
data Outcome = Complete Result
| TimeOut
deriving (Show)
funs = [$funs$]
|
gridaphobe/target
|
bin/CheckFun.template.hs
|
Haskell
|
mit
| 1,970
|
module Codecs.QuickCheck where
import Data.Monoid ((<>))
import Test.Tasty
import Test.QuickCheck
import Test.QuickCheck.Arbitrary
import Test.QuickCheck.Monadic
import Data.Scientific as S
import Data.Time
import Text.Printf
import Data.List as L
import Data.UUID (UUID, fromWords)
import Data.String (IsString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import Database.PostgreSQL.Driver
import Database.PostgreSQL.Protocol.DataRows
import Database.PostgreSQL.Protocol.Types
import Database.PostgreSQL.Protocol.Store.Encode
import Database.PostgreSQL.Protocol.Store.Decode
import qualified Database.PostgreSQL.Protocol.Codecs.Decoders as PD
import qualified Database.PostgreSQL.Protocol.Codecs.Encoders as PE
import qualified Database.PostgreSQL.Protocol.Codecs.PgTypes as PGT
import Connection
import Codecs.Runner
-- | Makes property that if here is a value then encoding and sending it
-- to PostgreSQL, and receiving back returns the same value.
makeCodecProperty
:: (Show a, Eq a, Arbitrary a)
=> Connection
-> Oid -> (a -> Encode) -> PD.FieldDecoder a
-> a -> Property
makeCodecProperty c oid encoder fd v = monadicIO $ do
let q = Query "SELECT $1" [(oid, Just $ encoder v)]
Binary Binary AlwaysCache
decoder = PD.dataRowHeader *> PD.getNonNullable fd
r <- run $ do
sendBatchAndSync c [q]
dr <- readNextData c
waitReadyForQuery c
either (error . show) (pure . decodeOneRow decoder) dr
assertQCEqual v r
-- | Makes a property that encoded value is correctly parsed and printed
-- by PostgreSQL.
makeCodecEncodeProperty
:: Arbitrary a
=> Connection
-> Oid
-> B.ByteString
-> (a -> Encode)
-> (a -> String)
-> a -> Property
makeCodecEncodeProperty c oid queryString encoder fPrint v = monadicIO $ do
let q = Query queryString [(oid, Just $ encoder v)]
Binary Text AlwaysCache
decoder = PD.dataRowHeader *> PD.getNonNullable PD.bytea
r <- run $ do
sendBatchAndSync c [q]
dr <- readNextData c
waitReadyForQuery c
either (error . show) (pure . BC.unpack . decodeOneRow decoder) dr
assertQCEqual (fPrint v) r
assertQCEqual :: (Eq a, Show a, Monad m) => a -> a -> PropertyM m ()
assertQCEqual a b
| a == b = pure ()
| otherwise = fail $
"Equal assertion failed. Expected:\n" <> show a
<> "\nbut got:\n" <> show b
-- | Makes Tasty test tree.
mkCodecTest
:: (Eq a, Arbitrary a, Show a)
=> TestName -> PGT.Oids -> (a -> Encode) -> PD.FieldDecoder a
-> TestTree
mkCodecTest name oids encoder decoder = testPropertyConn name $ \c ->
makeCodecProperty c (PGT.oidType oids) encoder decoder
mkCodecEncodeTest
:: (Arbitrary a, Show a)
=> TestName -> PGT.Oids -> B.ByteString -> (a -> Encode) -> (a -> String)
-> TestTree
mkCodecEncodeTest name oids queryString encoder fPrint =
testPropertyConn name $ \c ->
makeCodecEncodeProperty c (PGT.oidType oids) queryString encoder fPrint
testCodecsEncodeDecode :: TestTree
testCodecsEncodeDecode = testGroup "Codecs property 'encode . decode = id'"
[ mkCodecTest "bool" PGT.bool PE.bool PD.bool
, mkCodecTest "bytea" PGT.bytea PE.bytea PD.bytea
, mkCodecTest "char" PGT.char (PE.char . unAsciiChar)
(fmap AsciiChar <$> PD.char)
, mkCodecTest "date" PGT.date PE.date PD.date
, mkCodecTest "float4" PGT.float4 PE.float4 PD.float4
, mkCodecTest "float8" PGT.float8 PE.float8 PD.float8
, mkCodecTest "int2" PGT.int2 PE.int2 PD.int2
, mkCodecTest "int4" PGT.int4 PE.int4 PD.int4
, mkCodecTest "int8" PGT.int8 PE.int8 PD.int8
, mkCodecTest "interval" PGT.interval PE.interval PD.interval
, mkCodecTest "json" PGT.json (PE.bsJsonText . unJsonString)
(fmap JsonString <$> PD.bsJsonText)
, mkCodecTest "jsonb" PGT.jsonb (PE.bsJsonBytes . unJsonString)
(fmap JsonString <$> PD.bsJsonBytes)
, mkCodecTest "numeric" PGT.numeric PE.numeric PD.numeric
, mkCodecTest "text" PGT.text PE.bsText PD.bsText
, mkCodecTest "time" PGT.time PE.time PD.time
, mkCodecTest "timetz" PGT.timetz PE.timetz PD.timetz
, mkCodecTest "timestamp" PGT.timestamp PE.timestamp PD.timestamp
, mkCodecTest "timestamptz" PGT.timestamptz PE.timestamptz PD.timestamptz
, mkCodecTest "uuid" PGT.uuid PE.uuid PD.uuid
]
testCodecsEncodePrint :: TestTree
testCodecsEncodePrint = testGroup
"Codecs property 'Encoded value Postgres = value in Haskell'"
[ mkCodecEncodeTest "bool" PGT.bool qBasic PE.bool displayBool
, mkCodecEncodeTest "date" PGT.date qBasic PE.date show
, mkCodecEncodeTest "float8" PGT.float8
"SELECT trim(to_char($1, '99999999999990.9999999999'))"
PE.float8 (printf "%.10f")
, mkCodecEncodeTest "int8" PGT.int8 qBasic PE.int8 show
, mkCodecEncodeTest "interval" PGT.interval
"SELECT extract(epoch from $1)||'s'" PE.interval show
, mkCodecEncodeTest "numeric" PGT.numeric qBasic PE.numeric
displayScientific
, mkCodecEncodeTest "timestamp" PGT.timestamp qBasic PE.timestamp show
, mkCodecEncodeTest "timestamptz" PGT.timestamptz
"SELECT ($1 at time zone 'UTC')||' UTC'" PE.timestamptz show
, mkCodecEncodeTest "uuid" PGT.uuid qBasic PE.uuid show
]
where
qBasic = "SELECT $1"
displayScientific s | isInteger s = show $ ceiling s
| otherwise = formatScientific S.Fixed Nothing s
displayBool False = "f"
displayBool True = "t"
--
-- Orphan instances
--
newtype AsciiChar = AsciiChar { unAsciiChar :: Char }
deriving (Show, Eq)
instance Arbitrary AsciiChar where
arbitrary = AsciiChar <$> choose ('\0', '\127')
-- Helper to generate valid json strings
newtype JsonString = JsonString { unJsonString :: B.ByteString }
deriving (Show, Eq, IsString)
instance Arbitrary JsonString where
arbitrary = oneof $ map pure
[ "{}"
, "{\"a\": 5}"
, "{\"b\": [1, 2, 3]}"
]
instance Arbitrary B.ByteString where
arbitrary = do
len <- choose (0, 1024)
B.pack <$> vectorOf len (choose (1, 127))
instance Arbitrary Day where
arbitrary = ModifiedJulianDay <$> choose (-100000, 100000)
instance Arbitrary DiffTime where
arbitrary = secondsToDiffTime <$> choose (0, 86400 - 1)
instance Arbitrary TimeOfDay where
arbitrary = timeToTimeOfDay <$> arbitrary
instance Arbitrary LocalTime where
arbitrary = LocalTime <$> arbitrary <*> fmap timeToTimeOfDay arbitrary
instance Arbitrary UTCTime where
arbitrary = UTCTime <$> arbitrary <*> arbitrary
instance Arbitrary UUID where
arbitrary = fromWords <$> arbitrary <*> arbitrary
<*> arbitrary <*> arbitrary
instance Arbitrary Scientific where
arbitrary = do
c <- choose (-100000000, 100000000)
e <- choose (-10, 10)
pure . normalize $ scientific c e
|
postgres-haskell/postgres-wire
|
tests/Codecs/QuickCheck.hs
|
Haskell
|
mit
| 7,070
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
-- | Defines an Postgresql event store.
module Eventful.Store.Postgresql
( postgresqlEventStoreWriter
, module Eventful.Store.Class
, module Eventful.Store.Sql
) where
import Control.Monad.Reader
import Data.Monoid ((<>))
import Data.Text (Text)
import Database.Persist
import Database.Persist.Sql
import Eventful.Store.Class
import Eventful.Store.Sql
-- | An 'EventStore' that uses a PostgreSQL database as a backend. Use
-- 'SqlEventStoreConfig' to configure this event store.
postgresqlEventStoreWriter
:: (MonadIO m, PersistEntity entity, PersistEntityBackend entity ~ SqlBackend)
=> SqlEventStoreConfig entity serialized
-> VersionedEventStoreWriter (SqlPersistT m) serialized
postgresqlEventStoreWriter config = EventStoreWriter $ transactionalExpectedWriteHelper getLatestVersion storeEvents'
where
getLatestVersion = sqlMaxEventVersion config maxPostgresVersionSql
storeEvents' = sqlStoreEvents config (Just tableLockFunc) maxPostgresVersionSql
maxPostgresVersionSql :: DBName -> DBName -> DBName -> Text
maxPostgresVersionSql (DBName tableName) (DBName uuidFieldName) (DBName versionFieldName) =
"SELECT COALESCE(MAX(" <> versionFieldName <> "), -1) FROM " <> tableName <> " WHERE " <> uuidFieldName <> " = ?"
-- | We need to lock the events table or else our global sequence number might
-- not be monotonically increasing over time from the point of view of a
-- reader.
--
-- For example, say transaction A begins to write an event and the
-- auto-increment key is 1. Then, transaction B starts to insert an event and
-- gets an id of 2. If transaction B is quick and completes, then a listener
-- might see the event from B and thinks it has all the events up to a sequence
-- number of 2. However, once A finishes and the event with the id of 1 is
-- done, then the listener won't know that event exists.
tableLockFunc :: Text -> Text
tableLockFunc tableName = "LOCK " <> tableName <> " IN EXCLUSIVE MODE"
|
jdreaver/eventful
|
eventful-postgresql/src/Eventful/Store/Postgresql.hs
|
Haskell
|
mit
| 2,018
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.MediaError
(pattern MEDIA_ERR_ABORTED, pattern MEDIA_ERR_NETWORK,
pattern MEDIA_ERR_DECODE, pattern MEDIA_ERR_SRC_NOT_SUPPORTED,
pattern MEDIA_ERR_ENCRYPTED, js_getCode, getCode, MediaError,
castToMediaError, gTypeMediaError)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
pattern MEDIA_ERR_ABORTED = 1
pattern MEDIA_ERR_NETWORK = 2
pattern MEDIA_ERR_DECODE = 3
pattern MEDIA_ERR_SRC_NOT_SUPPORTED = 4
pattern MEDIA_ERR_ENCRYPTED = 5
foreign import javascript unsafe "$1[\"code\"]" js_getCode ::
MediaError -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaError.code Mozilla MediaError.code documentation>
getCode :: (MonadIO m) => MediaError -> m Word
getCode self = liftIO (js_getCode (self))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MediaError.hs
|
Haskell
|
mit
| 1,580
|
import GHC.RTS.Events
analyze path analysis =
do logread <- readEventLogFromFile path
print (do log <- logread
return $ analysis log)
isTrace (Event t i) = case i of
(UserMessage x) -> True
_ -> False
dfilter f = foldr ((++) . rfilter) []
where rfilter e@(Event _ i) =
case i of
(EventBlock _ _ es) -> dfilter f es
_ | f e -> [e]
otherwise -> []
listTraces = (dfilter isTrace) . events . dat
matchingMsg m = (filter mtch) . listTraces
where
mtch (Event t ei) = msg ei == m
|
patrickboe/artery
|
Analysis/Trace.hs
|
Haskell
|
mit
| 603
|
module Rebase.Data.Text.IO
(
module Data.Text.IO
)
where
import Data.Text.IO
|
nikita-volkov/rebase
|
library/Rebase/Data/Text/IO.hs
|
Haskell
|
mit
| 80
|
module Eval where
import Control.Monad.Error
import Types
eval :: LispVal -> ThrowsError LispVal
eval val@(String _) = return val
eval val@(Char _) = return val
eval val@(Number _) = return val
eval val@(Float _) = return val
eval val@(Bool _) = return val
eval (List [Atom "quote", val]) = return val
eval (List (Atom func : args)) = mapM eval args >>= apply func
eval badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm
apply :: String -> [LispVal] -> ThrowsError LispVal
apply func args = maybe (throwError $ NotFunction "Unrecognized primitive function args" func)
($ args)
(lookup func primitives)
primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
primitives = [("+", numericBinop (+))
,("-", numericBinop (-))
,("*", numericBinop (*))
,("/", numericBinop div)
,("mod", numericBinop mod)
,("quotient", numericBinop quot)
,("remainder", numericBinop rem)
,("symbol?", return . Bool . isSymbol . head)
,("string?", return . Bool . isString . head)
,("number?", return . Bool . isNumber . head)
]
numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal
numericBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
numericBinop op params = mapM unpackNum params >>= return . Number . foldl1 op
unpackNum :: LispVal -> ThrowsError Integer
unpackNum (Number n) = return n
unpackNum (Float f) = return $ round f
unpackNum (String n) = let parsed = reads n
in if null parsed
then throwError $ TypeMismatch "number" $ String n
else return $ fst $ head parsed
unpackNum (List [n]) = unpackNum n
unpackNum notNum = throwError $ TypeMismatch "number" notNum
isSymbol :: LispVal -> Bool
isSymbol (Atom _) = True
isSymbol _ = False
isString :: LispVal -> Bool
isString (String _) = True
isString _ = False
isNumber :: LispVal -> Bool
isNumber (Number _) = True
isNumber (Float _) = True
isNumber _ = False
|
dstruthers/WYAS
|
Eval.hs
|
Haskell
|
mit
| 2,148
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ConstraintKinds #-}
module App where
import BasePrelude hiding (first)
import Control.Lens
import Control.Monad.Except (ExceptT, MonadError (..), runExceptT)
import Control.Monad.Reader (MonadReader, ReaderT, runReaderT)
import Control.Monad.Trans (MonadIO, liftIO)
import Data.Bifunctor (first)
import Csv
import Db
import Utils
data AppEnv = AppEnv { _appEnvDb :: DbEnv }
makeClassy ''AppEnv
data AppError = AppCsvError CsvError | AppDbError DbError
makeClassyPrisms ''AppError
instance AsDbError AppError where
_DbError = _AppDbError . _DbError
instance AsCsvError AppError where
_CsvError = _AppCsvError . _CsvError
instance HasDbEnv AppEnv where
dbEnv = appEnvDb . dbEnv
type CanApp c e m =
( CanDb c e m
, CanCsv e m
, AsAppError e
, HasAppEnv c
)
loadAndInsert :: CanApp c e m => FilePath -> m [Int]
loadAndInsert p = do
xacts <- readTransactions p
insertTransactions xacts
|
benkolera/talk-stacking-your-monads
|
code-classy/src/App.hs
|
Haskell
|
mit
| 1,163
|
{-# LANGUAGE OverloadedStrings #-}
module Jolly.Parser
( runParseModule
) where
import qualified Data.Text.Lazy as TL
import Text.Megaparsec
import Text.Megaparsec.Char
import qualified Text.Megaparsec.Char.Lexer as L
import Text.Megaparsec.Expr
import Jolly.Syntax
type Parser = Parsec Decl TL.Text
-- Lexer helpers
{-# INLINE sc #-}
sc :: Parser ()
sc = L.space space1 lineCmnt blockCmnt
where
lineCmnt = L.skipLineComment "--"
blockCmnt = L.skipBlockComment "{-" "-}"
{-# INLINE lexeme #-}
lexeme :: Parser a -> Parser a
lexeme = L.lexeme sc
{-# INLINE symbol #-}
symbol :: TL.Text -> Parser TL.Text
symbol = L.symbol sc
-- Combinators
{-# INLINE parens #-}
parens :: Parser a -> Parser a
parens = between (symbol "(") (symbol ")")
-- Primative data types
{-# INLINE integer #-}
integer :: Parser Int
integer = lexeme L.decimal
{-# INLINE boolean #-}
boolean :: Parser Bool
boolean = True <$ reserved "True" <|> False <$ reserved "False"
-- Reserved tokens and identifiers
{-# INLINE reserved #-}
reserved :: TL.Text -> Parser ()
reserved w = string w *> notFollowedBy alphaNumChar *> sc
{-# INLINE rws #-}
rws :: [String]
rws = ["True", "False", "let"]
{-# INLINE identifier #-}
identifier :: Parser Name
identifier = (lexeme . try) (p >>= check)
where
p = (:) <$> letterChar <*> many alphaNumChar
check x =
if x `elem` rws
then fail $ "keyword " ++ show x ++ " cannot be an identifier"
else return x
-- Expressions
expr :: Parser Expr
expr = makeExprParser term operators
operators :: [[Operator Parser Expr]]
operators =
[ [InfixL (Op Mul <$ symbol "*")]
, [InfixL (Op Add <$ symbol "+")]
, [InfixL (Op Sub <$ symbol "-")]
, [InfixL (Op Eql <$ symbol "==")]
]
lambda :: Parser Expr
lambda = do
symbol "\\"
arg <- identifier
symbol "->"
body <- expr
return $ Lam arg body
term :: Parser Expr
term =
aexp >>= \x -> (some aexp >>= \xs -> return (foldl App x xs)) <|> return x
aexp :: Parser Expr
aexp =
parens expr <|> Var <$> identifier <|> lambda <|> Lit . LInt <$> integer <|>
Lit . LBool <$> boolean
type Binding = (String, Expr)
signature :: Parser (Name, [Name], Expr)
signature = do
name <- identifier
args <- many identifier
symbol "="
body <- expr
return (name, args, body)
letdecl :: Parser Binding
letdecl = do
reserved "let"
(name, args, body) <- signature
return (name, foldr Lam body args)
letrecdecl :: Parser Binding
letrecdecl = do
reserved "let"
reserved "rec"
(name, args, body) <- signature
return (name, Fix $ foldr Lam body (name : args))
val :: Parser Binding
val = do
ex <- expr
return ("it", ex)
decl :: Parser Binding
decl = try letrecdecl <|> letdecl <|> val
top :: Parser Binding
top = do
x <- decl
optional (symbol ";")
return x
modl :: Parser [Binding]
modl = many top
runParseModule ::
String -> TL.Text -> Either (ParseError (Token TL.Text) Decl) [Binding]
runParseModule = runParser modl
|
jchildren/jolly
|
src/Jolly/Parser.hs
|
Haskell
|
mit
| 3,014
|
{-# LANGUAGE NoImplicitPrelude #-}
module Chapter14 where
import Chapter8 (recMul)
import Control.Monad (mapM_, return)
import Data.Bool (Bool(False, True), (&&), (||))
import Data.Char (toUpper)
import Data.Eq (Eq, (==), (/=))
import Data.Foldable (concat, foldr)
import Data.Function (id)
import Data.Functor (fmap)
import Data.Int (Int)
import Data.List ((++), length, reverse, sort, take)
import Data.Maybe (Maybe(Nothing, Just))
import Data.Ord (Ord, (>=))
import Data.String (String)
import Data.Tuple (snd)
import Prelude (Double, Fractional, Integer, Num, (.), ($), (^), (*), (/), (+), div, mod, quot, rem)
import System.IO (IO)
import Test.Hspec (describe, hspec, it, shouldBe)
import Test.QuickCheck (Arbitrary, Gen, Property, arbitrary, elements, forAll, frequency, maxSuccess, quickCheck, quickCheckWith, stdArgs, suchThat, verboseCheck)
import Text.Read (read)
import Text.Show (Show, show)
import WordNumber (digits, digitToWord, wordNumber)
--deepCheck = quickCheckWith (stdArgs {maxSuccess = 1000})
{-
Intermission: Short Exercise
In the Chapter Exercises at the end of Recursion, you were given this
exercise:
Write a function that multiplies two numbers using recursive sum-
mation. The type should be (Eq a, Num a) => a -> a -> a although,
depending on how you do it, you might also consider adding an Ord
constraint.
If you still have your answer, great! If not, rewrite it and then
write Hspec tests for it.
The above examples demonstrate the basics of writing individual
tests to test particular values. If you’d like to see a more developed
example, you could refer to Chris’s library, Bloodhound. 3
-}
testRecMul :: IO ()
testRecMul = hspec $ describe "recMul" $ do it "recMul 5 1 is 5" $
recMul 5 1 `shouldBe` 5
it "recMul 5 4 is 20" $
recMul 5 4 `shouldBe` 20
{-
Chapter Exercises
Now it’s time to write some tests of your own. You could write tests
for most of the exercises you’ve done in the book, but whether you’d
want to use Hspec or QuickCheck depends on what you’re trying to
test. We’ve tried to simplify things a bit by telling you which to use
for these exercises, but, as always, we encourage you to experiment
on your own.
Validating numbers into words
Remember the “numbers into words” exercise in Recursion? You’ll
be writing tests to validate the functions you wrote.
main :: IO ()
main = hspec $ do
describe "digitToWord does what we want" $ do
it "returns zero for 0" $ do
digitToWord 0 `shouldBe` "zero"
it "returns one for 1" $ do
print "???"
describe "digits does what we want" $ do
it "returns [1] for 1" $ do
digits 1 `shouldBe` [1]
it "returns [1, 0, 0] for 100" $ do
print "???"
describe "wordNumber does what we want" $ do
it "returns one-zero-zero for 100" $ do
wordNumber 100 `shouldBe` "one-zero-zero"
it "returns nine-zero-zero-one for 9001" $ do
print "???"
Fill in the test cases that print question marks. If you think of
additional tests you could perform, add them.
-}
testHspec :: IO ()
testHspec = hspec $ do
describe "digitToWord does what we want" $ do
it "returns zero for 0" $
digitToWord 0 `shouldBe` "zero"
it "returns one for 1" $
digitToWord 1 `shouldBe` "one"
it "returns two for 2" $
digitToWord 2 `shouldBe` "two"
it "returns three for 3" $
digitToWord 3 `shouldBe` "three"
it "returns four for 4" $
digitToWord 4 `shouldBe` "four"
it "returns five for 5" $
digitToWord 5 `shouldBe` "five"
it "returns six for 6" $
digitToWord 6 `shouldBe` "six"
it "returns seven for 7" $
digitToWord 7 `shouldBe` "seven"
it "returns eight for 8" $
digitToWord 8 `shouldBe` "eight"
it "returns nine for 9" $
digitToWord 9 `shouldBe` "nine"
describe "digits does what we want" $ do
it "returns [1] for 1" $
digits 1 `shouldBe` [1]
it "returns [1, 0, 0] for 100" $
digits 100 `shouldBe` [1, 0, 0]
it "returns [1, 2, 3] for 123" $
digits 123 `shouldBe` [1, 2, 3]
describe "wordNumber does what we want" $ do
it "returns one-zero-zero for 100" $
wordNumber 100 `shouldBe` "one-zero-zero"
it "returns nine-zero-zero-one for 9001" $
wordNumber 9001 `shouldBe` "nine-zero-zero-one"
it "returns one for 1" $
wordNumber 1 `shouldBe` "one"
{-
Using QuickCheck
Test some simple arithmetic properties using QuickCheck.
1.
-- for a function
half x = x / 2
-- this property should hold
halfIdentity = (*2) . half
-}
half :: Fractional a => a -> a
half x = x / 2
genDouble :: Gen Double
genDouble = arbitrary
propHalfIdentity :: Property
propHalfIdentity = forAll gen prop
where gen = genDouble
prop x = x == ((* 2) . half) x
propHalfEqualToPointFive :: Property
propHalfEqualToPointFive = forAll gen prop
where gen = genDouble
prop x = (x * 0.5) == half x
propHalfOneFourth :: Property
propHalfOneFourth = forAll gen prop
where gen = genDouble
prop x = (x * 0.25) == half (half x)
testPropsHalf :: IO ()
testPropsHalf = mapM_ quickCheck [ propHalfIdentity
, propHalfEqualToPointFive
, propHalfOneFourth
]
{-
2.
import Data.List (sort)
-- for any list you apply sort to
-- this property should hold
listOrdered :: (Ord a) => [a] -> Bool
listOrdered xs = snd $ foldr go (Nothing, True) xs
where go _ status@(_, False) = status
go y (Nothing, t) = (Just y, t)
go y (Just x, t) = (Just y, x >= y)
-}
listOrdered :: (Ord a) => [a] -> Bool
listOrdered xs = snd $ foldr go (Nothing, True) xs
where go _ status@(_, False) = status
go y (Nothing, t) = (Just y, t)
go y (Just x, _) = (Just y, x >= y)
genIntList :: Gen [Int]
genIntList = arbitrary
genIntegerList :: Gen [Integer]
genIntegerList = arbitrary
genString :: Gen String
genString = arbitrary
propOrdered :: (Arbitrary a, Ord a, Show a) => Gen [a] -> Property
propOrdered gen = forAll gen prop
where prop xs = listOrdered $ sort xs
testPropOrdered :: IO ()
testPropOrdered = mapM_ quickCheck [ propOrdered genIntList
, propOrdered genIntegerList
, propOrdered genString
]
{-
3.
Now we’ll test the associative and commutative properties of
addition:
plusAssociative x y z = x + (y + z) == (x + y) + z
plusCommutative x y = x + y == y + x
-}
plusAssociative :: (Eq a, Num a) => a -> a -> a -> Bool
plusAssociative x y z = x + (y + z) == (x + y) + z
plusCommutative :: (Eq a, Num a) => a -> a -> Bool
plusCommutative x y = x + y == y + x
gen3Nums :: (Arbitrary a, Num a) => Gen (a, a, a)
gen3Nums = do x <- arbitrary
y <- arbitrary
z <- arbitrary
return (x, y, z)
gen2Nums :: (Arbitrary a, Num a) => Gen (a, a)
gen2Nums = do x <- arbitrary
y <- arbitrary
return (x, y)
gen3Ints :: Gen (Int, Int, Int)
gen3Ints = gen3Nums
gen2Ints :: Gen (Int, Int)
gen2Ints = gen2Nums
propPlusAssociative :: Property
propPlusAssociative = forAll gen prop
where gen = gen3Ints
prop (x, y, z) = plusAssociative x y z
propPlusCommutative :: Property
propPlusCommutative = forAll gen prop
where gen = gen2Ints
prop (x, y) = plusCommutative x y
testAdditionProps :: IO ()
testAdditionProps = mapM_ quickCheck [ propPlusAssociative
, propPlusCommutative
]
{-
4.
Now do the same for multiplication.
-}
multAssociative :: (Eq a, Num a) => a -> a -> a -> Bool
multAssociative x y z = x + (y + z) == (x + y) + z
multCommutative :: (Eq a, Num a) => a -> a -> Bool
multCommutative x y = x + y == y + x
propMultAssociative :: Property
propMultAssociative = forAll gen prop
where gen = gen3Ints
prop (x, y, z) = multAssociative x y z
propMultCommutative :: Property
propMultCommutative = forAll gen prop
where gen = gen2Ints
prop (x, y) = multCommutative x y
testMultProps :: IO ()
testMultProps = mapM_ quickCheck [propMultAssociative, propMultCommutative]
{-
5.
We mentioned in one of the first chapters that there are some
laws involving the relationship of quot and rem and div and mod.
Write QuickCheck tests to prove them.
-- quot rem
(quot x y) * y + (rem x y) == x
(div x y) * y + (mod x y) == x
-}
genInt :: Gen Int
genInt = arbitrary
genIntGteOne :: Gen Int
genIntGteOne = genInt `suchThat` (>= 1)
genNoLessThanOneInt :: Gen (Int, Int)
genNoLessThanOneInt = do x <- genIntGteOne
y <- genIntGteOne
return (x, y)
propQuotRem :: Property
propQuotRem = forAll gen prop
where gen = genNoLessThanOneInt
prop (x, y) = quot x y * y + rem x y == x
propDivMod :: Property
propDivMod = forAll gen prop
where gen = genNoLessThanOneInt
prop (x, y) = div x y * y + mod x y == x
testPropQuotRemDivMod :: IO ()
testPropQuotRemDivMod = mapM_ quickCheck [ propQuotRem
, propDivMod
]
{-
6.
Is (^) associative? Is it commutative? Use QuickCheck to see if
the computer can contradict such an assertion.
-}
propExpAssociative :: Property
propExpAssociative = forAll gen prop
where gen = do x <- genInt
y <- genIntGteOne
z <- genIntGteOne
return (x, y, z)
prop (x, y, z) = x ^ (y ^ z) == (x ^ y) ^ z ||
x ^ (y ^ z) /= (x ^ y) ^ z
propExpCommutative :: Property
propExpCommutative = forAll gen prop
where gen = do x <- genIntGteOne
y <- genIntGteOne
return (x, y)
prop (x, y) = x ^ y == y ^ x || x ^ y /= y ^ x
testPropExp :: IO ()
testPropExp = mapM_ verboseCheck [ propExpAssociative
, propExpCommutative
]
{-
7.
Test that reversing a list twice is the same as the identity of the
list:
reverse . reverse == id
-}
propReverseIdentity :: Property
propReverseIdentity = forAll gen prop
where gen = genIntList
prop xs = (reverse . reverse) xs == id xs
testPropReverse :: IO ()
testPropReverse = mapM_ quickCheck [propReverseIdentity]
{-
8.
Write a property for the definition of ($) and (.).
f $ a = f a
f . g = \x -> f (g x)
-}
propApplyIdentity :: Property
propApplyIdentity = forAll gen prop
where gen = genInt
prop x = id $ x == id x
propComposeIdentity :: Property
propComposeIdentity = forAll gen prop
where gen = genInt
prop x = (id . id) x == id (id x)
testPropApplyAndCompose :: IO ()
testPropApplyAndCompose = mapM_ quickCheck [ propApplyIdentity
, propComposeIdentity
]
{-
9.
See if these two functions are equal:
foldr (:) == (++)
foldr (++) [] == concat
-}
genListIntsInts :: Gen [[Int]]
genListIntsInts = arbitrary
genListInts :: Gen [Int]
genListInts = arbitrary
propFoldrEqual :: Property
propFoldrEqual = forAll gen prop
where gen = do xs <- genListIntsInts
ys <- genListInts
zs <- genListInts
return (xs, ys, zs)
prop (xs, ys, zs) = foldr (++) [] xs == concat xs &&
foldr (:) ys zs == ys ++ zs
{-
10.
Hm. Is that so?
f n xs = length (take n xs) == n
-}
propLengthTake :: Property
propLengthTake = forAll gen prop
where gen = do n <- genInt
xs <- genListInts
return (n, xs)
prop (n, xs) = length (take n xs) == n
testPropLengthTake :: IO ()
testPropLengthTake = quickCheck propLengthTake
{-
11.
Finally, this is a fun one. You may remember we had you com-
pose read and show one time to complete a “round trip.” Well,
now you can test that it works:
f x = (read (show x)) == x
-}
propReadShow :: Property
propReadShow = forAll gen prop
where gen = genInt
prop n = read (show n) == n
{-
Failure
Find out why this property fails.
-- for a function
square x = x * x
-- why does this property not hold? Examine the type of sqrt.
squareIdentity = square . sqrt
Hint: Read about floating point arithmetic and precision if you’re
unfamiliar with it.
=> because of high precision and the large number of decimal places
Idempotence
Idempotence refers to a property of some functions in which the
result value does not change beyond the initial application. If you
apply the function once, it returns a result, and applying the same
function to that value won’t ever change it. You might think of a list
that you sort: once you sort it, the sorted list will remain the same
after applying the same sorting function to it. It’s already sorted, so
new applications of the sort function won’t change it.
Use QuickCheck and the following helper functions to demon-
strate idempotence for the following:
-}
twice :: (a -> a) -> (a -> a)
twice f = f . f
fourTimes :: (a -> a) -> (a -> a)
fourTimes = twice . twice
{-
1. f x = capitalizeWord x == twice capitalizeWord x ==
fourTimes capitalizeWord x
-}
capitalize :: String -> String
capitalize = fmap toUpper
propCapitalizeIdempotence :: Property
propCapitalizeIdempotence = forAll gen prop
where gen = arbitrary :: Gen String
prop s = c1 s && c2 s && c3 s
c1 s = capitalize s == twice capitalize s
c2 s = capitalize s == fourTimes capitalize s
c3 s = twice capitalize s == fourTimes capitalize s
{-
2. f x = sort x == twice sort x == fourTimes sort x
-}
propSortIdempotence :: Property
propSortIdempotence = forAll gen prop
where gen = arbitrary :: Gen String
prop s = c1 s && c2 s && c3 s
c1 s = sort s == twice sort s
c2 s = sort s == fourTimes sort s
c3 s = twice sort s == fourTimes sort s
testPropTwice :: IO ()
testPropTwice = mapM_ verboseCheck [ propCapitalizeIdempotence
, propSortIdempotence
]
{-
Make a Gen random generator for the datatype
We demonstrated in the chapter how to make Gen generators for
different datatypes. We are so certain you enjoyed that, we are going
to ask you to do it for some new datatypes:
1. Equal probabilities for each.
data Fool = Fulse
| Frue
deriving (Eq, Show)
-}
data Fool = Fulse
| Frue
deriving (Eq, Show)
instance Arbitrary Fool where
arbitrary = elements [Fulse, Frue]
{-
2. 2/3s chance of Fulse, 1/3 chance of Frue.
data Fool = Fulse
| Frue
deriving (Eq, Show)
-}
data Fool' = Fulse'
| Frue'
deriving (Eq, Show)
instance Arbitrary Fool' where
arbitrary = frequency [(2, return Fulse'), (1, return Frue')]
{-
Hangman testing
Next, you should go back to the Hangman project from the pre-
vious chapter and write tests. The kinds of tests you can write at
this point will be limited due to the interactive nature of the game.
However, you can test the functions. Focus your attention on testing
the following:
fillInCharacter :: Puzzle -> Char -> Puzzle
fillInCharacter (Puzzle word filledInSoFar s) c =
Puzzle word newFilledInSoFar (c : s)
where zipper guessed wordChar guessChar = if wordChar == guessed
then Just wordChar
else guessChar
newFilledInSoFar = zipWith (zipper c) word filledInSoFar
and:
handleGuess :: Puzzle -> Char -> IO Puzzle
handleGuess puzzle guess = do
putStrLn $ "Your guess was: " ++ [guess]
case (charInWord puzzle guess, alreadyGuessed puzzle guess) of
(_, True) -> do
putStrLn "You already guessed that character, pick something else!"
return puzzle
(True, _) -> do
putStrLn "This character was in the word, filling in the word accordingly"
return (fillInCharacter puzzle guess)
(False, _) -> do
putStrLn "This character wasn't in the word, try again."
return (fillInCharacter puzzle guess)
Refresh your memory on what those are supposed to do and then
test to make sure they do.
-}
|
Numberartificial/workflow
|
haskell-first-principles/haskell-programming-from-first-principles-master/src/Chapter14.hs
|
Haskell
|
mit
| 16,922
|
ans :: [[Int]] -> [Int]
ans ([0]:_) = []
ans ([k]:l:xs) =
let d = k - 1
a = sum l
in
(a`div`d):ans xs
main = do
c <- getContents
let i = map (map read) $ map words $ lines c :: [[Int]]
o = ans i
mapM_ print o
|
a143753/AOJ
|
1027.hs
|
Haskell
|
apache-2.0
| 287
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDial.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.QDial (
QqDial(..)
,notchSize
,notchesVisible
,QsetNotchesVisible(..)
,qDial_delete
,qDial_deleteLater
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QAbstractSlider
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
instance QuserMethod (QDial ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QDial_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QDial_userMethod" qtc_QDial_userMethod :: Ptr (TQDial a) -> CInt -> IO ()
instance QuserMethod (QDialSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QDial_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QDial ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QDial_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QDial_userMethodVariant" qtc_QDial_userMethodVariant :: Ptr (TQDial a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QDialSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QDial_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqDial x1 where
qDial :: x1 -> IO (QDial ())
instance QqDial (()) where
qDial ()
= withQDialResult $
qtc_QDial
foreign import ccall "qtc_QDial" qtc_QDial :: IO (Ptr (TQDial ()))
instance QqDial ((QWidget t1)) where
qDial (x1)
= withQDialResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial1 cobj_x1
foreign import ccall "qtc_QDial1" qtc_QDial1 :: Ptr (TQWidget t1) -> IO (Ptr (TQDial ()))
instance Qevent (QDial ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_event_h" qtc_QDial_event_h :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QDialSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_event_h cobj_x0 cobj_x1
instance QinitStyleOption (QDial ()) ((QStyleOptionSlider t1)) where
initStyleOption x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_initStyleOption cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_initStyleOption" qtc_QDial_initStyleOption :: Ptr (TQDial a) -> Ptr (TQStyleOptionSlider t1) -> IO ()
instance QinitStyleOption (QDialSc a) ((QStyleOptionSlider t1)) where
initStyleOption x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_initStyleOption cobj_x0 cobj_x1
instance QqminimumSizeHint (QDial ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QDial_minimumSizeHint_h" qtc_QDial_minimumSizeHint_h :: Ptr (TQDial a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QDialSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QDial ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QDial_minimumSizeHint_qth_h" qtc_QDial_minimumSizeHint_qth_h :: Ptr (TQDial a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QDialSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QmouseMoveEvent (QDial ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_mouseMoveEvent_h" qtc_QDial_mouseMoveEvent_h :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QDialSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QDial ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_mousePressEvent_h" qtc_QDial_mousePressEvent_h :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QDialSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QDial ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_mouseReleaseEvent_h" qtc_QDial_mouseReleaseEvent_h :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QDialSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseReleaseEvent_h cobj_x0 cobj_x1
notchSize :: QDial a -> (()) -> IO (Int)
notchSize x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_notchSize cobj_x0
foreign import ccall "qtc_QDial_notchSize" qtc_QDial_notchSize :: Ptr (TQDial a) -> IO CInt
instance QnotchTarget (QDial a) (()) where
notchTarget x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_notchTarget cobj_x0
foreign import ccall "qtc_QDial_notchTarget" qtc_QDial_notchTarget :: Ptr (TQDial a) -> IO CDouble
notchesVisible :: QDial a -> (()) -> IO (Bool)
notchesVisible x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_notchesVisible cobj_x0
foreign import ccall "qtc_QDial_notchesVisible" qtc_QDial_notchesVisible :: Ptr (TQDial a) -> IO CBool
instance QpaintEvent (QDial ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_paintEvent_h" qtc_QDial_paintEvent_h :: Ptr (TQDial a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QDialSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_paintEvent_h cobj_x0 cobj_x1
instance QresizeEvent (QDial ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_resizeEvent_h" qtc_QDial_resizeEvent_h :: Ptr (TQDial a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QDialSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_resizeEvent_h cobj_x0 cobj_x1
instance QsetNotchTarget (QDial a) ((Double)) where
setNotchTarget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setNotchTarget cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QDial_setNotchTarget" qtc_QDial_setNotchTarget :: Ptr (TQDial a) -> CDouble -> IO ()
class QsetNotchesVisible x0 x1 where
setNotchesVisible :: x0 -> x1 -> IO ()
instance QsetNotchesVisible (QDial ()) ((Bool)) where
setNotchesVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setNotchesVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_setNotchesVisible_h" qtc_QDial_setNotchesVisible_h :: Ptr (TQDial a) -> CBool -> IO ()
instance QsetNotchesVisible (QDialSc a) ((Bool)) where
setNotchesVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setNotchesVisible_h cobj_x0 (toCBool x1)
instance QsetWrapping (QDial ()) ((Bool)) where
setWrapping x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setWrapping_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_setWrapping_h" qtc_QDial_setWrapping_h :: Ptr (TQDial a) -> CBool -> IO ()
instance QsetWrapping (QDialSc a) ((Bool)) where
setWrapping x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setWrapping_h cobj_x0 (toCBool x1)
instance QqsizeHint (QDial ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sizeHint_h cobj_x0
foreign import ccall "qtc_QDial_sizeHint_h" qtc_QDial_sizeHint_h :: Ptr (TQDial a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QDialSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sizeHint_h cobj_x0
instance QsizeHint (QDial ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QDial_sizeHint_qth_h" qtc_QDial_sizeHint_qth_h :: Ptr (TQDial a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QDialSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QsliderChange (QDial ()) ((SliderChange)) where
sliderChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sliderChange_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QDial_sliderChange_h" qtc_QDial_sliderChange_h :: Ptr (TQDial a) -> CLong -> IO ()
instance QsliderChange (QDialSc a) ((SliderChange)) where
sliderChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sliderChange_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance Qwrapping (QDial a) (()) where
wrapping x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_wrapping cobj_x0
foreign import ccall "qtc_QDial_wrapping" qtc_QDial_wrapping :: Ptr (TQDial a) -> IO CBool
qDial_delete :: QDial a -> IO ()
qDial_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_delete cobj_x0
foreign import ccall "qtc_QDial_delete" qtc_QDial_delete :: Ptr (TQDial a) -> IO ()
qDial_deleteLater :: QDial a -> IO ()
qDial_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_deleteLater cobj_x0
foreign import ccall "qtc_QDial_deleteLater" qtc_QDial_deleteLater :: Ptr (TQDial a) -> IO ()
instance QchangeEvent (QDial ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_changeEvent_h" qtc_QDial_changeEvent_h :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QDialSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_changeEvent_h cobj_x0 cobj_x1
instance QkeyPressEvent (QDial ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_keyPressEvent_h" qtc_QDial_keyPressEvent_h :: Ptr (TQDial a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QDialSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_keyPressEvent_h cobj_x0 cobj_x1
instance QrepeatAction (QDial ()) (()) where
repeatAction x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_repeatAction cobj_x0
foreign import ccall "qtc_QDial_repeatAction" qtc_QDial_repeatAction :: Ptr (TQDial a) -> IO CLong
instance QrepeatAction (QDialSc a) (()) where
repeatAction x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_repeatAction cobj_x0
instance QsetRepeatAction (QDial ()) ((SliderAction)) where
setRepeatAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setRepeatAction cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QDial_setRepeatAction" qtc_QDial_setRepeatAction :: Ptr (TQDial a) -> CLong -> IO ()
instance QsetRepeatAction (QDialSc a) ((SliderAction)) where
setRepeatAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setRepeatAction cobj_x0 (toCLong $ qEnum_toInt x1)
instance QsetRepeatAction (QDial ()) ((SliderAction, Int)) where
setRepeatAction x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setRepeatAction1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCInt x2)
foreign import ccall "qtc_QDial_setRepeatAction1" qtc_QDial_setRepeatAction1 :: Ptr (TQDial a) -> CLong -> CInt -> IO ()
instance QsetRepeatAction (QDialSc a) ((SliderAction, Int)) where
setRepeatAction x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setRepeatAction1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCInt x2)
instance QsetRepeatAction (QDial ()) ((SliderAction, Int, Int)) where
setRepeatAction x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setRepeatAction2 cobj_x0 (toCLong $ qEnum_toInt x1) (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QDial_setRepeatAction2" qtc_QDial_setRepeatAction2 :: Ptr (TQDial a) -> CLong -> CInt -> CInt -> IO ()
instance QsetRepeatAction (QDialSc a) ((SliderAction, Int, Int)) where
setRepeatAction x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setRepeatAction2 cobj_x0 (toCLong $ qEnum_toInt x1) (toCInt x2) (toCInt x3)
instance QtimerEvent (QDial ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_timerEvent" qtc_QDial_timerEvent :: Ptr (TQDial a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QDialSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_timerEvent cobj_x0 cobj_x1
instance QwheelEvent (QDial ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_wheelEvent_h" qtc_QDial_wheelEvent_h :: Ptr (TQDial a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QDialSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_wheelEvent_h cobj_x0 cobj_x1
instance QactionEvent (QDial ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_actionEvent_h" qtc_QDial_actionEvent_h :: Ptr (TQDial a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QDialSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QDial ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_addAction" qtc_QDial_addAction :: Ptr (TQDial a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QDialSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_addAction cobj_x0 cobj_x1
instance QcloseEvent (QDial ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_closeEvent_h" qtc_QDial_closeEvent_h :: Ptr (TQDial a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QDialSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_closeEvent_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QDial ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_contextMenuEvent_h" qtc_QDial_contextMenuEvent_h :: Ptr (TQDial a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QDialSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_contextMenuEvent_h cobj_x0 cobj_x1
instance Qcreate (QDial ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_create cobj_x0
foreign import ccall "qtc_QDial_create" qtc_QDial_create :: Ptr (TQDial a) -> IO ()
instance Qcreate (QDialSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_create cobj_x0
instance Qcreate (QDial ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_create1" qtc_QDial_create1 :: Ptr (TQDial a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QDialSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_create1 cobj_x0 cobj_x1
instance Qcreate (QDial ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QDial_create2" qtc_QDial_create2 :: Ptr (TQDial a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QDialSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QDial ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QDial_create3" qtc_QDial_create3 :: Ptr (TQDial a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QDialSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QDial ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_destroy cobj_x0
foreign import ccall "qtc_QDial_destroy" qtc_QDial_destroy :: Ptr (TQDial a) -> IO ()
instance Qdestroy (QDialSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_destroy cobj_x0
instance Qdestroy (QDial ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_destroy1" qtc_QDial_destroy1 :: Ptr (TQDial a) -> CBool -> IO ()
instance Qdestroy (QDialSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QDial ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QDial_destroy2" qtc_QDial_destroy2 :: Ptr (TQDial a) -> CBool -> CBool -> IO ()
instance Qdestroy (QDialSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QDial ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_devType_h cobj_x0
foreign import ccall "qtc_QDial_devType_h" qtc_QDial_devType_h :: Ptr (TQDial a) -> IO CInt
instance QdevType (QDialSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_devType_h cobj_x0
instance QdragEnterEvent (QDial ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_dragEnterEvent_h" qtc_QDial_dragEnterEvent_h :: Ptr (TQDial a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QDialSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QDial ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_dragLeaveEvent_h" qtc_QDial_dragLeaveEvent_h :: Ptr (TQDial a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QDialSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QDial ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_dragMoveEvent_h" qtc_QDial_dragMoveEvent_h :: Ptr (TQDial a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QDialSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QDial ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_dropEvent_h" qtc_QDial_dropEvent_h :: Ptr (TQDial a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QDialSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QDial ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_enabledChange" qtc_QDial_enabledChange :: Ptr (TQDial a) -> CBool -> IO ()
instance QenabledChange (QDialSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QDial ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_enterEvent_h" qtc_QDial_enterEvent_h :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QDialSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_enterEvent_h cobj_x0 cobj_x1
instance QfocusInEvent (QDial ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_focusInEvent_h" qtc_QDial_focusInEvent_h :: Ptr (TQDial a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QDialSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QDial ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_focusNextChild cobj_x0
foreign import ccall "qtc_QDial_focusNextChild" qtc_QDial_focusNextChild :: Ptr (TQDial a) -> IO CBool
instance QfocusNextChild (QDialSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_focusNextChild cobj_x0
instance QfocusNextPrevChild (QDial ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_focusNextPrevChild" qtc_QDial_focusNextPrevChild :: Ptr (TQDial a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QDialSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QDial ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_focusOutEvent_h" qtc_QDial_focusOutEvent_h :: Ptr (TQDial a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QDialSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_focusOutEvent_h cobj_x0 cobj_x1
instance QfocusPreviousChild (QDial ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_focusPreviousChild cobj_x0
foreign import ccall "qtc_QDial_focusPreviousChild" qtc_QDial_focusPreviousChild :: Ptr (TQDial a) -> IO CBool
instance QfocusPreviousChild (QDialSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_focusPreviousChild cobj_x0
instance QfontChange (QDial ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_fontChange" qtc_QDial_fontChange :: Ptr (TQDial a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QDialSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QDial ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QDial_heightForWidth_h" qtc_QDial_heightForWidth_h :: Ptr (TQDial a) -> CInt -> IO CInt
instance QheightForWidth (QDialSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QDial ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_hideEvent_h" qtc_QDial_hideEvent_h :: Ptr (TQDial a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QDialSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_hideEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QDial ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_inputMethodEvent" qtc_QDial_inputMethodEvent :: Ptr (TQDial a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QDialSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QDial ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QDial_inputMethodQuery_h" qtc_QDial_inputMethodQuery_h :: Ptr (TQDial a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QDialSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyReleaseEvent (QDial ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_keyReleaseEvent_h" qtc_QDial_keyReleaseEvent_h :: Ptr (TQDial a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QDialSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QDial ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_languageChange cobj_x0
foreign import ccall "qtc_QDial_languageChange" qtc_QDial_languageChange :: Ptr (TQDial a) -> IO ()
instance QlanguageChange (QDialSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_languageChange cobj_x0
instance QleaveEvent (QDial ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_leaveEvent_h" qtc_QDial_leaveEvent_h :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QDialSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QDial ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QDial_metric" qtc_QDial_metric :: Ptr (TQDial a) -> CLong -> IO CInt
instance Qmetric (QDialSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance QmouseDoubleClickEvent (QDial ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_mouseDoubleClickEvent_h" qtc_QDial_mouseDoubleClickEvent_h :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QDialSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance Qmove (QDial ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QDial_move1" qtc_QDial_move1 :: Ptr (TQDial a) -> CInt -> CInt -> IO ()
instance Qmove (QDialSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QDial ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QDial_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QDial_move_qth" qtc_QDial_move_qth :: Ptr (TQDial a) -> CInt -> CInt -> IO ()
instance Qmove (QDialSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QDial_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QDial ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_move cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_move" qtc_QDial_move :: Ptr (TQDial a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QDialSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_move cobj_x0 cobj_x1
instance QmoveEvent (QDial ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_moveEvent_h" qtc_QDial_moveEvent_h :: Ptr (TQDial a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QDialSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QDial ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_paintEngine_h cobj_x0
foreign import ccall "qtc_QDial_paintEngine_h" qtc_QDial_paintEngine_h :: Ptr (TQDial a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QDialSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_paintEngine_h cobj_x0
instance QpaletteChange (QDial ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_paletteChange" qtc_QDial_paletteChange :: Ptr (TQDial a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QDialSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QDial ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_repaint cobj_x0
foreign import ccall "qtc_QDial_repaint" qtc_QDial_repaint :: Ptr (TQDial a) -> IO ()
instance Qrepaint (QDialSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_repaint cobj_x0
instance Qrepaint (QDial ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QDial_repaint2" qtc_QDial_repaint2 :: Ptr (TQDial a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QDialSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QDial ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_repaint1" qtc_QDial_repaint1 :: Ptr (TQDial a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QDialSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QDial ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_resetInputContext cobj_x0
foreign import ccall "qtc_QDial_resetInputContext" qtc_QDial_resetInputContext :: Ptr (TQDial a) -> IO ()
instance QresetInputContext (QDialSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_resetInputContext cobj_x0
instance Qresize (QDial ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QDial_resize1" qtc_QDial_resize1 :: Ptr (TQDial a) -> CInt -> CInt -> IO ()
instance Qresize (QDialSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QDial ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_resize" qtc_QDial_resize :: Ptr (TQDial a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QDialSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_resize cobj_x0 cobj_x1
instance Qresize (QDial ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QDial_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QDial_resize_qth" qtc_QDial_resize_qth :: Ptr (TQDial a) -> CInt -> CInt -> IO ()
instance Qresize (QDialSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QDial_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QsetGeometry (QDial ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QDial_setGeometry1" qtc_QDial_setGeometry1 :: Ptr (TQDial a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QDialSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QDial ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_setGeometry" qtc_QDial_setGeometry :: Ptr (TQDial a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QDialSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QDial ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QDial_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QDial_setGeometry_qth" qtc_QDial_setGeometry_qth :: Ptr (TQDial a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QDialSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QDial_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QDial ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_setMouseTracking" qtc_QDial_setMouseTracking :: Ptr (TQDial a) -> CBool -> IO ()
instance QsetMouseTracking (QDialSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setMouseTracking cobj_x0 (toCBool x1)
instance QsetVisible (QDial ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_setVisible_h" qtc_QDial_setVisible_h :: Ptr (TQDial a) -> CBool -> IO ()
instance QsetVisible (QDialSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QDial ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_showEvent_h" qtc_QDial_showEvent_h :: Ptr (TQDial a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QDialSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_showEvent_h cobj_x0 cobj_x1
instance QtabletEvent (QDial ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_tabletEvent_h" qtc_QDial_tabletEvent_h :: Ptr (TQDial a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QDialSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QDial ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_updateMicroFocus cobj_x0
foreign import ccall "qtc_QDial_updateMicroFocus" qtc_QDial_updateMicroFocus :: Ptr (TQDial a) -> IO ()
instance QupdateMicroFocus (QDialSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_updateMicroFocus cobj_x0
instance QwindowActivationChange (QDial ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDial_windowActivationChange" qtc_QDial_windowActivationChange :: Ptr (TQDial a) -> CBool -> IO ()
instance QwindowActivationChange (QDialSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QDial ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_childEvent" qtc_QDial_childEvent :: Ptr (TQDial a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QDialSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QDial ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDial_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QDial_connectNotify" qtc_QDial_connectNotify :: Ptr (TQDial a) -> CWString -> IO ()
instance QconnectNotify (QDialSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDial_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QDial ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDial_customEvent" qtc_QDial_customEvent :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QDialSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDial_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QDial ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDial_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QDial_disconnectNotify" qtc_QDial_disconnectNotify :: Ptr (TQDial a) -> CWString -> IO ()
instance QdisconnectNotify (QDialSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDial_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QDial ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDial_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QDial_eventFilter_h" qtc_QDial_eventFilter_h :: Ptr (TQDial a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QDialSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDial_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QDial ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDial_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QDial_receivers" qtc_QDial_receivers :: Ptr (TQDial a) -> CWString -> IO CInt
instance Qreceivers (QDialSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDial_receivers cobj_x0 cstr_x1
instance Qsender (QDial ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sender cobj_x0
foreign import ccall "qtc_QDial_sender" qtc_QDial_sender :: Ptr (TQDial a) -> IO (Ptr (TQObject ()))
instance Qsender (QDialSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDial_sender cobj_x0
|
uduki/hsQt
|
Qtc/Gui/QDial.hs
|
Haskell
|
bsd-2-clause
| 45,334
|
{-# LANGUAGE OverloadedStrings #-}
module Config (AppConfig(..), config, defaultConfig)
where
import qualified Data.Configurator as C
import Data.Configurator.Types
import Control.Exception (catch)
import Data.Text (unpack)
import Options
data AppOptions = AppOptions {
configPath :: String
}
data AppConfig = AppConfig {
repositoryPath :: String,
repositoryBaseUrl :: String,
rsyncBasePath :: String,
snapshotSyncPeriod :: Int,
oldDataRetainPeriod :: Int,
appPort :: Int,
rsyncRepoMap :: [(String, String)]
} deriving (Show)
defaultConfig :: AppConfig
defaultConfig = AppConfig {
repositoryPath = "./test-repo/rrdp",
repositoryBaseUrl = "http://localhost:19999/test-repo",
rsyncBasePath = "./test-repo",
snapshotSyncPeriod = 10,
oldDataRetainPeriod = 3600,
appPort = 19999,
rsyncRepoMap = [("rsync://test.url/", "test.url")]
}
config :: AppOptions -> IO (Either String AppConfig)
config (AppOptions confPath) = readConfig `catch` catchError
where
readConfig = do
conf <- C.load [C.Required confPath]
port <- C.lookupDefault 19999 conf "port"
repoPath <- C.require conf "repository.rrdpPath"
repoBaseUrl <- C.require conf "repository.baseUrl"
rsyncPath <- C.require conf "repository.rsync.basePath"
urlMapping <- C.require conf "repository.rsync.urlMapping"
syncPeriod <- C.lookupDefault 10 conf "snaphotSyncPeriod"
retainPeriod <- C.lookupDefault 3600 conf "oldDataRetainPeriod"
return $ Right AppConfig {
repositoryPath = repoPath,
repositoryBaseUrl = repoBaseUrl,
rsyncBasePath = rsyncPath,
snapshotSyncPeriod = syncPeriod,
oldDataRetainPeriod = retainPeriod,
appPort = port,
rsyncRepoMap = urlMapping
}
catchError :: KeyError -> IO (Either String AppConfig)
catchError (KeyError key) = return $ Left $ unpack key ++ " must be defined"
instance Options AppOptions where
defineOptions = pure AppOptions
<*> simpleOption "config-path" "rpki-pub-server.conf" "Path to the config file"
|
lolepezy/rpki-pub-server
|
src/Config.hs
|
Haskell
|
bsd-2-clause
| 2,204
|
module Raven.ParserSpec ( spec ) where
import Test.Tasty.Hspec
import Test.QuickCheck
import Test.Hspec.Megaparsec
import Text.Megaparsec hiding (parse, string)
import Raven.Types
import Raven.Parser
spec :: Spec
spec = describe "Parser" $ do
describe "parsing bools" $ do
it "should be able to parse true and false" $ do
parse bool "true" `shouldParse` (RavenLiteral $ RavenBool True)
parse bool "false" `shouldParse` (RavenLiteral $ RavenBool False)
it "should fail to parse invalid input" $ do
parse bool `shouldFailOn` "truf"
parse bool `shouldFailOn` "fals"
parse bool `shouldFailOn` ""
parse bool `shouldFailOn` " "
describe "parsing strings" $ do
it "should be able to parse valid strings" $ do
let checkStr a b = parse string a `shouldParse` (RavenLiteral $ RavenString b)
checkStr "\"\"" ""
checkStr "\"a\"" "a"
checkStr "\"ab\"" "ab"
checkStr "\"a b\"" "a b"
checkStr "\"a b\"" "a b"
it "should be able to parse escape characters" $ do
let checkStr a b = parse string a `shouldParse` (RavenLiteral $ RavenString b)
checkStr "\"a\r\n\t\b\v\\\'b\"" "a\r\n\t\b\v\\\'b"
it "should fail to parse invalid input" $ do
let checkFailStr a = parse string `shouldFailOn` a
checkFailStr ""
checkFailStr "\""
checkFailStr "\"a"
checkFailStr "a\""
describe "parsing comments" $ do
it "should be able to parse valid comments" $ do
parse number "1 ; comment\n" `shouldParse` (RavenLiteral . RavenNumber $ RavenIntegral 1)
parse define "(def a ; comment goes here\n 3)" `shouldParse` (RavenDefine "a" (RavenLiteral . RavenNumber $ RavenIntegral 3))
parse number "1 ;; more comments\n" `shouldParse` (RavenLiteral . RavenNumber $ RavenIntegral 1)
describe "parsing identifiers" $ do
it "should be able to parse valid identifiers" $ do
let checkIdent a = parse identifier a `shouldParse` a
checkIdent "lambda"
checkIdent "list->vector"
checkIdent "+"
checkIdent "<=?"
checkIdent "the-word-recursion-has-many-meanings"
checkIdent "q"
checkIdent "soup"
checkIdent "V17a"
checkIdent "a34kTMNs"
checkIdent "-"
checkIdent "..."
checkIdent "a!$%&*+-./:<=>?@^_~"
it "should fail to parse invalid identifiers" $ do
let checkFailIdent a = parse identifier `shouldFailOn` a
checkFailIdent "1"
checkFailIdent "1.0a"
checkFailIdent "."
checkFailIdent ".."
describe "parsing symbols" $ do
it "should be able to parse valid symbols" $ do
let checkSymbol a b = parse symbol a `shouldParse` (RavenLiteral $ RavenSymbol b)
checkSymbol "'a" "a"
checkSymbol "'ab" "ab"
checkSymbol "'a1" "a1"
checkSymbol "'a+-.*/<=>!?$%_&^~" "a+-.*/<=>!?$%_&^~"
it "should fail to parse invalid symbols" $ do
let checkFailSymbol a = parse symbol `shouldFailOn` a
checkFailSymbol "1"
checkFailSymbol "1a"
checkFailSymbol "1\n"
checkFailSymbol "!"
describe "parsing variables" $ do
it "should be able to parse valid variables" $ do
let checkVar a b = parse variable a `shouldParse` (RavenVariable b)
checkVar "a" "a"
checkVar "a123" "a123"
it "should fail to parse invalid variables" $ do
let checkFailVar a = parse variable `shouldFailOn` a
checkFailVar "lambda"
checkFailVar "true"
checkFailVar "def"
-- TODO check remaining keywords
describe "parsing numbers" $ do
it "should be able to parse (positive) decimal numbers" $ do
let checkInt a b = parse number a `shouldParse` (RavenLiteral . RavenNumber . RavenIntegral $ b)
checkInt "0" 0
checkInt "1" 1
checkInt "2" 2
checkInt "11" 11
-- NOTE: negative integers are represented as (- X) -> handled with a different parser
it "should fail to parse invalid decimal numbers" $ do
let checkFailInt a = parse number `shouldFailOn` a
checkFailInt "-0"
checkFailInt "-1"
checkFailInt "a1"
it "should be able to parse hexadecimal numbers" $ do
let checkHex a b = parse number a `shouldParse` (RavenLiteral . RavenNumber . RavenIntegral $ b)
checkHex "0x0" 0
checkHex "0x1" 1
checkHex "0x2" 2
checkHex "0xa" 0x0A
checkHex "0xf" 0x0F
checkHex "0xA" 0x0A
checkHex "0x0F" 0x0F
checkHex "0xFF" 0xFF
it "should fail to parse invalid hexadecimal numbers" $ do
let checkFailHex a = parse number `shouldFailOn` a
checkFailHex "0x"
checkFailHex "0x 0"
checkFailHex "0xG"
checkFailHex "0x.1"
--checkFailHex "0x1.0"
--checkFailHex "0x0.1"
it "should be able to parse binary numbers" $ do
let checkBin a b = parse number a `shouldParse` (RavenLiteral . RavenNumber . RavenIntegral $ b)
checkBin "0b0" 0
checkBin "0b1" 1
checkBin "0b01" 1
checkBin "0b10" 2
checkBin "0b11" 3
checkBin "0b1000" 8
it "should fail to parse invalid binary numbers" $ do
let checkFailBin a = parse number `shouldFailOn` a
checkFailBin "0b"
checkFailBin "0b 0"
checkFailBin "0b2"
checkFailBin "0b.1"
--checkFailBin "0b1.0"
it "should be able to parse rational numbers" $ do
let checkRat a b c = parse number a `shouldParse` (RavenLiteral . RavenNumber $ RavenRational b c)
checkRat "0/1" 0 1
checkRat "1/1" 1 1
checkRat "1/2" 1 2
checkRat "3/2" 3 2
checkRat "-3/2" (negate 3) 2
--it "should fail to parse invalid rational numbers" $ do
--let checkFailRat a = parse number `shouldFailOn` a
--checkFailRat "0.1/1"
--checkFailRat "1i/1"
--checkFailRat "1 / 1"
--checkFailRat "1/ 1"
--checkFailRat "1 /1"
it "should be able to parse real (floating point) numbers" $ do
let checkDouble a b = parse number a `shouldParse` (RavenLiteral . RavenNumber . RavenReal $ b)
checkDouble "0.0" 0.0
checkDouble "0.1" 0.1
checkDouble "1.1" 1.1
checkDouble "1e3" 1000
checkDouble "1e-3" 0.001
-- NOTE: negative floats not checked here, represented as (- F)
it "should fail to parse invalid real (floating point) numbers" $ do
let checkFailDouble a = parse number `shouldFailOn` a
checkFailDouble ".1"
checkFailDouble "a.1"
checkFailDouble ".a1"
checkFailDouble "-1e3"
it "should be able to parse complex numbers" $ do
let checkComplex a b c = parse number a `shouldParse` (RavenLiteral . RavenNumber $ RavenComplex b c)
let checkComplexI a b = checkComplex a 0 b
checkComplexI "0i" 0
checkComplexI "0.1i" 0.1
checkComplexI "1i" 1
checkComplex "1+1i" 1 1
checkComplex "1+0.1i" 1 0.1
checkComplex "0.1+0.1i" 0.1 0.1
checkComplex "0.1-0.1i" 0.1 (negate 0.1)
checkComplex "-0.1-0.1i" (negate 0.1) (negate 0.1)
it "should fail to parse invalid complex numbers" $ do
let checkFailComplex a = parse number `shouldFailOn` a
checkFailComplex "i"
checkFailComplex "ai"
checkFailComplex ".1i"
--checkFailComplex "1*1i"
--checkFailComplex "1/1i"
--checkFailComplex "0.1e3i"
describe "parsing defines" $ do
it "should be able to parse a valid define expression (no procedure)" $ do
let checkDefine a b c = parse define a `shouldParse` RavenDefine b c
checkDefine "(def a 3)" "a" (RavenLiteral . RavenNumber . RavenIntegral $ 3)
checkDefine "(def b \"test\")" "b" (RavenLiteral . RavenString $ "test")
checkDefine "(def a true)" "a" (RavenLiteral . RavenBool $ True)
it "should be able to parse funcions defined with 'def'" $ do
let makeFuncDef b c d = RavenDefine b (RavenFunction $ Function c d)
let checkDefine a b c d = parse define a `shouldParse` (makeFuncDef b c d)
let int = RavenLiteral . RavenNumber . RavenIntegral
let var = RavenVariable
let func a b c = RavenFunctionCall (var a) [var b, var c]
checkDefine "(def (test-func) 1)" "test-func" [] [int 1]
checkDefine "(def (test-func a) a)" "test-func" ["a"] [var "a"]
checkDefine "(def (test-func a b) a)" "test-func" ["a", "b"] [var "a"]
checkDefine "(def (test-func a b) (+ a b))" "test-func" ["a", "b"] [func "+" "a" "b"]
it "should fail to parse invalid define expression" $ do
let checkFailDefine a = parse define `shouldFailOn` a
checkFailDefine "def a 3"
checkFailDefine "(ef a 3)"
checkFailDefine "(def a)"
checkFailDefine "(def 3)"
checkFailDefine "(def true false)"
checkFailDefine "(def (test-func 1)"
checkFailDefine "(def test-func) 1)"
checkFailDefine "(def () 1)"
describe "parsing function calls" $ do
it "should be able to parse valid function calls" $ do
let checkFunc a b c = parse functionCall a `shouldParse` (RavenFunctionCall b c)
let op = RavenVariable -- TODO this should return a procedure/function
let int = RavenLiteral . RavenNumber . RavenIntegral
checkFunc "(test-func)" (op "test-func") []
checkFunc "(print \"test123\")" (op "print") [RavenLiteral . RavenString $ "test123"]
checkFunc "(+ 1 2)" (op "+") (map int [1, 2])
checkFunc "(- 1 2 3)" (op "-") (map int [1, 2, 3])
it "should fail to parse invalid function call syntax" $ do
let checkFailFunc a = parse functionCall `shouldFailOn` a
checkFailFunc "()"
checkFailFunc "(test-func"
checkFailFunc "test-func)"
describe "parsing lambdas" $ do
it "should be able to parse valid lambdas" $ do
let checkFunc a b c = parse lambda a `shouldParse` (RavenFunction $ Function b c)
let var = RavenVariable
let int = RavenLiteral . RavenNumber . RavenIntegral
let func a b = RavenFunctionCall (RavenVariable a) b -- TODO this should be a procedure
checkFunc "(lambda () 1)" [] [int 1]
checkFunc "(lambda (a) a)" ["a"] [var "a"]
checkFunc "(lambda (a) (test-func) (test-func2))" ["a"] [ func "test-func" []
, func "test-func2" []
]
checkFunc "(lambda (a b) (+ a b))" ["a", "b"] [func "+" [var "a", var "b"]]
it "should fail to parse invalid lambda syntax" $ do
let checkFailFunc a = parse lambda `shouldFailOn` a
checkFailFunc "(lambd () 1)"
checkFailFunc "(lambda 1)"
checkFailFunc "(lambda ( 1)"
checkFailFunc "(lambda ())"
describe "parsing and expressions" $ do
it "should be able to parse valid and expressions" $ do
let checkAnd a b = parse andExpr a `shouldParse` (RavenAnd $ And b)
let boolean = RavenLiteral . RavenBool
let int = RavenLiteral . RavenNumber . RavenIntegral
let func a b = RavenFunctionCall (RavenVariable a) b -- TODO this should be a procedure
checkAnd "(and)" []
checkAnd "(and true)" [boolean True]
checkAnd "(and true true)" [boolean True, boolean True]
checkAnd "(and true 1)" [boolean True, int 1]
checkAnd "(and true (+ 1 2))" [boolean True, func "+" [int 1, int 2]]
it "should fail to parse invalid and expressions" $ do
let checkFailAnd a = parse andExpr `shouldFailOn` a
checkFailAnd "(nd)"
checkFailAnd "(and"
checkFailAnd "and)"
describe "parsing or expressions" $ do
it "should be able to parse valid or expressions" $ do
let checkAnd a b = parse orExpr a `shouldParse` (RavenOr $ Or b)
let boolean = RavenLiteral . RavenBool
let int = RavenLiteral . RavenNumber . RavenIntegral
let func a b = RavenFunctionCall (RavenVariable a) b -- TODO this should be a procedure
checkAnd "(or)" []
checkAnd "(or true)" [boolean True]
checkAnd "(or true true)" [boolean True, boolean True]
checkAnd "(or true 1)" [boolean True, int 1]
checkAnd "(or true (+ 1 2))" [boolean True, func "+" [int 1, int 2]]
it "should fail to parse invalid or expressions" $ do
let checkFailAnd a = parse orExpr `shouldFailOn` a
checkFailAnd "(r)"
checkFailAnd "(or"
checkFailAnd "or)"
describe "parsing begin expressions" $ do
it "should be able to parse valid begin expressions" $ do
let checkBegin a b = parse begin a `shouldParse` (RavenBegin $ Begin b)
let func a b = RavenFunctionCall (RavenVariable a) b
let int = RavenLiteral . RavenNumber . RavenIntegral
checkBegin "(begin (f1))" [func "f1" []]
checkBegin "(begin (f1) (f2))" [func "f1" [], func "f2" []]
checkBegin "(begin 1 (f1))" [int 1, func "f1" []]
checkBegin "(begin (f1) 1)" [func "f1" [], int 1]
it "should fail to parse invalid begin expressions" $ do
let checkFailBegin a = parse begin `shouldFailOn` a
checkFailBegin "(begi)"
checkFailBegin "(begin)"
checkFailBegin "(begin ())"
describe "parsing assignments" $ do
it "should be possible to parse valid assignment expressions" $ do
let int = RavenLiteral . RavenNumber . RavenIntegral
let str = RavenLiteral . RavenString
let checkAssign a b c = parse assignment a `shouldParse` (RavenAssign $ Assign (b) c)
checkAssign "(set! a 3)" "a" (int 3)
checkAssign "(set! b \"123456789\")" "b" (str "123456789")
it "should fail to parse invalid assignment expressions" $ do
let checkFailAssign a = parse assignment `shouldFailOn` a
checkFailAssign "(set!)"
checkFailAssign "(set!x a 3)"
checkFailAssign "(set! a)"
checkFailAssign "(set! 3)"
checkFailAssign "(set! 3 3)"
describe "parsing if expressions" $ do
it "should be possible to parse valid if expressions" $ do
let checkIf a b = parse ifExpr a `shouldParse` b
let int = RavenLiteral . RavenNumber . RavenIntegral
let boolean = RavenLiteral . RavenBool
let str = RavenLiteral . RavenString
checkIf "(if true 1)" (RavenIf (If (boolean True) (int 1) Nothing))
checkIf "(if true 1 2)" (RavenIf (If (boolean True) (int 1) (Just (int 2))))
let func = RavenFunctionCall (RavenVariable "test-func") []
checkIf "(if \"test\" (test-func))" (RavenIf (If (str "test") func Nothing))
it "should fail to parse invalid if expressions" $ do
let checkFailIf a = parse ifExpr `shouldFailOn` a
checkFailIf "(if)"
checkFailIf "(if () true)"
checkFailIf "(if true)"
checkFailIf "(iff true 1)"
describe "parsing delay expressions" $ do
it "should be able to parse valid delay expressions" $ do
let checkDelay a b = parse delay a `shouldParse` b
let int = RavenLiteral . RavenNumber . RavenIntegral
let boolean = RavenLiteral . RavenBool
checkDelay "(delay 1)" (RavenDelay (int 1))
checkDelay "(delay true)" (RavenDelay (boolean True))
it "should fail to parse invalid delay expressions" $ do
let checkFailDelay a = parse delay `shouldFailOn` a
checkFailDelay "(delay"
checkFailDelay "delay)"
checkFailDelay "(delay)"
checkFailDelay "(delayy (+ 1 2))"
describe "parsing cond expressions" $ do
it "should be able to parse valid cond expressions" $ do
let checkCond a b = parse cond a `shouldParse` b
let condExpr a b = RavenCond $ Cond a b
let boolean = RavenLiteral . RavenBool
let int = RavenLiteral . RavenNumber . RavenIntegral
let var = RavenVariable
let func a b = RavenFunctionCall (var a) b
let listFunc = func "list" [int 1, int 2]
let lambdaFunc a = RavenFunctionCall (RavenFunction (Function ["x"] [var "x"])) a
checkCond "(cond (true))" (condExpr [[boolean True]] [])
checkCond "(cond (true 1))" (condExpr [[boolean True, int 1]] [])
checkCond "(cond (else 1))" (condExpr [] [int 1])
checkCond "(cond (false 1) (true 2))" (condExpr [[boolean False, int 1], [boolean True, int 2]] [])
checkCond "(cond (false 1) (false 2) (else 3))" (condExpr [[boolean False, int 1], [boolean False, int 2]] [int 3])
checkCond "(cond ((list 1 2) => car))" (condExpr [[listFunc, func "car" [listFunc]]] [])
checkCond "(cond (1 => (lambda (x) x)))" (condExpr [[int 1, lambdaFunc [int 1]]] [])
it "should fail to parse invalid cond expressions" $ do
let checkFailCond a = parse cond `shouldFailOn` a
checkFailCond "(cond)"
checkFailCond "(cond ())"
checkFailCond "(cnd (true))"
checkFailCond "(cond (true)"
checkFailCond "cond (true))"
checkFailCond "cond (true))"
checkFailCond "(cond ((list 1 2) =>)"
checkFailCond "(cond (=> (list 1 2))"
checkFailCond "(cond (else))"
checkFailCond "(cond (else 1) (true))"
describe "parsing case expressions" $ do
it "should be able to parse valid case expressions" $ do
let checkCase a b = parse caseExpr a `shouldParse` b
let caseExpr' a b c = RavenCase $ Case a b c
let boolean = RavenLiteral . RavenBool
let int = RavenLiteral . RavenNumber . RavenIntegral
checkCase "(case 1 ((1) 2))" (caseExpr' (int 1) [([int 1], [int 2])] [])
checkCase "(case 1 ((1) 2 3))" (caseExpr' (int 1) [([int 1], [int 2, int 3])] [])
checkCase "(case 1 ((1) 2) ((3) 4))" (caseExpr' (int 1) [([int 1], [int 2]), ([int 3], [int 4])] [])
checkCase "(case 1 ((1) 2) ((3) 4) (else 5))" (caseExpr' (int 1) [([int 1], [int 2]), ([int 3], [int 4])] [int 5])
checkCase "(case 2 ((1 2) 3))" (caseExpr' (int 2) [([int 1, int 2], [int 3])] [])
checkCase "(case 1 (else 2))" (caseExpr' (int 1) [] [int 2])
checkCase "(case 1 (else 2 3))" (caseExpr' (int 1) [] [int 2, int 3])
it "should fail to parse invalid case expressions" $ do
let checkFailCase a = parse caseExpr `shouldFailOn` a
checkFailCase "(case)"
checkFailCase "(case 1)"
checkFailCase "(case 1 ())"
checkFailCase "(case 1 ((1) ))"
checkFailCase "(cas 1 ((1) 2))"
checkFailCase "(case 1 ((1) 1)"
checkFailCase "case 1 ((1) 1))"
checkFailCase "(case (else 1))"
checkFailCase "(case 1 (else))"
describe "parsing do expressions" $ do
it "should be able to parse valid do expressions" $ do
let checkDo a b = parse doExpr a `shouldParse` b
let doExpr' a b c = RavenDo $ Do a b c
let boolean = RavenLiteral . RavenBool
let int = RavenLiteral . RavenNumber . RavenIntegral
let var = RavenVariable
let func a b = RavenFunctionCall (var a) b
checkDo "(do () (true))" (doExpr' [] (boolean True, []) [])
checkDo "(do () (true 1))" (doExpr' [] (boolean True, [int 1]) [])
checkDo "(do () (true 1 2))" (doExpr' [] (boolean True, [int 1, int 2]) [])
checkDo "(do ((a 1)) (true))" (doExpr' [(var "a", int 1, var "a")] (boolean True, []) [])
checkDo "(do ((a 1 (+ a 1))) (true))" (doExpr' [(var "a", int 1, func "+" [var "a", int 1])] (boolean True, []) [])
checkDo "(do ((a 1) (b 2)) (true))" (doExpr' [(var "a", int 1, var "a"), (var "b", int 2, var "b")] (boolean True, []) [])
checkDo "(do () (true 1))" (doExpr' [] (boolean True, [int 1]) [])
checkDo "(do () (true 1 2))" (doExpr' [] (boolean True, [int 1, int 2]) [])
checkDo "(do () (true) 1)" (doExpr' [] (boolean True, []) [int 1])
checkDo "(do () (true) 1 2)" (doExpr' [] (boolean True, []) [int 1, int 2])
it "should fail to parse invalid do expressions" $ do
let checkFailDo a = parse doExpr `shouldFailOn` a
checkFailDo "(do)"
checkFailDo "(do ())"
checkFailDo "(do () ())"
checkFailDo "(d () (true))"
checkFailDo "(do () (true ()))"
checkFailDo "(do (a) (true))"
checkFailDo "(do (true))"
checkFailDo "(do () true)"
-- TODO fix failing test cases (mostly due to lack of end of number indicator: " " or ")")
|
luc-tielen/raven
|
test/Raven/ParserSpec.hs
|
Haskell
|
bsd-3-clause
| 20,712
|
module Main where
import qualified System.IO.Streams.Tests.Attoparsec.ByteString as AttoparsecByteString
import qualified System.IO.Streams.Tests.Attoparsec.Text as AttoparsecText
import qualified System.IO.Streams.Tests.Builder as Builder
import qualified System.IO.Streams.Tests.ByteString as ByteString
import qualified System.IO.Streams.Tests.Combinators as Combinators
import qualified System.IO.Streams.Tests.Concurrent as Concurrent
import qualified System.IO.Streams.Tests.Debug as Debug
import qualified System.IO.Streams.Tests.File as File
import qualified System.IO.Streams.Tests.Handle as Handle
import qualified System.IO.Streams.Tests.Internal as Internal
import qualified System.IO.Streams.Tests.List as List
import qualified System.IO.Streams.Tests.Network as Network
import qualified System.IO.Streams.Tests.Process as Process
import qualified System.IO.Streams.Tests.Text as Text
import qualified System.IO.Streams.Tests.Vector as Vector
import qualified System.IO.Streams.Tests.Zlib as Zlib
import Test.Framework (defaultMain, testGroup)
------------------------------------------------------------------------------
main :: IO ()
main = defaultMain tests
where
tests = [ testGroup "Tests.Attoparsec.ByteString" AttoparsecByteString.tests
, testGroup "Tests.Attoparsec.Text" AttoparsecText.tests
, testGroup "Tests.Builder" Builder.tests
, testGroup "Tests.ByteString" ByteString.tests
, testGroup "Tests.Debug" Debug.tests
, testGroup "Tests.Combinators" Combinators.tests
, testGroup "Tests.Concurrent" Concurrent.tests
, testGroup "Tests.File" File.tests
, testGroup "Tests.Handle" Handle.tests
, testGroup "Tests.Internal" Internal.tests
, testGroup "Tests.List" List.tests
, testGroup "Tests.Network" Network.tests
, testGroup "Tests.Process" Process.tests
, testGroup "Tests.Text" Text.tests
, testGroup "Tests.Vector" Vector.tests
, testGroup "Tests.Zlib" Zlib.tests
]
|
LukeHoersten/io-streams
|
test/TestSuite.hs
|
Haskell
|
bsd-3-clause
| 2,344
|
{-# LANGUAGE DataKinds, FlexibleContexts, TemplateHaskell #-}
-- | Demonstration of streaming data processing. Try building with
-- cabal (@cabal build benchdemo@), then running in bash with
-- something like,
--
-- @$ /usr/bin/time -l dist/build/benchdemo/benchdemo 2>&1 | head -n 4@
import qualified Control.Foldl as F
import Frames
import Pipes.Prelude (fold)
tableTypes "Ins" "data/FL2.csv"
main :: IO ()
main = do (lat,lng,n) <- F.purely fold f (readTable "data/FL2.csv")
print $ lat / n
print $ lng / n
where f :: F.Fold Ins (Double,Double,Double)
f = (,,) <$> F.handles pointLatitude F.sum
<*> F.handles pointLongitude F.sum
<*> F.genericLength
|
codygman/Frames
|
benchmarks/BenchDemo.hs
|
Haskell
|
bsd-3-clause
| 718
|
{-# LANGUAGE TemplateHaskell, LambdaCase, FlexibleContexts, DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
module Jugendstil.Doc.Layout
( Layout(..)
, matchLayout
, computeStyle
, Document
, renderDocument
, rows
, columns
, docs
, margin
-- * DoList
, DoList
, unDoList
, (==>)
, rowsDL
, columnsDL)
where
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Iter
import Data.BoundingBox
import Data.BoundingBox as Box
import Data.Monoid
import Graphics.Holz
import Jugendstil.Doc
import Linear
data Layout a = Horizontal [(Maybe Float, a)]
| Vertical [(Maybe Float, a)]
| Stack [a]
| Extend (Box V2 Float -> Box V2 Float) a
deriving (Functor, Foldable, Traversable)
matchLayout :: Applicative m => (Maybe a -> b -> m c) -> Layout a -> Layout b -> m (Layout c)
matchLayout f (Horizontal xs) (Horizontal ys) = Horizontal
<$> zipWithM (\m (s, b) -> (,) s <$> f (snd <$> m) b)
(map Just xs ++ repeat Nothing) ys
matchLayout f (Vertical xs) (Vertical ys) = Vertical
<$> zipWithM (\m (s, b) -> (,) s <$> f (snd <$> m) b)
(map Just xs ++ repeat Nothing) ys
matchLayout f (Stack xs) (Stack ys) = Stack <$> zipWithM f (map Just xs ++ repeat Nothing) ys
matchLayout f (Extend _ a) (Extend g b) = Extend g <$> f (Just a) b
matchLayout f _ l = traverse (f Nothing) l
renderDocument :: Document a -> ShaderT (HolzT IO) (Doc Layout (Box V2 Float, a))
renderDocument doc = do
box <- getBoundingBox
let doc' = computeStyle box doc
renderDoc fst doc'
return doc'
computeStyle :: Box V2 Float -> Doc Layout a -> Doc Layout (Box V2 Float, a)
computeStyle box (Prim a bg) = Prim (box, a) bg
computeStyle box@(Box (V2 x0 y0) (V2 x1 y1)) (Docs a (Horizontal xs))
= Docs (box, a) $ Horizontal $ zip (map fst xs) $ boxes x0 $ sortLayout (x1 - x0) xs
where
boxes x ((w, d):ws) = computeStyle (Box (V2 x y0) (V2 (x + w) y1)) d : boxes (x + w) ws
boxes _ [] = []
computeStyle box@(Box (V2 x0 y0) (V2 x1 y1)) (Docs a (Vertical xs))
= Docs (box, a) $ Vertical $ zip (map fst xs) $ boxes y0 $ sortLayout (y1 - y0) xs
where
boxes y ((h, d):hs) = computeStyle (Box (V2 x0 y) (V2 x1 (y + h))) d : boxes (y + h) hs
boxes _ [] = []
computeStyle box (Docs a (Stack xs)) = Docs (box, a) $ Stack $ map (computeStyle box) xs
computeStyle box (Docs a (Extend f d)) = Docs (box, a) $ Extend f $ computeStyle (f box) d
computeStyle box (Viewport a d) = Viewport (box, a) (computeStyle box d)
sortLayout :: Float -> [(Maybe Float, a)] -> [(Float, a)]
sortLayout total xs0 = let (r, ys) = go total 0 xs0 in map ($ r) ys where
go :: Float -> Int -> [(Maybe Float, a)] -> (Float, [Float -> (Float, a)])
go t n ((Just r, a) : xs) = let v = total * r
in (const (v, a) :) <$> go (t - v) n xs
go t n ((Nothing, a) : xs) = (:) (\r -> (r, a)) <$> go t (n + 1) xs
go t n _ = (t / fromIntegral n, [])
type Document = Doc Layout
rows :: Monoid a => [(Maybe Float, Document a)] -> Document a
rows xs = Docs mempty $ Vertical xs
columns :: Monoid a => [(Maybe Float, Document a)] -> Document a
columns xs = Docs mempty $ Horizontal xs
docs :: Monoid a => [Document a] -> Document a
docs xs = Docs mempty $ Stack xs
margin :: Monoid a => V4 Float -> Document a -> Document a
margin (V4 t r b l) = Docs mempty
. Extend (\(V2 x0 y0 `Box` V2 x1 y1)
-> V2 (x0 + l) (y0 + t) `Box` V2 (x1 - r) (y1 - b))
type DoList a = (,) (Endo [a])
unDoList :: DoList a x -> [a]
unDoList (Endo f, _) = f []
(==>) :: a -> b -> DoList (a, b) ()
a ==> b = (Endo ((a, b):), ())
infix 0 ==>
rowsDL :: Monoid a => DoList (Maybe Float, Document a) x -> Document a
rowsDL = rows . unDoList
columnsDL :: Monoid a => DoList (Maybe Float, Document a) x -> Document a
columnsDL = columns . unDoList
|
fumieval/jugendstil
|
src/Jugendstil/Doc/Layout.hs
|
Haskell
|
bsd-3-clause
| 3,806
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Aria.Pass where
import Happstack.ClientSession
import Control.Lens
import Datat.Data
import Data.SafeCopy (base, deriveSafeCopy)
import Control.Monad.Catch
import Control.Monad.IO.Class
import GHC.Generics
import qualified Data.Map as DM
data LoginSessionData = LoginSessionData
{ _loginRName :: Text
} deriving (Eq, Ord, Show, Read, Data, Typeable)
data BadLoginError =
BadLoginError Text
deriving (Eq, Ord, Show, Read, Data, Typeable, Generic)
data FailedLoginAttempt = FailedLoginAttempt Username Password
deriving (Eq,Ord,Show,Read,Data,Typeable, Generic)
type LoginApp = ClientSessionT LoginSessionData
type Username = String
type Password = String
type UNamePassMap = DM.Map String String
makeLenses ''LoginSessionData
$(deriveSafeCopy 0 'base ''LoginSessionData)
instance ClientSession LoginSessionData where
emptySession =
LoginSessionData
{ _loginRName = ""
}
instance Exception BadLoginError
instance Exception FailedLoginAttempt
guardLogin :: (MonadIO m, MonadThrow m) => Text -> m a -> LoginApp m a
guardLogin login act = do
loginName <- getSession
case (loginName == login) of
True -> act
_ -> throwM $ BadLoginError loginName
login :: (MonadIO m, MonadThrow m) => (Username,Password) -> LoginApp m ()
login upass@(uname,pass) = do
unless (checkLogin upass) $ throwM FailedLoginAttempt uname pass
|
theNerd247/ariaRacer
|
arweb/app/Aria/Pass.hs
|
Haskell
|
bsd-3-clause
| 1,507
|
-- | This module defines a sever-side handler that lets you serve static files.
--
-- - 'serveDirectory' lets you serve anything that lives under a particular
-- directory on your filesystem.
module Servant.Utils.StaticFiles (
serveDirectory,
) where
import Filesystem.Path.CurrentOS (decodeString)
import Network.Wai.Application.Static
import Servant.API.Raw
import Servant.Server.Internal
-- | Serve anything under the specified directory as a 'Raw' endpoint.
--
-- @
-- type MyApi = "static" :> Raw
--
-- server :: Server MyApi
-- server = serveDirectory "\/var\/www"
-- @
--
-- would capture any request to @\/static\/\<something>@ and look for
-- @\<something>@ under @\/var\/www@.
--
-- It will do its best to guess the MIME type for that file, based on the extension,
-- and send an appropriate /Content-Type/ header if possible.
--
-- If your goal is to serve HTML, CSS and Javascript files that use the rest of the API
-- as a webapp backend, you will most likely not want the static files to be hidden
-- behind a /\/static\// prefix. In that case, remember to put the 'serveDirectory'
-- handler in the last position, because /servant/ will try to match the handlers
-- in order.
serveDirectory :: FilePath -> Server Raw
serveDirectory documentRoot =
staticApp (defaultFileServerSettings (decodeString (documentRoot ++ "/")))
|
derekelkins/servant-server
|
src/Servant/Utils/StaticFiles.hs
|
Haskell
|
bsd-3-clause
| 1,346
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.