code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Init.Pages (init) where
import Elm.Utils ((|>))
import Prelude hiding (init)
import System.Directory (getDirectoryContents)
import System.FilePath ((</>), (<.>), dropExtension, hasExtension, joinPath, takeExtension)
import qualified Init.FileTree as FT
import Init.Helpers (makeWithStyle, write)
init :: IO [(FilePath, FilePath)]
init =
do files <- getFiles ("src" </> "pages") ".elm"
let numFiles = length files
result <- mapM (initFile numFiles) (zip [1..] files)
putStrLn "done\n"
return result
initFile :: Int -> (Int, String) -> IO (String, FilePath)
initFile numFiles (index, name) =
do write $ "\rSetting up pages (" ++ show index ++ " of " ++ show numFiles ++ ") "
let input = "src" </> "pages" </> name <.> "elm"
let output = FT.file ["pages"] name "html"
makeWithStyle input output
return (name, output)
-- COLLECT FILES
getFiles :: FilePath -> String -> IO [FilePath]
getFiles root ext =
getFilesHelp root ext []
getFilesHelp :: FilePath -> String -> [FilePath] -> IO [FilePath]
getFilesHelp root ext dirs =
do let directory = root </> joinPath dirs
contents <- getDirectoryContents directory
let files =
contents
|> filter (\name -> ext == takeExtension name)
|> map (joinPath . rightCons dirs . dropExtension)
let subDirs =
filter (not . hasExtension) contents
subFiles <- mapM (getFilesHelp root ext . rightCons dirs) subDirs
return (files ++ concat subFiles)
where
rightCons xs x =
xs ++ [x] | inchingforward/elm-lang.org | src/backend/Init/Pages.hs | bsd-3-clause | 1,588 | 0 | 16 | 392 | 559 | 288 | 271 | 38 | 1 |
import Data.Int
import Data.Word
main = do
print [5 `div` (minBound+k::Int) | k <- [0 .. 10]]
print [5 `div` (minBound+k::Int8) | k <- [0 .. 10]]
print [5 `div` (minBound+k::Int16) | k <- [0 .. 10]]
print [5 `div` (minBound+k::Int32) | k <- [0 .. 10]]
print [5 `div` (minBound+k::Int64) | k <- [0 .. 10]]
print [5 `quot` (minBound+k::Int) | k <- [0 .. 10]]
print [5 `quot` (minBound+k::Int8) | k <- [0 .. 10]]
print [5 `quot` (minBound+k::Int16) | k <- [0 .. 10]]
print [5 `quot` (minBound+k::Int32) | k <- [0 .. 10]]
print [5 `quot` (minBound+k::Int64) | k <- [0 .. 10]]
| ghc-android/ghc | testsuite/tests/numeric/should_run/T7233.hs | bsd-3-clause | 609 | 0 | 11 | 144 | 406 | 229 | 177 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-|
This module provides the API that is exposed to users; it is based
around the 'Entry' type.
Users directly interacting with blobs presents two problems:
Information leakage: if Alice wants to determine if someone already
has a copy of some data, she attempts to read its SHA-256 digest. The
server will return the data if she has it. This data is of no
consequence to Alice, as she likely already had a copy of the data to
produce the hash.
Managing data is more difficult: in the case where a user asks the
server to delete a file that multiple users have, the server has no
way to determine what other users might have the data. One user can
then remove data that other users may still wish to
retain. Alternatively, the server might refuse to delete this data,
which means users have no way to remove data from the system.
The solution is to only access blob IDs in the software, and to
provide users with UUIDs to reference their data. A UUID contains
- the ID
- the referenced object ID (see below, this may be a SHA-256 ID or
another UUID)
- creation date
- the parent UUID
- UUIDs of any children
In order to provide useful access control, a reference may be a proxy
reference: that is, it may refer to another blob reference. This means
that a user can grant revocable access to the data without
jeopardizing their own access.
Therefore, to know an ID is to have access to that ID. For this
reason, users can only see the metadata and none of the IDs. The
system needs an API that can traverse the history tree without
exposing these IDs to users. Proxy objects either need to be presented
with no history information (empty parent and children), or the entire
history needs to be proxied. Similarly, a revocation API needs to be
able to take into account that the entire history tree may be proxied.
This data must be stored in a persistent data structure, such as a
database.
This reference is named an entry. This reference is the only interface
users have with blobs.
-}
module Nebula.Entry
(
-- * Entry accessors
Entry
, newEntry
, entryID
, target
-- * Entry persistence
, writeEntry
, readEntry
-- * Lineage
, getLineage
-- * Entry proxying
-- | Proxying is a means of sharing a reference to an entry
-- without sharing the reference directly.
, proxyEntry, proxyLineage
) where
import qualified Data.Int as Int
import Data.List.Split (splitOn)
import qualified Data.UUID as UUID
import Data.UUID.V4 (nextRandom)
import qualified System.Directory as Dir
import qualified System.FilePath as File
import Nebula.Blob as Blob
import Nebula.Util as Util
-- | The core type of this package is the Entry: a reference to either
-- a blob or an entry.
data Entry = Entry
{ -- | A UUID identifying this entry.
entryID :: !String
-- | What 'Entry' or blob does this refer to?
, target :: !String
-- | Unix timestamp (at millisecond or better
-- resolution) of when the entry was created.
, created :: !Int.Int64
-- | An optional parent. It's possible this is the
-- first entry in its lineage, in which case it will be
-- @Nothing@. If it's @Just@ anything, it will be a
-- UUID pointing to another Entry. This field will
-- never point to a blob.
, parent :: !(Maybe String)
} deriving (Show, Read)
-- | createEntry is the raw function for creating a new entry. It does
-- no validation of its parameters, and returns a new timestamped
-- entry with a random ID.
createEntry :: String -- ^ Target identifier
-> Maybe String -- ^ Entry's parent (what entry precedes this one?)
-> IO Entry -- ^ The timestamped entry
createEntry target parent = do
t <- Util.getTime
uuid <- nextRandom
return $ Entry (UUID.toString uuid) target t parent
{-
The string parameters passed to createEntry must not be empty
strings. The target must be either a SHA-256 hash (i.e., it points to
a blob) or a UUID. The parent must either be Nothing or contain a
valid UUID, as the parent will always be an entry.
-}
validTarget :: String -> Bool
validTarget s = (Util.isValidHash s) || (Util.isValidUUID s)
validParent :: Maybe String -> Bool
validParent Nothing = True
validParent (Just s) = Util.isValidUUID s
validEntryParams :: String -> Maybe String -> Bool
validEntryParams t p = validTarget t && validParent p
-- | newEntry takes a target identifier that indicates what this entry
-- should point to, and an an optional string containing the parent
-- entry; if these two identifiers are valid, a new entry will be
-- created with a random identifier.
--
-- A valid target identifier may be either
--
-- * a blob identifier: if the entry points directly at a file entry,
-- the identifier will be a valid blob identifier.
--
-- * an entry identifier: if the entry is a proxied entry, the
-- identifier will be a valid entry identifier.
newEntry :: String -- ^ Target identifier
-> Maybe String -- ^ Optional parent entry
-> IO (Maybe Entry) -- ^ Resulting entry
newEntry t p = if validEntryParams t p
then do
entry <- createEntry t p
return $ Just entry
else return Nothing
{-
Entries will be stored in some parent directory joined with a number
of path components built from the sections of the UUID. That is, the
UUID "8b00b986-b7cc-4493-acc8-ece4ff86092e" with a parent of "p" would
be split into "p/8b00b986/b7cc/4493/acc8/ece4ff86092e".
-}
entryPath :: FilePath -> Entry -> FilePath
entryPath p (Entry id _ _ _) = idPath p id
idPath :: FilePath -> String -> FilePath
idPath p id = File.joinPath $ p : splitOn "-" id
{- An entry right now is just serialised as its show form. -}
-- | writeEntry serialises an entry and stores it in an appropriate
-- subdirectory under the given parent directory.
writeEntry :: FilePath -- ^ Parent directory
-> IO Entry -- ^ Entry to store
-> IO String -- ^ Path to stored entry
writeEntry p e = do
entry <- e
let path = entryPath p entry
Dir.createDirectoryIfMissing True (File.takeDirectory path)
writeFile path (show entry)
return path
{- Reading an entry is a case of checking whether the entry exists, and
parsing the contents of the file. -}
-- | readEntry looks up the given identifier in the given top-level
-- directory, returned the 'Entry' if it exists.
readEntry :: FilePath -- ^ Parent directory containing the entries
-> String -- ^ Entry identifier
-> IO (Maybe Entry) -- ^ Stored entry
readEntry p id =
if validTarget id
then do
let path = idPath p id
entryExists <- Dir.doesFileExist path
if entryExists
then do
contents <- readFile path
return $ Just (read contents)
else return Nothing
else return Nothing
{- It's useful to be able to lookup the parent of an entry. -}
readParent :: FilePath -> Maybe Entry -> IO (Maybe Entry)
readParent p entry = case entry of
Just (Entry _ _ _ (Just parent)) -> readEntry p parent
_ -> return Nothing
{- An entry's lineage may be similarly fetched. -}
-- | getLineage returns a list of identifiers pointing to an entry's
-- lineage. The list will have the root identifier at the list's tail
-- position.
getLineage :: FilePath -- ^ Parent directory containing entries
-> String -- ^ Entry identifier
-> IO [String] -- ^ Entry's lineage
getLineage p id = do
entry <- readEntry p id
case entry of
Just (Entry _ _ _ (Just parent)) -> do
parents <- getLineage p parent
return $! id : parents
Just (Entry _ _ _ Nothing) -> return [id]
_ -> return []
{- An entry may be proxied: -}
-- | proxyEntry creates a reference to the entry, removing any history
-- from it. The resulting entry will have no reference to a parent.
proxyEntry :: Entry -- ^ Entry to proxy
-> IO (Maybe Entry) -- ^ Proxied entry
proxyEntry (Entry id _ _ _) = newEntry id Nothing
proxy :: Maybe Entry -> Maybe String -> IO (Maybe Entry)
proxy Nothing _ = return Nothing
{- A whole lineage may be proxied: -}
-- | proxyLineage creates a proxy of an entire lineage. It will return a
-- list of entries, with each each entry proxied to a corresponding
-- entry in the original lineage.
proxyLineage :: FilePath -- ^ Parent directory containing entries
-> Entry -- ^ Entry whose lineage should be proxied
-> IO [Entry] -- ^ Proxied lineage
proxyLineage p (Entry id _ _ _) = do
lineage <- getLineage p id
proxied <- proxyAll (reverse lineage) Nothing
return $ reverse proxied
proxyAll :: [String] -> Maybe String -> IO [Entry]
proxyAll [] _ = return []
proxyAll (t:ts) p = do
entry@(Entry id _ _ _) <- createEntry t p
parents <- proxyAll ts (Just id)
return $! entry : parents
| kisom/nebulahs | src/Nebula/Entry.hs | mit | 9,182 | 0 | 14 | 2,338 | 1,261 | 663 | 598 | 115 | 3 |
module Y2017.M07.D03.Exercise where
{--
It's a question of Ord.
From the Mensa Genius Quiz-a-Day Book by Dr. Abbie F. Salny, July 1 problem:
Tom is younger than Rose, but older than Will and Jack, in that order. Rose is
younger than Susie, but older than Jack. Jack is younger than Jim. Susie is
older than Rose, but younger than Jim. Jim is older than Tom. Who is the oldest?
--}
data Person = Tom | Rose | Will | Jack | Susie | Jim
deriving (Eq, Show)
data AgeRel = IsOlderThan Person Person | IsYoungerThan Person Person
deriving (Eq, Show)
oldest :: [AgeRel] -> Person
oldest peeps = undefined
-- Question: is there a better, more accurate, type for oldest?
| geophf/1HaskellADay | exercises/HAD/Y2017/M07/D03/Exercise.hs | mit | 675 | 0 | 6 | 133 | 92 | 55 | 37 | 7 | 1 |
import qualified Data.Array.Unboxed as A
import Data.Char
solve :: Int
solve = product $ map ((digits A.!)) [1, 10, 100, 1000, 10000, 100000, 1000000]
where
digits :: A.UArray Int Int
digits = A.listArray (1,1000000) $ map ((subtract 48) . ord) $ concatMap (show) [1::Int ..]
main :: IO ()
main = print solve
| jwtouron/haskell-play | ProjectEuler/Problem40.hs | mit | 331 | 0 | 13 | 75 | 151 | 86 | 65 | 8 | 1 |
-- Switch to conduit instead?
module Util.ReadLines where
import qualified Data.ByteString as BS
import System.IO
--import System.IO.Error
readLines :: FilePath -> IO [BS.ByteString]
readLines f = withFile f ReadMode hReadLines
hReadLines :: Handle -> IO [BS.ByteString]
hReadLines h =
liftM2 (:) (BS.hGetLine h) (hReadLines h)
`catch`
(\e -> if isEOFError e then return [] else ioError e)
| dancor/melang | src/Util/ReadLines.hs | mit | 406 | 0 | 10 | 73 | 134 | 74 | 60 | 10 | 2 |
{-# OPTIONS -fvia-C #-}
{-# OPTIONS -fno-warn-name-shadowing #-}
-- 6.4 gives a name shadow warning I haven't tracked down.
--
-- | This marvellous module contributed by Thomas J\344ger
--
module Language.Haskell.Pointfree.Rules (RewriteRule(..), rules, fire) where
import Language.Haskell.Pointfree.Common
import Data.Array
import qualified Data.Set as S
import Control.Monad.Fix (fix)
--import PlModule.PrettyPrinter
-- Next time I do somthing like this, I'll actually think about the combinator
-- language before, instead of producing something ad-hoc like this:
data RewriteRule
= RR Rewrite Rewrite
| CRR (Expr -> Maybe Expr)
| Down RewriteRule RewriteRule
| Up RewriteRule RewriteRule
| Or [RewriteRule]
| OrElse RewriteRule RewriteRule
| Then RewriteRule RewriteRule
| Opt RewriteRule
| If RewriteRule RewriteRule
| Hard RewriteRule
-- No MLambda here because we only consider closed Terms (no alpha-renaming!).
data MExpr
= MApp !MExpr !MExpr
| Hole !Int
| Quote !Expr
deriving Eq
--instance Show MExpr where
-- show = show . fromMExpr
data Rewrite = Rewrite {
holes :: MExpr,
rid :: Int -- rlength - 1
} --deriving Show
-- What are you gonna do when no recursive modules are possible?
class RewriteC a where
getRewrite :: a -> Rewrite
instance RewriteC MExpr where
getRewrite rule = Rewrite {
holes = rule,
rid = 0
}
type ExprArr = Array Int Expr
myFire :: ExprArr -> MExpr -> MExpr
myFire xs (MApp e1 e2) = MApp (myFire xs e1) (myFire xs e2)
myFire xs (Hole h) = Quote $ xs ! h
myFire _ me = me
nub' :: Ord a => [a] -> [a]
nub' = S.toList . S.fromList
uniqueArray :: Ord v => Int -> [(Int, v)] -> Maybe (Array Int v)
uniqueArray n lst
| length (nub' lst) == n = Just $ array (0,n-1) lst
| otherwise = Nothing
match :: Rewrite -> Expr -> Maybe ExprArr
match (Rewrite hl rid') e = uniqueArray rid' =<< matchWith hl e
fire' :: Rewrite -> ExprArr -> MExpr
fire' (Rewrite hl _) = (`myFire` hl)
fire :: Rewrite -> Rewrite -> Expr -> Maybe Expr
fire r1 r2 e = (fromMExpr . fire' r2) `fmap` match r1 e
matchWith :: MExpr -> Expr -> Maybe [(Int, Expr)]
matchWith (MApp e1 e2) (App e1' e2') =
liftM2 (++) (matchWith e1 e1') (matchWith e2 e2')
matchWith (Quote e) e' = if e == e' then Just [] else Nothing
matchWith (Hole k) e = Just [(k,e)]
matchWith _ _ = Nothing
fromMExpr :: MExpr -> Expr
fromMExpr (MApp e1 e2) = App (fromMExpr e1) (fromMExpr e2)
fromMExpr (Hole _) = Var Pref "Hole" -- error "Hole in MExpr"
fromMExpr (Quote e) = e
instance RewriteC a => RewriteC (MExpr -> a) where
getRewrite rule = Rewrite {
holes = holes . getRewrite . rule . Hole $ pid,
rid = pid + 1
} where
pid = rid $ getRewrite (bt :: a)
-- Yet another pointless transformation
transformM :: Int -> MExpr -> MExpr
transformM _ (Quote e) = constE `a` Quote e
transformM n (Hole n') = if n == n' then idE else constE `a` Hole n'
transformM n (Quote (Var _ ".") `MApp` e1 `MApp` e2)
| e1 `hasHole` n && not (e2 `hasHole` n)
= flipE `a` compE `a` e2 `c` transformM n e1
transformM n e@(MApp e1 e2)
| fr1 && fr2 = sE `a` transformM n e1 `a` transformM n e2
| fr1 = flipE `a` transformM n e1 `a` e2
| fr2, Hole n' <- e2, n' == n = e1
| fr2 = e1 `c` transformM n e2
| otherwise = constE `a` e
where
fr1 = e1 `hasHole` n
fr2 = e2 `hasHole` n
hasHole :: MExpr -> Int -> Bool
hasHole (MApp e1 e2) n = e1 `hasHole` n || e2 `hasHole` n
hasHole (Quote _) _ = False
hasHole (Hole n') n = n == n'
--
-- haddock doesn't like n+k patterns, so rewrite them
--
getVariants, getVariants' :: Rewrite -> [Rewrite]
getVariants' r@(Rewrite _ 0) = [r]
getVariants' r@(Rewrite e nk)
| nk >= 1 = r : getVariants (Rewrite e' (nk-1))
| otherwise = error "getVariants' : nk went negative"
where
e' = decHoles $ transformM 0 e
decHoles (Hole n') = Hole (n'-1)
decHoles (MApp e1 e2) = decHoles e1 `MApp` decHoles e2
decHoles me = me
getVariants = getVariants' -- r = trace (show vs) vs where vs = getVariants' r
rr, rr0, rr1, rr2 :: RewriteC a => a -> a -> RewriteRule
-- use this rewrite rule and rewrite rules derived from it by iterated
-- pointless transformation
rrList :: RewriteC a => a -> a -> [RewriteRule]
rrList r1 r2 = zipWith RR (getVariants r1') (getVariants r2') where
r1' = getRewrite r1
r2' = getRewrite r2
rr r1 r2 = Or $ rrList r1 r2
rr1 r1 r2 = Or . take 2 $ rrList r1 r2
rr2 r1 r2 = Or . take 3 $ rrList r1 r2
-- use only this rewrite rule
rr0 r1 r2 = RR r1' r2' where
r1' = getRewrite r1
r2' = getRewrite r2
down, up :: RewriteRule -> RewriteRule
down = fix . Down
up = fix . Up
idE, flipE, bindE, extE, returnE, consE, appendE, nilE, foldrE, foldlE, fstE,
sndE, dollarE, constE, uncurryE, curryE, compE, headE, tailE, sE, commaE,
fixE, foldl1E, notE, equalsE, nequalsE, plusE, multE, zeroE, oneE, lengthE,
sumE, productE, concatE, concatMapE, joinE, mapE, fmapE, fmapIE, subtractE,
minusE, liftME, apE, liftM2E, seqME, zipE, zipWithE,
crossE, firstE, secondE, andE, orE, allE, anyE :: MExpr
idE = Quote $ Var Pref "id"
flipE = Quote $ Var Pref "flip"
constE = Quote $ Var Pref "const"
compE = Quote $ Var Inf "."
sE = Quote $ Var Pref "ap"
fixE = Quote $ Var Pref "fix"
bindE = Quote $ Var Inf ">>="
extE = Quote $ Var Inf "=<<"
returnE = Quote $ Var Pref "return"
consE = Quote $ Var Inf ":"
nilE = Quote $ Var Pref "[]"
appendE = Quote $ Var Inf "++"
foldrE = Quote $ Var Pref "foldr"
foldlE = Quote $ Var Pref "foldl"
fstE = Quote $ Var Pref "fst"
sndE = Quote $ Var Pref "snd"
dollarE = Quote $ Var Inf "$"
uncurryE = Quote $ Var Pref "uncurry"
curryE = Quote $ Var Pref "curry"
headE = Quote $ Var Pref "head"
tailE = Quote $ Var Pref "tail"
commaE = Quote $ Var Inf ","
foldl1E = Quote $ Var Pref "foldl1"
equalsE = Quote $ Var Inf "=="
nequalsE = Quote $ Var Inf "/="
notE = Quote $ Var Pref "not"
plusE = Quote $ Var Inf "+"
multE = Quote $ Var Inf "*"
zeroE = Quote $ Var Pref "0"
oneE = Quote $ Var Pref "1"
lengthE = Quote $ Var Pref "length"
sumE = Quote $ Var Pref "sum"
productE = Quote $ Var Pref "product"
concatE = Quote $ Var Pref "concat"
concatMapE = Quote $ Var Pref "concatMap"
joinE = Quote $ Var Pref "join"
mapE = Quote $ Var Pref "map"
fmapE = Quote $ Var Pref "fmap"
fmapIE = Quote $ Var Inf "fmap"
subtractE = Quote $ Var Pref "subtract"
minusE = Quote $ Var Inf "-"
liftME = Quote $ Var Pref "liftM"
liftM2E = Quote $ Var Pref "liftM2"
apE = Quote $ Var Inf "ap"
seqME = Quote $ Var Inf ">>"
zipE = Quote $ Var Pref "zip"
zipWithE = Quote $ Var Pref "zipWith"
crossE = Quote $ Var Inf "***"
firstE = Quote $ Var Pref "first"
secondE = Quote $ Var Pref "second"
andE = Quote $ Var Pref "and"
orE = Quote $ Var Pref "or"
allE = Quote $ Var Pref "all"
anyE = Quote $ Var Pref "any"
a, c :: MExpr -> MExpr -> MExpr
a = MApp
c e1 e2 = compE `a` e1 `a` e2
infixl 9 `a`
infixr 8 `c`
collapseLists :: Expr -> Maybe Expr
collapseLists (Var _ "++" `App` e1 `App` e2)
| (xs,x) <- getList e1, x==nil,
(ys,y) <- getList e2, y==nil = Just $ makeList $ xs ++ ys
collapseLists _ = Nothing
data Binary = forall a b c. (Read a, Show a, Read b, Show b, Read c, Show c) => BA (a -> b -> c)
evalBinary :: [(String, Binary)] -> Expr -> Maybe Expr
evalBinary fs (Var _ f' `App` Var _ x' `App` Var _ y')
| Just (BA f) <- lookup f' fs = (Var Pref . show) `fmap` liftM2 f (readM x') (readM y')
evalBinary _ _ = Nothing
data Unary = forall a b. (Read a, Show a, Read b, Show b) => UA (a -> b)
evalUnary :: [(String, Unary)] -> Expr -> Maybe Expr
evalUnary fs (Var _ f' `App` Var _ x')
| Just (UA f) <- lookup f' fs = (Var Pref . show . f) `fmap` readM x'
evalUnary _ _ = Nothing
assocR, assocL, assoc :: [String] -> Expr -> Maybe Expr
-- (f `op` g) `op` h --> f `op` (g `op` h)
assocR ops (Var f1 op1 `App` (Var f2 op2 `App` e1 `App` e2) `App` e3)
| op1 == op2 && op1 `elem` ops
= Just (Var f1 op1 `App` e1 `App` (Var f2 op2 `App` e2 `App` e3))
assocR _ _ = Nothing
-- f `op` (g `op` h) --> (f `op` g) `op` h
assocL ops (Var f1 op1 `App` e1 `App` (Var f2 op2 `App` e2 `App` e3))
| op1 == op2 && op1 `elem` ops
= Just (Var f1 op1 `App` (Var f2 op2 `App` e1 `App` e2) `App` e3)
assocL _ _ = Nothing
-- op f . op g --> op (f `op` g)
assoc ops (Var _ "." `App` (Var f1 op1 `App` e1) `App` (Var f2 op2 `App` e2))
| op1 == op2 && op1 `elem` ops
= Just (Var f1 op1 `App` (Var f2 op2 `App` e1 `App` e2))
assoc _ _ = Nothing
commutative :: [String] -> Expr -> Maybe Expr
commutative ops (Var f op `App` e1 `App` e2)
| op `elem` ops = Just (Var f op `App` e2 `App` e1)
commutative ops (Var _ "flip" `App` e@(Var _ op)) | op `elem` ops = Just e
commutative _ _ = Nothing
-- TODO: Move rules into a file.
{-# INLINE simplifies #-}
simplifies :: RewriteRule
simplifies = Or [
-- (f . g) x --> f (g x)
rr0 (\f g x -> (f `c` g) `a` x)
(\f g x -> f `a` (g `a` x)),
-- id x --> x
rr0 (\x -> idE `a` x)
(\x -> x),
-- flip (flip x) --> x
rr (\x -> flipE `a` (flipE `a` x))
(\x -> x),
-- flip id x . f --> flip f x
rr0 (\f x -> (flipE `a` idE `a` x) `c` f)
(\f x -> flipE `a` f `a` x),
-- id . f --> f
rr0 (\f -> idE `c` f)
(\f -> f),
-- f . id --> f
rr0 (\f -> f `c` idE)
(\f -> f),
-- const x y --> x
rr0 (\x y -> constE `a` x `a` y)
(\x _ -> x),
-- not (not x) --> x
rr (\x -> notE `a` (notE `a` x))
(\x -> x),
-- fst (x,y) --> x
rr (\x y -> fstE `a` (commaE `a` x `a` y))
(\x _ -> x),
-- snd (x,y) --> y
rr (\x y -> sndE `a` (commaE `a` x `a` y))
(\_ y -> y),
-- head (x:xs) --> x
rr (\x xs -> headE `a` (consE `a` x `a` xs))
(\x _ -> x),
-- tail (x:xs) --> xs
rr (\x xs -> tailE `a` (consE `a` x `a` xs))
(\_ xs -> xs),
-- uncurry f (x,y) --> f x y
rr1 (\f x y -> uncurryE `a` f `a` (commaE `a` x `a` y))
(\f x y -> f `a` x `a` y),
-- uncurry (,) --> id
rr (uncurryE `a` commaE)
(idE),
-- uncurry f . s (,) g --> s f g
rr1 (\f g -> (uncurryE `a` f) `c` (sE `a` commaE `a` g))
(\f g -> sE `a` f `a` g),
-- curry fst --> const
rr (curryE `a` fstE) (constE),
-- curry snd --> const id
rr (curryE `a` sndE) (constE `a` idE),
-- s f g x --> f x (g x)
rr0 (\f g x -> sE `a` f `a` g `a` x)
(\f g x -> f `a` x `a` (g `a` x)),
-- flip f x y --> f y x
rr0 (\f x y -> flipE `a` f `a` x `a` y)
(\f x y -> f `a` y `a` x),
-- flip (=<<) --> (>>=)
rr0 (flipE `a` extE)
bindE,
-- TODO: Think about map/fmap
-- fmap id --> id
rr (fmapE `a` idE)
(idE),
-- map id --> id
rr (mapE `a` idE)
(idE),
-- (f . g) . h --> f . (g . h)
rr0 (\f g h -> (f `c` g) `c` h)
(\f g h -> f `c` (g `c` h)),
-- fmap f . fmap g -> fmap (f . g)
rr0 (\f g -> fmapE `a` f `c` fmapE `a` g)
(\f g -> fmapE `a` (f `c` g)),
-- map f . map g -> map (f . g)
rr0 (\f g -> mapE `a` f `c` mapE `a` g)
(\f g -> mapE `a` (f `c` g))
]
onceRewrites :: RewriteRule
onceRewrites = Hard $ Or [
-- ($) --> id
rr0 (dollarE)
idE,
-- concatMap --> (=<<)
rr concatMapE extE,
-- concat --> join
rr concatE joinE,
-- liftM --> fmap
rr liftME fmapE,
-- map --> fmap
rr mapE fmapE,
-- subtract -> flip (-)
rr subtractE
(flipE `a` minusE)
]
-- Now we can state rewrite rules in a nice high level way
-- Rewrite rules should be as pointful as possible since the pointless variants
-- will be derived automatically.
rules :: RewriteRule
rules = Or [
-- f (g x) --> (f . g) x
Hard $
rr (\f g x -> f `a` (g `a` x))
(\f g x -> (f `c` g) `a` x),
-- (>>=) --> flip (=<<)
Hard $
rr bindE
(flipE `a` extE),
-- (.) id --> id
rr (compE `a` idE)
idE,
-- (++) [x] --> (:) x
rr (\x -> appendE `a` (consE `a` x `a` nilE))
(\x -> consE `a` x),
-- (=<<) return --> id
rr (extE `a` returnE)
idE,
-- (=<<) f (return x) -> f x
rr (\f x -> extE `a` f `a` (returnE `a` x))
(\f x -> f `a` x),
-- (=<<) ((=<<) f . g) --> (=<<) f . (=<<) g
rr (\f g -> extE `a` ((extE `a` f) `c` g))
(\f g -> (extE `a` f) `c` (extE `a` g)),
-- flip (f . g) --> flip (.) g . flip f
Hard $
rr (\f g -> flipE `a` (f `c` g))
(\f g -> (flipE `a` compE `a` g) `c` (flipE `a` f)),
-- flip (.) f . flip id --> flip f
rr (\f -> (flipE `a` compE `a` f) `c` (flipE `a` idE))
(\f -> flipE `a` f),
-- flip (.) f . flip flip --> flip (flip . f)
rr (\f -> (flipE `a` compE `a` f) `c` (flipE `a` flipE))
(\f -> flipE `a` (flipE `c` f)),
-- flip (flip (flip . f) g) --> flip (flip . flip f) g
rr1 (\f g -> flipE `a` (flipE `a` (flipE `c` f) `a` g))
(\f g -> flipE `a` (flipE `c` flipE `a` f) `a` g),
-- flip (.) id --> id
rr (flipE `a` compE `a` idE)
idE,
-- (.) . flip id --> flip flip
rr (compE `c` (flipE `a` idE))
(flipE `a` flipE),
-- s const x y --> y
rr (\x y -> sE `a` constE `a` x `a` y)
(\_ y -> y),
-- s (const . f) g --> f
rr1 (\f g -> sE `a` (constE `c` f) `a` g)
(\f _ -> f),
-- s (const f) --> (.) f
rr (\f -> sE `a` (constE `a` f))
(\f -> compE `a` f),
-- s (f . fst) snd --> uncurry f
rr (\f -> sE `a` (f `c` fstE) `a` sndE)
(\f -> uncurryE `a` f),
-- fst (join (,) x) --> x
rr (\x -> fstE `a` (joinE `a` commaE `a` x))
(\x -> x),
-- snd (join (,) x) --> x
rr (\x -> sndE `a` (joinE `a` commaE `a` x))
(\x -> x),
-- The next two are `simplifies', strictly speaking, but invoked rarely.
-- uncurry f (x,y) --> f x y
-- rr (\f x y -> uncurryE `a` f `a` (commaE `a` x `a` y))
-- (\f x y -> f `a` x `a` y),
-- curry (uncurry f) --> f
rr (\f -> curryE `a` (uncurryE `a` f))
(\f -> f),
-- uncurry (curry f) --> f
rr (\f -> uncurryE `a` (curryE `a` f))
(\f -> f),
-- (const id . f) --> const id
rr (\f -> (constE `a` idE) `c` f)
(\_ -> constE `a` idE),
-- const x . f --> const x
rr (\x f -> constE `a` x `c` f)
(\x _ -> constE `a` x),
-- fix f --> f (fix x)
Hard $
rr0 (\f -> fixE `a` f)
(\f -> f `a` (fixE `a` f)),
-- f (fix f) --> fix x
Hard $
rr0 (\f -> f `a` (fixE `a` f))
(\f -> fixE `a` f),
-- fix f --> f (f (fix x))
Hard $
rr0 (\f -> fixE `a` f)
(\f -> f `a` (f `a` (fixE `a` f))),
-- fix (const f) --> f
rr (\f -> fixE `a` (constE `a` f))
(\f -> f),
-- flip const x --> id
rr (\x -> flipE `a` constE `a` x)
(\_ -> idE),
-- const . f --> flip (const f)
Hard $
rr (\f -> constE `c` f)
(\f -> flipE `a` (constE `a` f)),
-- not (x == y) -> x /= y
rr2 (\x y -> notE `a` (equalsE `a` x `a` y))
(\x y -> nequalsE `a` x `a` y),
-- not (x /= y) -> x == y
rr2 (\x y -> notE `a` (nequalsE `a` x `a` y))
(\x y -> equalsE `a` x `a` y),
If (Or [rr plusE plusE, rr minusE minusE, rr multE multE]) $ down $ Or [
-- 0 + x --> x
rr (\x -> plusE `a` zeroE `a` x)
(\x -> x),
-- 0 * x --> 0
rr (\x -> multE `a` zeroE `a` x)
(\_ -> zeroE),
-- 1 * x --> x
rr (\x -> multE `a` oneE `a` x)
(\x -> x),
-- x - x --> 0
rr (\x -> minusE `a` x `a` x)
(\_ -> zeroE),
-- x - y + y --> x
rr (\y x -> plusE `a` (minusE `a` x `a` y) `a` y)
(\_ x -> x),
-- x + y - y --> x
rr (\y x -> minusE `a` (plusE `a` x `a` y) `a` y)
(\_ x -> x),
-- x + (y - z) --> x + y - z
rr (\x y z -> plusE `a` x `a` (minusE `a` y `a` z))
(\x y z -> minusE `a` (plusE `a` x `a` y) `a` z),
-- x - (y + z) --> x - y - z
rr (\x y z -> minusE `a` x `a` (plusE `a` y `a` z))
(\x y z -> minusE `a` (minusE `a` x `a` y) `a` z),
-- x - (y - z) --> x + y - z
rr (\x y z -> minusE `a` x `a` (minusE `a` y `a` z))
(\x y z -> minusE `a` (plusE `a` x `a` y) `a` z)
],
Hard onceRewrites,
-- join (fmap f x) --> f =<< x
rr (\f x -> joinE `a` (fmapE `a` f `a` x))
(\f x -> extE `a` f `a` x),
-- (=<<) id --> join
rr (extE `a` idE) joinE,
-- join --> (=<<) id
Hard $
rr joinE (extE `a` idE),
-- join (return x) --> x
rr (\x -> joinE `a` (returnE `a` x))
(\x -> x),
-- (return . f) =<< m --> fmap f m
rr (\f m -> extE `a` (returnE `c` f) `a` m)
(\f m -> fmapIE `a` f `a` m),
-- (x >>=) . (return .) . f --> flip (fmap . f) x
rr (\f x -> bindE `a` x `c` (compE `a` returnE) `c` f)
(\f x -> flipE `a` (fmapIE `c` f) `a` x),
-- (>>=) (return f) --> flip id f
rr (\f -> bindE `a` (returnE `a` f))
(\f -> flipE `a` idE `a` f),
-- liftM2 f x --> ap (f `fmap` x)
Hard $
rr (\f x -> liftM2E `a` f `a` x)
(\f x -> apE `a` (fmapIE `a` f `a` x)),
-- liftM2 f (return x) --> fmap (f x)
rr (\f x -> liftM2E `a` f `a` (returnE `a` x))
(\f x -> fmapIE `a` (f `a` x)),
-- f `fmap` return x --> return (f x)
rr (\f x -> fmapE `a` f `a` (returnE `a` x))
(\f x -> returnE `a` (f `a` x)),
-- (=<<) . flip (fmap . f) --> flip liftM2 f
Hard $
rr (\f -> extE `c` flipE `a` (fmapE `c` f))
(\f -> flipE `a` liftM2E `a` f),
-- (.) -> fmap
Hard $
rr compE fmapE,
-- map f (zip xs ys) --> zipWith (curry f) xs ys
Hard $
rr (\f xs ys -> mapE `a` f `a` (zipE `a` xs `a` ys))
(\f xs ys -> zipWithE `a` (curryE `a` f) `a` xs `a` ys),
-- zipWith (,) --> zip (,)
rr (zipWithE `a` commaE) zipE,
-- all f --> and . map f
Hard $
rr (\f -> allE `a` f)
(\f -> andE `c` mapE `a` f),
-- and . map f --> all f
rr (\f -> andE `c` mapE `a` f)
(\f -> allE `a` f),
-- any f --> or . map f
Hard $
rr (\f -> anyE `a` f)
(\f -> orE `c` mapE `a` f),
-- or . map f --> any f
rr (\f -> orE `c` mapE `a` f)
(\f -> anyE `a` f),
-- return f `ap` x --> fmap f x
rr (\f x -> apE `a` (returnE `a` f) `a` x)
(\f x -> fmapIE `a` f `a` x),
-- ap (f `fmap` x) --> liftM2 f x
rr (\f x -> apE `a` (fmapIE `a` f `a` x))
(\f x -> liftM2E `a` f `a` x),
-- f `ap` x --> (`fmap` x) =<< f
Hard $
rr (\f x -> apE `a` f `a` x)
(\f x -> extE `a` (flipE `a` fmapIE `a` x) `a` f),
-- (`fmap` x) =<< f --> f `ap` x
rr (\f x -> extE `a` (flipE `a` fmapIE `a` x) `a` f)
(\f x -> apE `a` f `a` x),
-- (x >>=) . flip (fmap . f) -> liftM2 f x
rr (\f x -> bindE `a` x `c` flipE `a` (fmapE `c` f))
(\f x -> liftM2E `a` f `a` x),
-- (f =<< m) x --> f (m x) x
rr0 (\f m x -> extE `a` f `a` m `a` x)
(\f m x -> f `a` (m `a` x) `a` x),
-- (fmap f g x) --> f (g x)
rr0 (\f g x -> fmapE `a` f `a` g `a` x)
(\f g x -> f `a` (g `a` x)),
-- return x y --> y
rr (\y x -> returnE `a` x `a` y)
(\y _ -> y),
-- liftM2 f g h x --> g x `h` h x
rr0 (\f g h x -> liftM2E `a` f `a` g `a` h `a` x)
(\f g h x -> f `a` (g `a` x) `a` (h `a` x)),
-- ap f id --> join f
rr (\f -> apE `a` f `a` idE)
(\f -> joinE `a` f),
-- (=<<) const q --> flip (>>) q
Hard $ -- ??
rr (\q p -> extE `a` (constE `a` q) `a` p)
(\q p -> seqME `a` p `a` q),
-- p >> q --> const q =<< p
Hard $
rr (\p q -> seqME `a` p `a` q)
(\p q -> extE `a` (constE `a` q) `a` p),
-- experimental support for Control.Arrow stuff
-- (costs quite a bit of performace)
-- uncurry ((. g) . (,) . f) --> f *** g
rr (\f g -> uncurryE `a` ((flipE `a` compE `a` g) `c` commaE `c` f))
(\f g -> crossE `a` f `a` g),
-- uncurry ((,) . f) --> first f
rr (\f -> uncurryE `a` (commaE `c` f))
(\f -> firstE `a` f),
-- uncurry ((. g) . (,)) --> second g
rr (\g -> uncurryE `a` ((flipE `a` compE `a` g) `c` commaE))
(\g -> secondE `a` g),
-- I think we need all three of them:
-- uncurry (const f) --> f . snd
rr (\f -> uncurryE `a` (constE `a` f))
(\f -> f `c` sndE),
-- uncurry const --> fst
rr (uncurryE `a` constE)
(fstE),
-- uncurry (const . f) --> f . fst
rr (\f -> uncurryE `a` (constE `c` f))
(\f -> f `c` fstE),
-- TODO is this the right place?
-- [x] --> return x
Hard $
rr (\x -> consE `a` x `a` nilE)
(\x -> returnE `a` x),
-- list destructors
Hard $
If (Or [rr consE consE, rr nilE nilE]) $ Or [
down $ Or [
-- length [] --> 0
rr (lengthE `a` nilE)
zeroE,
-- length (x:xs) --> 1 + length xs
rr (\x xs -> lengthE `a` (consE `a` x `a` xs))
(\_ xs -> plusE `a` oneE `a` (lengthE `a` xs))
],
-- map/fmap elimination
down $ Or [
-- map f (x:xs) --> f x: map f xs
rr (\f x xs -> mapE `a` f `a` (consE `a` x `a` xs))
(\f x xs -> consE `a` (f `a` x) `a` (mapE `a` f `a` xs)),
-- fmap f (x:xs) --> f x: Fmap f xs
rr (\f x xs -> fmapE `a` f `a` (consE `a` x `a` xs))
(\f x xs -> consE `a` (f `a` x) `a` (fmapE `a` f `a` xs)),
-- map f [] --> []
rr (\f -> mapE `a` f `a` nilE)
(\_ -> nilE),
-- fmap f [] --> []
rr (\f -> fmapE `a` f `a` nilE)
(\_ -> nilE)
],
-- foldr elimination
down $ Or [
-- foldr f z (x:xs) --> f x (foldr f z xs)
rr (\f x xs z -> (foldrE `a` f `a` z) `a` (consE `a` x `a` xs))
(\f x xs z -> (f `a` x) `a` (foldrE `a` f `a` z `a` xs)),
-- foldr f z [] --> z
rr (\f z -> foldrE `a` f `a` z `a` nilE)
(\_ z -> z)
],
-- foldl elimination
down $ Opt (CRR $ assocL ["."]) `Then` Or [
-- sum xs --> foldl (+) 0 xs
rr (\xs -> sumE `a` xs)
(\xs -> foldlE `a` plusE `a` zeroE `a` xs),
-- product xs --> foldl (*) 1 xs
rr (\xs -> productE `a` xs)
(\xs -> foldlE `a` multE `a` oneE `a` xs),
-- foldl1 f (x:xs) --> foldl f x xs
rr (\f x xs -> foldl1E `a` f `a` (consE `a` x `a` xs))
(\f x xs -> foldlE `a` f `a` x `a` xs),
-- foldl f z (x:xs) --> foldl f (f z x) xs
rr (\f z x xs -> (foldlE `a` f `a` z) `a` (consE `a` x `a` xs))
(\f z x xs -> foldlE `a` f `a` (f `a` z `a` x) `a` xs),
-- foldl f z [] --> z
rr (\f z -> foldlE `a` f `a` z `a` nilE)
(\_ z -> z),
-- special rule:
-- foldl f z [x] --> f z x
rr (\f z x -> foldlE `a` f `a` z `a` (returnE `a` x))
(\f z x -> f `a` z `a` x),
rr (\f z x -> foldlE `a` f `a` z `a` (consE `a` x `a` nilE))
(\f z x -> f `a` z `a` x)
] `OrElse` (
-- (:) x --> (++) [x]
Opt (rr0 (\x -> consE `a` x)
(\x -> appendE `a` (consE `a` x `a` nilE))) `Then`
-- More special rule: (:) x . (++) ys --> (++) (x:ys)
up (rr0 (\x ys -> (consE `a` x) `c` (appendE `a` ys))
(\x ys -> appendE `a` (consE `a` x `a` ys)))
)
],
-- Complicated Transformations
CRR (collapseLists),
up $ Or [CRR (evalUnary unaryBuiltins), CRR (evalBinary binaryBuiltins)],
up $ CRR (assoc assocOps),
up $ CRR (assocL assocOps),
up $ CRR (assocR assocOps),
Up (CRR (commutative commutativeOps)) $ down $ Or [CRR $ assocL assocLOps,
CRR $ assocR assocROps],
Hard $ simplifies
] `Then` Opt (up simplifies)
assocLOps, assocROps, assocOps :: [String]
assocLOps = ["+", "*", "&&", "||", "max", "min"]
assocROps = [".", "++"]
assocOps = assocLOps ++ assocROps
commutativeOps :: [String]
commutativeOps = ["*", "+", "==", "/=", "max", "min"]
unaryBuiltins :: [(String,Unary)]
unaryBuiltins = [
("not", UA (not :: Bool -> Bool)),
("negate", UA (negate :: Integer -> Integer)),
("signum", UA (signum :: Integer -> Integer)),
("abs", UA (abs :: Integer -> Integer))
]
binaryBuiltins :: [(String,Binary)]
binaryBuiltins = [
("+", BA ((+) :: Integer -> Integer -> Integer)),
("-", BA ((-) :: Integer -> Integer -> Integer)),
("*", BA ((*) :: Integer -> Integer -> Integer)),
("^", BA ((^) :: Integer -> Integer -> Integer)),
("<", BA ((<) :: Integer -> Integer -> Bool)),
(">", BA ((>) :: Integer -> Integer -> Bool)),
("==", BA ((==) :: Integer -> Integer -> Bool)),
("/=", BA ((/=) :: Integer -> Integer -> Bool)),
("<=", BA ((<=) :: Integer -> Integer -> Bool)),
(">=", BA ((>=) :: Integer -> Integer -> Bool)),
("div", BA (div :: Integer -> Integer -> Integer)),
("mod", BA (mod :: Integer -> Integer -> Integer)),
("max", BA (max :: Integer -> Integer -> Integer)),
("min", BA (min :: Integer -> Integer -> Integer)),
("&&", BA ((&&) :: Bool -> Bool -> Bool)),
("||", BA ((||) :: Bool -> Bool -> Bool))
]
| substack/hs-disappoint | src/Language/Haskell/Pointfree/Rules.hs | mit | 24,721 | 0 | 22 | 7,499 | 11,116 | 6,607 | 4,509 | -1 | -1 |
-- |
-- Module : Southpaw.Utilities.Utilities
-- Description : General functional bits and bobs
-- Copyright : (c) Jonatan H Sundqvist, 2015
-- License : MIT
-- Maintainer : Jonatan H Sundqvist
-- Stability : experimental|stable
-- Portability : POSIX (not sure)
--
-- Created March 08 2015
-- TODO | -
-- -
-- SPEC | -
-- -
--------------------------------------------------------------------------------------------------------------------------------------------
-- GHC directives
--------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------
-- API
--------------------------------------------------------------------------------------------------------------------------------------------
-- TODO: Organise exports (by category, haddock headers)
module Southpaw.Utilities.Utilities (thousands, abbreviate, numeral, roman,
chunks, split, pairwise, cuts, count,
gridM, degrees,
radians, π) where
--------------------------------------------------------------------------------------------------------------------------------------------
-- We'll need these
--------------------------------------------------------------------------------------------------------------------------------------------
import Data.List (intercalate, unfoldr)
import Control.Monad (forM, forM_)
--------------------------------------------------------------------------------------------------------------------------------------------
-- Section
--------------------------------------------------------------------------------------------------------------------------------------------
-- Grammar and string formatting -----------------------------------------------------------------------------------------------------------
-- | Format a number with thousand separators
-- TODO: Allow non-integral numbers
thousands :: Int -> String
thousands = reverse . intercalate "," . chunks 3 . reverse . show
-- |
-- TODO: Optional ellipsis argument
-- TODO: Better name (?)
-- let len = length s in take (min len $ n-3) s ++ take () "..."
abbreviate :: Int -> String -> String
abbreviate n s
| n < length s = let visible = n-3 in take visible s ++ "..."
| otherwise = s
-- | Divides a list into chunks of the given size
--
-- assert chunks 5 "fivesknifelives" == ["fives", "knife", "lives"] -- TODO: Move this to a test section
--
-- TODO: Implement with higher-order recursive function (cf. foldr, iterate, until) (?)
--
chunks :: Int -> [a] -> [[a]]
chunks _ [] = []
chunks n xs = let (chunk, rest) = splitAt n xs in chunk : chunks n rest
-- chunks n = unfoldr (\ xs -> if null xs then Nothing else splitAt n xs)
-- |
splitWith :: Eq a => ([a] -> ([a], [a])) -> [a] -> [[a]]
splitWith f = unfoldr cut
where cut [] = Nothing
cut xs = Just $ f xs
-- |
-- TODO: Rename (?)
split :: Eq a => a -> [a] -> [[a]]
split c = splitWith $ \ xs -> let (token, rest) = span (/=c) xs in (token, dropWhile (==c) rest)
-- split c s = filter (/=[c]) . groupBy ((==) `on` (==c)) $ s
-- | Same as Python's str.split (I think) (eg. split '|' "a||c" == ["a", "", "c"])
-- TODO: Rename
-- TODO: Easier to implement with groupBy (?)
cuts :: Eq a => a -> [a] -> [[a]]
cuts c = splitWith $ \ xs -> let (token, rest) = span (/=c) xs in (token, drop 1 rest)
-- |
-- TODO: Accept a function (eg. (a -> a -> b))
pairwise :: (a -> a -> b) -> [a] -> [b]
pairwise f xs = zipWith f xs (drop 1 xs)
-- Verb conjugation
{- where be 1 = "is"
be _ = "are"
suffix 1 = ""
suffix _ = "s"
-}
-- | Converts a positive integer to an English numeral. Numbers above twelve are converted to comma-separated strings
--
-- TODO: Refactor, simplify (?)
--
numeral :: Int -> String
numeral n = case n of
0 -> sign "zero"
1 -> sign "one"
2 -> sign "two"
3 -> sign "three"
4 -> sign "four"
5 -> sign "five"
6 -> sign "six"
7 -> sign "seven"
8 -> sign "eight"
9 -> sign "nine"
10 -> sign "ten"
11 -> sign "eleven"
12 -> sign "twelve"
_ -> thousands (n :: Int)
where
sign | n < 0 = ("negative " ++) -- TODO: Use 'minus' instead, optional (?)
| otherwise = (id)
-- |
-- TODO: Finish
roman :: Int -> Maybe Char
roman n = case n of
0 -> Nothing
1 -> Just 'I'
5 -> Just 'V'
10 -> Just 'X'
50 -> Just 'L'
100 -> Just 'C'
500 -> Just 'D'
1000 -> Just 'M'
-- General utilities -----------------------------------------------------------------------------------------------------------------------
-- | Counts the number of elements that satisfy the predicate
count :: (a -> Bool) -> [a] -> Int
count p = length . filter p
-- Control structures ----------------------------------------------------------------------------------------------------------------------
-- |
grid :: (Integral n) => n -> n -> [(n, n)]
grid cols rows = [ (col, row) | col <- [1..cols], row <- [1..rows]]
-- |
gridM :: (Integral n, Monad m) => n -> n -> (n -> n -> m a) -> m [a]
gridM cols rows f = forM (grid cols rows) (uncurry f)
-- |
gridM_ :: (Integral n, Monad m) => n -> n -> (n -> n -> m a) -> m ()
gridM_ cols rows f = forM_ (grid cols rows) (uncurry f)
-- Math ------------------------------------------------------------------------------------------------------------------------------------
--
π :: Floating a => a
π = pi
-- |
-- TODO: Unit types, Num instance (?)
-- TODO: Rename (eg. 'toDegrees', 'fromRadians') (?)
degrees :: Floating f => f -> f
degrees rad = rad * (180.0/π)
-- |
radians :: Floating f => f -> f
radians deg = deg * (π/180.0)
-- Experiments -----------------------------------------------------------------------------------------------------------------------------
-- | Polymorphism with list of records of functions
--------------------------------------------------------------------------------------------------------------------------------------------
-- Tests
--------------------------------------------------------------------------------------------------------------------------------------------
| SwiftsNamesake/Southpaw | lib/Southpaw/Utilities/Utilities.hs | mit | 6,398 | 0 | 12 | 1,196 | 1,294 | 706 | 588 | 67 | 14 |
{-# LANGUAGE JavaScriptFFI, CPP, OverloadedStrings, ScopedTypeVariables #-}
module Main where
import Control.Monad
import Control.Concurrent
import GHCJS.Foreign
import GHCJS.Foreign.Callback
import GHCJS.Marshal
import GHCJS.Types
import GHCJS.Prim hiding (getProp)
import Data.JSString
import JavaScript.Cast
import Data.Maybe
import System.IO.Unsafe
import Data.String
{- Note. This isn't good Haskell code! It's atrocious. But that's not
what it's here for. This is a direct translation of the Hello World
example you get when you create a new project with
nativescript/tns. This includes the fact that in the project there's a
split between main_view_model and main_page (they live in separate .js
files). There's no reason to do this aside from a pedagocial one: this
will be necessary when we really do have multiple views with more
complex apps. So we keep that setup here in order to show how those
mechanisms work. -}
{- The control flow here can be a bit confusing. First nativescript
starts up app.js (the result of compiling this code). This runs main,
and main must run synchronously and eventually return back to ns. Main
exports functions which have the same names as the views (this app has
only one view, main-page). main-page is the Main action, so it gets
displayed and that code is run. That file (and all other .js files)
contain stubs that look like:
require("./app.js")["main-page"](module.exports);
In our case the function main_page is exported as
main-page. Javascript starts the main-page view and calls back into
Haskell. We export a pageLoaded callback which, by way of another
level of identical callbacks and direction to get main-view-mode, sets
the model-view-mode as the bindingContext of the page. This provides
us with an observable that receives callbacks when changes occur. -}
foreign import javascript unsafe "$1.start()"
start :: (JSRef a) -> IO ()
-- We really want this:
--
-- foreign import javascript unsafe "$1.require($2)"
-- require :: (JSRef a) -> JSString -> IO (JSRef a)
--
-- but unfortunately nativescript doesn't support this require
-- syntax. Seems like it's node.js specific. This means we end up
-- requiring everything into the current module.
foreign import javascript unsafe "require($1)"
require :: JSString -> IO (JSRef a)
foreign import javascript unsafe "$1[$2] = $3"
export' :: (JSRef a) -> JSString -> JSRef a -> IO ()
foreign import javascript unsafe "$1[$2] = $3"
js_export :: (JSRef a) -> JSString -> Callback (IO ()) -> IO ()
foreign import javascript unsafe "$1[$2] = $3"
js_export1 :: (JSRef a) -> JSString -> Callback (b -> IO ()) -> IO ()
export mod name f = syncCallback ThrowWouldBlock f >>= js_export mod name
export1 mod name f = syncCallback1 ThrowWouldBlock f >>= js_export1 mod name
foreign import javascript unsafe "$1[$2] = $3"
setProp :: JSRef a -> JSString -> JSRef b -> IO (JSRef c)
foreign import javascript unsafe "$1[$2]"
getProp :: JSRef a -> JSString -> IO (JSRef b)
foreign import javascript unsafe "$r = exports"
js_exports :: JSRef a
-- TODO Why do we need a temporary here? I don't understand why this
-- doesn't work without it.
foreign import javascript unsafe "obs = require('data/observable'); $r = new obs.Observable()"
newObservable :: IO (JSRef a)
foreign import javascript unsafe "$1.set($2, $3);"
o_set :: JSRef a -> JSRef b -> JSRef c -> IO ()
set_message o s = o_set o (sToRef "message") =<< s
foreign import javascript unsafe "$1[$2] = $1[$2] - 1"
dec :: JSRef a -> JSString -> IO ()
foreign import javascript unsafe "$1[$2] = $1[$2] + 1"
inc :: JSRef a -> JSString -> IO ()
main_view_model e = do
model <- newObservable
setProp model "counter" =<< toJSRef (5 :: Int)
let taps = do Just (d::Int) <- fromJSRef =<< getProp model "counter"
return $ sToRef $ show d ++ " taps left"
set_message model taps
setProp model "tapAction"
=<< toJSRef =<< syncCallback ThrowWouldBlock (do
dec model "counter"
Just (d::Int) <- fromJSRef =<< getProp model "counter"
if d <= 0 then
set_message model $ return $ sToRef "Unlocked"
else
set_message model taps
return ())
export' e "mainViewModel" model
return ()
-- Convention is underscores in the name of what would be js modules
-- but dashes when exporting. js doesn't have functions with
-- dashes so we won't clash.
main_page e = do
view <- require "./main-view-model"
export1 e "pageLoaded"
(\a -> do
page <- getProp a "object"
setProp page "bindingContext" =<< getProp view "mainViewModel"
return ())
sToRef :: String -> JSRef String
sToRef x = unsafePerformIO $ toJSRef x
main = do
app <- require "application"
setProp app "mainModule" $ sToRef "main-page"
setProp app "cssFile" $ sToRef "./app.css"
export1 js_exports "main-page" main_page
export1 js_exports "main-view-model" main_view_model
start app
return ()
| abarbu/haskell-mobile | hello/app/App.hs | mit | 5,181 | 38 | 15 | 1,184 | 968 | 476 | 492 | 74 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Data.Vectors(
Axis(..),
Vector2(..),
Vector3(..),
Vector(..),
fromTuple,
fromTriple,
toInt2,
fromInt2,
toInt3,
fromInt3
) where
import Data.List
import Control.Lens
data Axis = X | Y | Z deriving (Show, Eq)
data Vector2 a = Vector2 a a deriving (Show, Eq, Ord)
data Vector3 a = Vector3 a a a deriving (Show, Eq, Ord)
makeLenses ''Vector2
makeLenses ''Vector3
-- | NB. toInt2, toInt3 only for use with vectors that can be represented
-- | in base 3! This is an ad-hoc way for representing space IDs
-- base 3 representation of a Vector2
-- | NB. toInt2 . fromInt2 = id
-- | fromInt2 . toInt2 = id
toInt2 :: Vector2 Int -> Int
toInt2 (Vector2 x y) = 3 * y + x
toBase3 :: Int -> [Int]
toBase3 0 = [0]
toBase3 1 = [1]
toBase3 2 = [2]
toBase3 x = (x `mod` 3) : toBase3 (x `div` 3)
fromInt2 :: Int -> Vector2 Int
fromInt2 x = Vector2 x' y'
where [x', y'] =
case toBase3 x of
[x'] -> [x', 0]
a@[_,_] -> a
_ -> error "Cannot convert number larger than 8 to Vector2."
-- base 3 representation of a Vector3
-- x, y, z in 0..2 (though z will typically be 0 or 1)
-- | NB. toInt3 . fromInt3 = id
-- | fromInt3 . toInt3 = id
toInt3 :: Vector3 Int -> Int
toInt3 (Vector3 x y z) = 9 * z + 3 * y + x
fromInt3 :: Int -> Vector3 Int
fromInt3 x = Vector3 x' y' z'
where [x', y', z'] =
case toBase3 x of
[x'] -> [x', 0, 0]
[x', y'] -> [x', y', 0]
a@[_,_,_] -> a
_ -> error "Cannot convert number larger than 26 to Vector3"
class Vector v where
vmap :: Axis -> (a -> a) -> v a -> Maybe (v a)
setV :: Axis -> a -> v a -> Maybe (v a)
setV axis x = vmap axis (const x)
getAxis :: Axis -> v a -> (Maybe a)
smult :: (Functor v, Num n) => n -> v n -> v n
smult n v = fmap (*n) v
instance Vector Vector3 where
vmap X f (Vector3 x y z) = Just $ Vector3 (f x) y z
vmap Y f (Vector3 x y z) = Just $ Vector3 x (f y) z
vmap Z f (Vector3 x y z) = Just $ Vector3 x y (f z)
getAxis X (Vector3 x y z) = Just x
getAxis Y (Vector3 x y z) = Just y
getAxis Z (Vector3 x y z) = Just z
instance Vector Vector2 where
vmap X f (Vector2 x y) = Just $ Vector2 (f x) y
vmap Y f (Vector2 x y) = Just $ Vector2 x (f y)
vmap _ _ _ = Nothing
getAxis X (Vector2 x y) = Just x
getAxis Y (Vector2 x y) = Just y
getAxis _ _ = Nothing
instance Functor Vector2 where
fmap f (Vector2 x y) = Vector2 (f x) (f y)
instance Functor Vector3 where
fmap f (Vector3 x y z) = Vector3 (f x) (f y) (f z)
fromTuple :: (a, a) -> Vector2 a
fromTuple (x, y) = Vector2 x y
fromTriple :: (a, a, a) -> Vector3 a
fromTriple (x, y, z) = Vector3 x y z | 5outh/textlunky | src/Data/Vectors.hs | mit | 2,776 | 6 | 12 | 825 | 1,222 | 641 | 581 | 72 | 4 |
module Control.Disruptor.FixedSequenceGroup where
import Control.Disruptor.Sequence
import qualified Data.Foldable as F
import qualified Data.Vector as V
newtype FixedSequenceGroup = FixedSequenceGroup { fromFixedSequenceGroup :: V.Vector Sequence }
fixedSequenceGroup :: F.Foldable f => f Sequence -> FixedSequenceGroup
fixedSequenceGroup = FixedSequenceGroup . V.fromList . F.toList
instance GetSequence FixedSequenceGroup where
get = findMinimumSequence . fromFixedSequenceGroup
| iand675/disruptor | src/Control/Disruptor/FixedSequenceGroup.hs | mit | 498 | 0 | 8 | 66 | 102 | 60 | 42 | 9 | 1 |
moduele Main where
import Text.ParserCombinators.Parsec hiding (spaces)
import System.Environment
import Control.Monad
import Control.Monad.Error
import System.IO
import Data.IORef
| pie-lang/pie | proto/parser.hs | mit | 182 | 0 | 5 | 18 | 47 | 27 | 20 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2016.Bench where
import Criterion (Benchmark, bench, bgroup, nf, whnf)
import Criterion.Main (env)
import Y2016
bathroomDirections = unlines
[ "ULL"
, "RRDDD"
, "LURDL"
, "UUUUD"
]
benchmarks :: Benchmark
benchmarks =
bgroup "Y2016"
[ bgroup "Day 1"
[ bgroup "blockDistance"
[ bench "simple" $ nf blockDistance "R2, L3"
, bench "larger" $ nf blockDistance "R5, L5, R5, R3"
]
, bgroup "visitedTwice"
[ bench "simple" $ nf visitedTwice "R8, R4, R4, R8"
]
]
, bgroup "Day 2"
[ bgroup "bathroomCode"
[ bench "part 1" $ nf (bathroomCode grid1 (2,2)) bathroomDirections
, bench "part 2" $ nf (bathroomCode grid2 (1,3)) bathroomDirections
]
]
]
| tylerjl/adventofcode | benchmark/Y2016/Bench.hs | mit | 906 | 0 | 15 | 334 | 218 | 117 | 101 | 23 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLAnchorElement
(js_toString, toString, js_setCharset, setCharset, js_getCharset,
getCharset, js_setCoords, setCoords, js_getCoords, getCoords,
js_setDownload, setDownload, js_getDownload, getDownload,
js_setHref, setHref, js_getHref, getHref, js_setHreflang,
setHreflang, js_getHreflang, getHreflang, js_setName, setName,
js_getName, getName, js_setPing, setPing, js_getPing, getPing,
js_setRel, setRel, js_getRel, getRel, js_setRev, setRev, js_getRev,
getRev, js_setShape, setShape, js_getShape, getShape, js_setTarget,
setTarget, js_getTarget, getTarget, js_setType, setType,
js_getType, getType, js_setHash, setHash, js_getHash, getHash,
js_setHost, setHost, js_getHost, getHost, js_setHostname,
setHostname, js_getHostname, getHostname, js_setPathname,
setPathname, js_getPathname, getPathname, js_setPort, setPort,
js_getPort, getPort, js_setProtocol, setProtocol, js_getProtocol,
getProtocol, js_setSearch, setSearch, js_getSearch, getSearch,
js_getOrigin, getOrigin, js_setText, setText, js_getText, getText,
js_getRelList, getRelList, HTMLAnchorElement,
castToHTMLAnchorElement, gTypeHTMLAnchorElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"toString\"]()" js_toString
:: JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.toString Mozilla HTMLAnchorElement.toString documentation>
toString ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
toString self
= liftIO
(fromJSString <$> (js_toString (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"charset\"] = $2;"
js_setCharset :: JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.charset Mozilla HTMLAnchorElement.charset documentation>
setCharset ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setCharset self val
= liftIO
(js_setCharset (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"charset\"]" js_getCharset ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.charset Mozilla HTMLAnchorElement.charset documentation>
getCharset ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getCharset self
= liftIO
(fromJSString <$> (js_getCharset (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"coords\"] = $2;"
js_setCoords :: JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.coords Mozilla HTMLAnchorElement.coords documentation>
setCoords ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setCoords self val
= liftIO (js_setCoords (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"coords\"]" js_getCoords ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.coords Mozilla HTMLAnchorElement.coords documentation>
getCoords ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getCoords self
= liftIO
(fromJSString <$> (js_getCoords (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"download\"] = $2;"
js_setDownload :: JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.download Mozilla HTMLAnchorElement.download documentation>
setDownload ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setDownload self val
= liftIO
(js_setDownload (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"download\"]" js_getDownload
:: JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.download Mozilla HTMLAnchorElement.download documentation>
getDownload ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getDownload self
= liftIO
(fromJSString <$> (js_getDownload (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"href\"] = $2;" js_setHref ::
JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.href Mozilla HTMLAnchorElement.href documentation>
setHref ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setHref self val
= liftIO (js_setHref (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"href\"]" js_getHref ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.href Mozilla HTMLAnchorElement.href documentation>
getHref ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getHref self
= liftIO (fromJSString <$> (js_getHref (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"hreflang\"] = $2;"
js_setHreflang :: JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.hreflang Mozilla HTMLAnchorElement.hreflang documentation>
setHreflang ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setHreflang self val
= liftIO
(js_setHreflang (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"hreflang\"]" js_getHreflang
:: JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.hreflang Mozilla HTMLAnchorElement.hreflang documentation>
getHreflang ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getHreflang self
= liftIO
(fromJSString <$> (js_getHreflang (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName ::
JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.name Mozilla HTMLAnchorElement.name documentation>
setName ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setName self val
= liftIO (js_setName (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"name\"]" js_getName ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.name Mozilla HTMLAnchorElement.name documentation>
getName ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getName self
= liftIO (fromJSString <$> (js_getName (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"ping\"] = $2;" js_setPing ::
JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.ping Mozilla HTMLAnchorElement.ping documentation>
setPing ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setPing self val
= liftIO (js_setPing (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"ping\"]" js_getPing ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.ping Mozilla HTMLAnchorElement.ping documentation>
getPing ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getPing self
= liftIO (fromJSString <$> (js_getPing (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"rel\"] = $2;" js_setRel ::
JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.rel Mozilla HTMLAnchorElement.rel documentation>
setRel ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setRel self val
= liftIO (js_setRel (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"rel\"]" js_getRel ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.rel Mozilla HTMLAnchorElement.rel documentation>
getRel ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getRel self
= liftIO (fromJSString <$> (js_getRel (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"rev\"] = $2;" js_setRev ::
JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.rev Mozilla HTMLAnchorElement.rev documentation>
setRev ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setRev self val
= liftIO (js_setRev (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"rev\"]" js_getRev ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.rev Mozilla HTMLAnchorElement.rev documentation>
getRev ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getRev self
= liftIO (fromJSString <$> (js_getRev (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"shape\"] = $2;" js_setShape
:: JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.shape Mozilla HTMLAnchorElement.shape documentation>
setShape ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setShape self val
= liftIO (js_setShape (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"shape\"]" js_getShape ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.shape Mozilla HTMLAnchorElement.shape documentation>
getShape ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getShape self
= liftIO
(fromJSString <$> (js_getShape (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"target\"] = $2;"
js_setTarget :: JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.target Mozilla HTMLAnchorElement.target documentation>
setTarget ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setTarget self val
= liftIO (js_setTarget (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"target\"]" js_getTarget ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.target Mozilla HTMLAnchorElement.target documentation>
getTarget ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getTarget self
= liftIO
(fromJSString <$> (js_getTarget (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"type\"] = $2;" js_setType ::
JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.type Mozilla HTMLAnchorElement.type documentation>
setType ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setType self val
= liftIO (js_setType (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"type\"]" js_getType ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.type Mozilla HTMLAnchorElement.type documentation>
getType ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getType self
= liftIO (fromJSString <$> (js_getType (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"hash\"] = $2;" js_setHash ::
JSRef HTMLAnchorElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.hash Mozilla HTMLAnchorElement.hash documentation>
setHash ::
(MonadIO m, ToJSString val) =>
HTMLAnchorElement -> Maybe val -> m ()
setHash self val
= liftIO
(js_setHash (unHTMLAnchorElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"hash\"]" js_getHash ::
JSRef HTMLAnchorElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.hash Mozilla HTMLAnchorElement.hash documentation>
getHash ::
(MonadIO m, FromJSString result) =>
HTMLAnchorElement -> m (Maybe result)
getHash self
= liftIO
(fromMaybeJSString <$> (js_getHash (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"host\"] = $2;" js_setHost ::
JSRef HTMLAnchorElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.host Mozilla HTMLAnchorElement.host documentation>
setHost ::
(MonadIO m, ToJSString val) =>
HTMLAnchorElement -> Maybe val -> m ()
setHost self val
= liftIO
(js_setHost (unHTMLAnchorElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"host\"]" js_getHost ::
JSRef HTMLAnchorElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.host Mozilla HTMLAnchorElement.host documentation>
getHost ::
(MonadIO m, FromJSString result) =>
HTMLAnchorElement -> m (Maybe result)
getHost self
= liftIO
(fromMaybeJSString <$> (js_getHost (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"hostname\"] = $2;"
js_setHostname ::
JSRef HTMLAnchorElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.hostname Mozilla HTMLAnchorElement.hostname documentation>
setHostname ::
(MonadIO m, ToJSString val) =>
HTMLAnchorElement -> Maybe val -> m ()
setHostname self val
= liftIO
(js_setHostname (unHTMLAnchorElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"hostname\"]" js_getHostname
:: JSRef HTMLAnchorElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.hostname Mozilla HTMLAnchorElement.hostname documentation>
getHostname ::
(MonadIO m, FromJSString result) =>
HTMLAnchorElement -> m (Maybe result)
getHostname self
= liftIO
(fromMaybeJSString <$> (js_getHostname (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"pathname\"] = $2;"
js_setPathname ::
JSRef HTMLAnchorElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.pathname Mozilla HTMLAnchorElement.pathname documentation>
setPathname ::
(MonadIO m, ToJSString val) =>
HTMLAnchorElement -> Maybe val -> m ()
setPathname self val
= liftIO
(js_setPathname (unHTMLAnchorElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"pathname\"]" js_getPathname
:: JSRef HTMLAnchorElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.pathname Mozilla HTMLAnchorElement.pathname documentation>
getPathname ::
(MonadIO m, FromJSString result) =>
HTMLAnchorElement -> m (Maybe result)
getPathname self
= liftIO
(fromMaybeJSString <$> (js_getPathname (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"port\"] = $2;" js_setPort ::
JSRef HTMLAnchorElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.port Mozilla HTMLAnchorElement.port documentation>
setPort ::
(MonadIO m, ToJSString val) =>
HTMLAnchorElement -> Maybe val -> m ()
setPort self val
= liftIO
(js_setPort (unHTMLAnchorElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"port\"]" js_getPort ::
JSRef HTMLAnchorElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.port Mozilla HTMLAnchorElement.port documentation>
getPort ::
(MonadIO m, FromJSString result) =>
HTMLAnchorElement -> m (Maybe result)
getPort self
= liftIO
(fromMaybeJSString <$> (js_getPort (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"protocol\"] = $2;"
js_setProtocol ::
JSRef HTMLAnchorElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.protocol Mozilla HTMLAnchorElement.protocol documentation>
setProtocol ::
(MonadIO m, ToJSString val) =>
HTMLAnchorElement -> Maybe val -> m ()
setProtocol self val
= liftIO
(js_setProtocol (unHTMLAnchorElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"protocol\"]" js_getProtocol
:: JSRef HTMLAnchorElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.protocol Mozilla HTMLAnchorElement.protocol documentation>
getProtocol ::
(MonadIO m, FromJSString result) =>
HTMLAnchorElement -> m (Maybe result)
getProtocol self
= liftIO
(fromMaybeJSString <$> (js_getProtocol (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"search\"] = $2;"
js_setSearch ::
JSRef HTMLAnchorElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.search Mozilla HTMLAnchorElement.search documentation>
setSearch ::
(MonadIO m, ToJSString val) =>
HTMLAnchorElement -> Maybe val -> m ()
setSearch self val
= liftIO
(js_setSearch (unHTMLAnchorElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"search\"]" js_getSearch ::
JSRef HTMLAnchorElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.search Mozilla HTMLAnchorElement.search documentation>
getSearch ::
(MonadIO m, FromJSString result) =>
HTMLAnchorElement -> m (Maybe result)
getSearch self
= liftIO
(fromMaybeJSString <$> (js_getSearch (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"origin\"]" js_getOrigin ::
JSRef HTMLAnchorElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.origin Mozilla HTMLAnchorElement.origin documentation>
getOrigin ::
(MonadIO m, FromJSString result) =>
HTMLAnchorElement -> m (Maybe result)
getOrigin self
= liftIO
(fromMaybeJSString <$> (js_getOrigin (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"text\"] = $2;" js_setText ::
JSRef HTMLAnchorElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.text Mozilla HTMLAnchorElement.text documentation>
setText ::
(MonadIO m, ToJSString val) => HTMLAnchorElement -> val -> m ()
setText self val
= liftIO (js_setText (unHTMLAnchorElement self) (toJSString val))
foreign import javascript unsafe "$1[\"text\"]" js_getText ::
JSRef HTMLAnchorElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.text Mozilla HTMLAnchorElement.text documentation>
getText ::
(MonadIO m, FromJSString result) => HTMLAnchorElement -> m result
getText self
= liftIO (fromJSString <$> (js_getText (unHTMLAnchorElement self)))
foreign import javascript unsafe "$1[\"relList\"]" js_getRelList ::
JSRef HTMLAnchorElement -> IO (JSRef DOMTokenList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement.relList Mozilla HTMLAnchorElement.relList documentation>
getRelList ::
(MonadIO m) => HTMLAnchorElement -> m (Maybe DOMTokenList)
getRelList self
= liftIO ((js_getRelList (unHTMLAnchorElement self)) >>= fromJSRef) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/HTMLAnchorElement.hs | mit | 21,050 | 298 | 11 | 3,505 | 4,587 | 2,417 | 2,170 | 336 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Util
( executeSqlFile
, updateOrInsert
, trySql
, prompt
, getOrCreate
, getDbConnection
, getCategoryId
, getAccountId
, getEnvelopeId
, defaultFromSql
, readInteger100
, promptPassword
, parseLocalTime
, numberOfOccurrences
) where
import Control.Exception
import Control.Monad
import Data.Char
import Data.Convertible
import Data.Maybe
import Data.List
import Data.Time
import Data.Time.Recurrence (Freq, recur, starting)
import Database.HDBC
import Database.HDBC.Sqlite3
import System.IO
import System.Locale (defaultTimeLocale)
getDbConnection :: IO Connection
getDbConnection = do
conn <- connectSqlite3 "manila.db"
runRaw conn "COMMIT; PRAGMA foreign_keys = ON; BEGIN TRANSACTION"
return conn
executeSqlFile :: Connection -> FilePath -> IO ()
executeSqlFile conn file = do
contents <- readFile file
runRaw conn contents
commit conn
updateOrInsert :: Connection -> (String, [SqlValue]) -> (String, [SqlValue]) -> (String, [SqlValue]) -> IO Integer
updateOrInsert conn (selectSql, selectParams) (updateSql, updateParams) (insertSql, insertParams) = do
selectResult <- quickQuery' conn selectSql selectParams
let result = case selectResult of
[] -> run conn insertSql insertParams
_ -> run conn updateSql updateParams
commit conn
result
getOrCreate :: Connection -> (String, [SqlValue]) -> (String, [SqlValue]) -> IO [[SqlValue]]
getOrCreate conn (selectSql, selectParams) (insertSql, insertParams) = do
selectResultMaybe <- quickQuery' conn selectSql selectParams
when (null selectResultMaybe) $ do
run conn insertSql insertParams
commit conn
quickQuery' conn selectSql selectParams
trySql :: IO a -> IO (Either SqlError a)
trySql = try
prompt :: String -> IO String
prompt text = do
putStr text
hFlush stdout
getLine
getCategoryId :: Connection -> String -> IO Integer
getCategoryId conn category = do
selectResult <- quickQuery' conn "SELECT id FROM category WHERE name = ?" [toSql category]
return . fromSql . head . head $ selectResult
getAccountId :: Connection -> String -> IO Integer
getAccountId conn account = do
selectResult <- quickQuery' conn "SELECT id FROM account WHERE name = ?" [toSql account]
return . fromSql . head . head $ selectResult
getEnvelopeId :: Connection -> String -> IO Integer
getEnvelopeId conn name = do
envelopeResult <- quickQuery' conn "SELECT id FROM envelope WHERE name = ?" [toSql name]
return $ fromSql . head . head $ envelopeResult
defaultFromSql :: Convertible SqlValue a => SqlValue -> a -> a
defaultFromSql x defaultValue =
case safeFromSql x of
Left (ConvertError{}) -> defaultValue
Right a -> a
readInteger100 :: String -> Integer
readInteger100 s = truncate $ (read s :: Float) * 100
promptPassword :: String -> IO String
promptPassword message = do
putStr message
hFlush stdout
pass <- withEcho False getLine
putChar '\n'
return pass
withEcho :: Bool -> IO a -> IO a
withEcho echo action = do
old <- hGetEcho stdin
bracket_ (hSetEcho stdin echo) (hSetEcho stdin old) action
parseLocalTime :: TimeZone -> String -> Maybe UTCTime
parseLocalTime tz s = fmap (localTimeToUTC tz) $ parseTime defaultTimeLocale "%F %T" s
numberOfOccurrences :: UTCTime -> UTCTime -> Freq -> Integer
numberOfOccurrences start end frequency =
genericLength $ takeWhile (<= end) $ starting start $ recur frequency
| jpotterm/manila-hs | src/Util.hs | cc0-1.0 | 3,577 | 0 | 13 | 767 | 1,064 | 533 | 531 | 95 | 2 |
rome
| dalonng/hellos | haskell.hello/decimalismToDecimalism.hs | gpl-2.0 | 6 | 0 | 4 | 2 | 4 | 1 | 3 | -1 | -1 |
module Demo where
{-
seq :: a -> b -> b -- îïðåäåëåí êàê ôóíêöèÿ 2 àðãóìåíòîâ
seq _|_ b = _|_ -- çäåñü èñïîëüçóåòñÿ êîíñòðóêöèÿ îñíîâàíèå, êîòîðàÿ îáîçíà÷àåò ðàñõîäÿùèåñÿ âû÷èñëåíèÿ
seq a b = b
-}
{- Ïðè âû÷èñëåíèè êàêèõ èç ïåðå÷èñëåííûõ íèæå ôóíêöèé èñïîëüçîâàíèå seq ïðåäîòâðàòèò íàðàñòàíèå êîëè÷åñòâà íåâû÷èñëåííûõ ðåäåêñîâ ïðè óâåëè÷åíèè çíà÷åíèÿ ïåðâîãî àðãóìåíòà: -}
foo 0 x = x
foo n x = let x' = foo (n - 1) (x + 1)
in x' `seq` x'
bar 0 f = f
bar x f = let f' = \a -> f (x + a)
x' = x - 1
in f' `seq` x' `seq` bar x' f'
baz 0 (x, y) = x + y
baz n (x, y) = let x' = x + 1
y' = y - 1
p = (x', y')
n' = n - 1
in p `seq` n' `seq` baz n' p
quux 0 (x, y) = x + y
quux n (x, y) = let x' = x + 1
y' = y - 1
p = (x', y')
n' = n - 1
in x' `seq` y' `seq` n' `seq` quux n' p
{-
($!) :: (a -> b) -> a -> b
f $! x = x `seq` f x
-} | devtype-blogspot-com/Haskell-Examples | Seq/Demo.hs | gpl-3.0 | 1,016 | 0 | 12 | 406 | 335 | 185 | 150 | 20 | 1 |
dimap f id (p b b) :: p a b | hmemcpy/milewski-ctfp-pdf | src/content/3.10/code/haskell/snippet02.hs | gpl-3.0 | 27 | 1 | 7 | 9 | 28 | 12 | 16 | -1 | -1 |
module SampleCells where
import MetaLife
metaCells = map (map zeroCellCreator) cellsGlider
cells' = [[alive, alive, dead, alive, alive]]
cells'' = [[alive, alive, alive]]
cellsGlider = [ [ dead, alive, dead]
, [alive, dead, dead]
, [alive, alive, alive] ]
cells''' = [ [dead, dead, dead, dead, alive, dead ]
, [dead, dead, dead, alive, dead, dead ]
, [dead, dead, dead, alive, alive, alive ]
, [dead, dead, dead, dead, dead, dead ]
, [dead, dead, dead, dead, dead, dead ]
, [dead, dead, dead, dead, dead, dead ]
, [dead, dead, dead, dead, dead, dead ]
, [dead, dead, dead, dead, dead, dead ]
, [alive, dead, alive, alive, alive, alive ]
, [dead, alive, alive, alive, dead, alive ]
, [alive, dead, dead, alive, alive, alive ]
, [dead, alive, dead, dead, alive, dead ]
, [alive, dead, dead, alive, alive, dead ]
, [dead, alive, alive, dead, dead, alive ]
, [alive, dead, alive, alive, alive, alive ]
, [dead, alive, alive, dead, alive, alive ]
, [alive, dead, alive, dead, alive, alive ]
, [dead, alive, dead, dead, alive, dead ]
, [alive, dead, alive, alive, dead, dead ]
, [dead, alive, alive, dead, alive, alive ]
, [alive, dead, dead, alive, dead, dead ]
]
testLine = [ alive : replicate 28 dead ++ [alive]]
testBlock = [ replicate 14 dead ++ [alive, alive] ++ replicate 14 dead]
fillers n = replicate n (replicate 30 dead)
testCells = testLine
++ fillers 6
++ testLine
++ fillers 6
++ testBlock
++ testBlock
++ fillers 6
++ testLine
++ fillers 6
++ testLine
| graninas/Haskell-Algorithms | Programs/GameOfLifeComonad/SampleCells.hs | gpl-3.0 | 1,724 | 0 | 14 | 529 | 680 | 428 | 252 | 42 | 1 |
module Scaner(
scaner,
Token(..),
Lexem
) where
import qualified Data.List as Lists
import qualified Data.Char as Chars
import IdKeywords
import Delimiters
import StringLiterals
import UnknownLexem
data Token = None | Unknown | IK IdKeyw | D Delims | Str String
deriving(Eq,Ord,Show)
getToken'::String->Int->(String,Token,String)
getToken' [] _ = ([],None,"")
getToken' y@(x:_) n
| x `elem` ['(',')'] = (\(h,d)->(h,D d,"")) $ delim y
| x=='\"' = (\(h,v,m)->(h,Str v,m)) $ stringLiteral y n
| is_id_char x = (\(h,v)->(h,IK v,"")) $ idKeyword y
| otherwise = (\h -> (h,Unknown,unknown_msg n)) $ unknownLexem y
getToken :: String->Int->(String,Token,String)
getToken s n = getToken' (dropWhile Chars.isSpace s) n
unknown_msg :: Int -> String
unknown_msg n = "Нераспознаваемая лексема в строке " ++ show n
type Lexem = (Token,Int)
lineSkaner::String->Int->[(Token,String)]
lineSkaner xs n = reverse $ lineSkaner' xs n []
lineSkaner' :: String->Int->[(Token,String)]->[(Token,String)]
lineSkaner' xs n ts =
if t ==None then
ts
else
lineSkaner' hvst n $ (t,diagnose):ts
where
(hvst,t,diagnose) = getToken xs n
scaner :: String->Either String [Lexem]
scaner xs =
if not . null $ tm then
Left tm
else
Right tl
where
y = reverse . snd . Lists.foldl' ( \(n, ls) s -> (n+1, (s, n):ls) ) (1, []) $ lines xs
w = map convertTokenList $ map (\(s, n) -> (lineSkaner s n, n) ) y
(tl,tm)=(\(ls',ss)->(concat ls', unlines . filter (not . null) . concat $ ss)) $ unzip w
convertTokenList :: ([(Token, String)], Int) -> ([Lexem], [String])
convertTokenList (tss, n) = (reverse lexems, reverse d)
where
(lexems, d) = Lists.foldl' (\(ls, strs) (t, s) -> ((t, n):ls, s:strs) ) ([], []) tss | geva995/murlyka | src/Utils/Scaner.hs | gpl-3.0 | 1,803 | 0 | 16 | 368 | 926 | 522 | 404 | 43 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidEnterprise.Installs.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Requests to remove an app from a device. A call to get or list will
-- still show the app as installed on the device until it is actually
-- removed.
--
-- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.installs.delete@.
module Network.Google.Resource.AndroidEnterprise.Installs.Delete
(
-- * REST Resource
InstallsDeleteResource
-- * Creating a Request
, installsDelete
, InstallsDelete
-- * Request Lenses
, idXgafv
, idUploadProtocol
, idEnterpriseId
, idAccessToken
, idUploadType
, idUserId
, idInstallId
, idDeviceId
, idCallback
) where
import Network.Google.AndroidEnterprise.Types
import Network.Google.Prelude
-- | A resource alias for @androidenterprise.installs.delete@ method which the
-- 'InstallsDelete' request conforms to.
type InstallsDeleteResource =
"androidenterprise" :>
"v1" :>
"enterprises" :>
Capture "enterpriseId" Text :>
"users" :>
Capture "userId" Text :>
"devices" :>
Capture "deviceId" Text :>
"installs" :>
Capture "installId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Requests to remove an app from a device. A call to get or list will
-- still show the app as installed on the device until it is actually
-- removed.
--
-- /See:/ 'installsDelete' smart constructor.
data InstallsDelete =
InstallsDelete'
{ _idXgafv :: !(Maybe Xgafv)
, _idUploadProtocol :: !(Maybe Text)
, _idEnterpriseId :: !Text
, _idAccessToken :: !(Maybe Text)
, _idUploadType :: !(Maybe Text)
, _idUserId :: !Text
, _idInstallId :: !Text
, _idDeviceId :: !Text
, _idCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InstallsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'idXgafv'
--
-- * 'idUploadProtocol'
--
-- * 'idEnterpriseId'
--
-- * 'idAccessToken'
--
-- * 'idUploadType'
--
-- * 'idUserId'
--
-- * 'idInstallId'
--
-- * 'idDeviceId'
--
-- * 'idCallback'
installsDelete
:: Text -- ^ 'idEnterpriseId'
-> Text -- ^ 'idUserId'
-> Text -- ^ 'idInstallId'
-> Text -- ^ 'idDeviceId'
-> InstallsDelete
installsDelete pIdEnterpriseId_ pIdUserId_ pIdInstallId_ pIdDeviceId_ =
InstallsDelete'
{ _idXgafv = Nothing
, _idUploadProtocol = Nothing
, _idEnterpriseId = pIdEnterpriseId_
, _idAccessToken = Nothing
, _idUploadType = Nothing
, _idUserId = pIdUserId_
, _idInstallId = pIdInstallId_
, _idDeviceId = pIdDeviceId_
, _idCallback = Nothing
}
-- | V1 error format.
idXgafv :: Lens' InstallsDelete (Maybe Xgafv)
idXgafv = lens _idXgafv (\ s a -> s{_idXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
idUploadProtocol :: Lens' InstallsDelete (Maybe Text)
idUploadProtocol
= lens _idUploadProtocol
(\ s a -> s{_idUploadProtocol = a})
-- | The ID of the enterprise.
idEnterpriseId :: Lens' InstallsDelete Text
idEnterpriseId
= lens _idEnterpriseId
(\ s a -> s{_idEnterpriseId = a})
-- | OAuth access token.
idAccessToken :: Lens' InstallsDelete (Maybe Text)
idAccessToken
= lens _idAccessToken
(\ s a -> s{_idAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
idUploadType :: Lens' InstallsDelete (Maybe Text)
idUploadType
= lens _idUploadType (\ s a -> s{_idUploadType = a})
-- | The ID of the user.
idUserId :: Lens' InstallsDelete Text
idUserId = lens _idUserId (\ s a -> s{_idUserId = a})
-- | The ID of the product represented by the install, e.g.
-- \"app:com.google.android.gm\".
idInstallId :: Lens' InstallsDelete Text
idInstallId
= lens _idInstallId (\ s a -> s{_idInstallId = a})
-- | The Android ID of the device.
idDeviceId :: Lens' InstallsDelete Text
idDeviceId
= lens _idDeviceId (\ s a -> s{_idDeviceId = a})
-- | JSONP
idCallback :: Lens' InstallsDelete (Maybe Text)
idCallback
= lens _idCallback (\ s a -> s{_idCallback = a})
instance GoogleRequest InstallsDelete where
type Rs InstallsDelete = ()
type Scopes InstallsDelete =
'["https://www.googleapis.com/auth/androidenterprise"]
requestClient InstallsDelete'{..}
= go _idEnterpriseId _idUserId _idDeviceId
_idInstallId
_idXgafv
_idUploadProtocol
_idAccessToken
_idUploadType
_idCallback
(Just AltJSON)
androidEnterpriseService
where go
= buildClient (Proxy :: Proxy InstallsDeleteResource)
mempty
| brendanhay/gogol | gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Installs/Delete.hs | mpl-2.0 | 5,963 | 0 | 23 | 1,537 | 948 | 551 | 397 | 137 | 1 |
{-# LANGUAGE PackageImports #-}
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Image where
import qualified "codeworld-api" CodeWorld.Image as CW
import GHC.Stack
import Internal.Num
import Internal.Picture
import Internal.Text
import "base" Prelude (($))
-- | @image(name, url, w, h)@ is an image from a standard image format.
--
-- * @name@ is a name for the picture, used for debugging.
-- * @url@ is a data-scheme URI for the image data.
-- * @w@ is the width in CodeWorld screen units.
-- * @h@ is the height in CodeWorld screen units.
--
-- The image can be any universally supported format, including SVG, PNG,
-- JPG, etc. SVG should be preferred, as it behaves better with
-- transformations.
image :: HasCallStack => (Text, Text, Number, Number) -> Picture
image (name, url, w, h) = withFrozenCallStack $ CWPic $
CW.image (fromCWText name) (fromCWText url) (toDouble w) (toDouble h)
| alphalambda/codeworld | codeworld-base/src/Image.hs | apache-2.0 | 1,472 | 0 | 8 | 263 | 145 | 90 | 55 | -1 | -1 |
-----------------------------------------------------------------------------
-- Copyright 2019, Ideas project team. This file is distributed under the
-- terms of the Apache License 2.0. For more information, see the files
-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution.
-----------------------------------------------------------------------------
-- |
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable (depends on ghc)
--
-----------------------------------------------------------------------------
module Ideas.Text.OpenMath.Tests (propEncoding) where
import Control.Monad
import Ideas.Text.OpenMath.Dictionary.Arith1
import Ideas.Text.OpenMath.Dictionary.Calculus1
import Ideas.Text.OpenMath.Dictionary.Fns1
import Ideas.Text.OpenMath.Dictionary.Linalg2
import Ideas.Text.OpenMath.Dictionary.List1
import Ideas.Text.OpenMath.Dictionary.Logic1
import Ideas.Text.OpenMath.Dictionary.Nums1
import Ideas.Text.OpenMath.Dictionary.Quant1
import Ideas.Text.OpenMath.Dictionary.Relation1
import Ideas.Text.OpenMath.Dictionary.Transc1
import Ideas.Text.OpenMath.Object
import Test.QuickCheck
arbOMOBJ :: Gen OMOBJ
arbOMOBJ = sized rec
where
symbols = arith1List ++ calculus1List ++ fns1List ++ linalg2List ++
list1List ++ logic1List ++ nums1List ++ quant1List ++
relation1List ++ transc1List
rec 0 = frequency
[ (1, OMI <$> arbitrary)
, (1, (\n -> OMF (fromInteger n / 1000)) <$> arbitrary)
, (1, OMV <$> arbitrary)
, (5, elements $ map OMS symbols)
]
rec n = frequency
[ (1, rec 0)
, (3, choose (1,4) >>= fmap OMA . (`replicateM` f))
, (1, OMBIND <$> f <*> arbitrary <*> f)
]
where
f = rec (n `div` 2)
propEncoding :: Property
propEncoding = forAll arbOMOBJ $ \x -> xml2omobj (omobj2xml x) == Right x | ideas-edu/ideas | src/Ideas/Text/OpenMath/Tests.hs | apache-2.0 | 1,913 | 0 | 16 | 346 | 405 | 246 | 159 | 31 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : VecaTests
-- Copyright : (c) 2017 Pascal Poizat
-- License : Apache-2.0 (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : unknown
--
-- Test file for the Veca module.
-----------------------------------------------------------------------------
module VecaTests (vecaTests)
where
import Test.Tasty
import Test.Tasty.HUnit
-- import Test.Tasty.QuickCheck as QC
-- import Test.Tasty.SmallCheck as SC
import Data.Map (Map, fromList)
import Data.Monoid ((<>))
import Models.Events
import Models.LabelledTransitionSystem as LTS (LabelledTransitionSystem (..),
State (..),
Transition (..))
import Models.Name
import Models.Named (Named (..), prefixBy)
import Models.TimedAutomaton as TA (Bounds (..), Edge (..),
Expression (..),
Location (..),
TimedAutomaton (..),
VariableAssignment (..),
VariableType (..),
VariableTyping (..),
Clock(..),
relabel)
import Trees.Tree
import Veca.Model
import Veca.Operations
vecaTests :: TestTree
vecaTests = testGroup "Tests" [unittests]
unittests :: TestTree
unittests =
testGroup "Unit tests for the Veca module" [uIsValidComponent, uCToTA, uCToCTree, uCTreeToTAList]
uIsValidComponent :: TestTree
uIsValidComponent =
testGroup "Unit tests for isValidComponent"
[testCase "case 2.1" $ isValidComponent (componentType c1) @?= True
,testCase "case 2.1 with internal event" $ isValidComponent (componentType c1tau) @?= True
,testCase "case 2.1 with timeout event" $ isValidComponent (componentType c1theta) @?= True
,testCase "case 2.2" $ isValidComponent (componentType c2) @?= True
,testCase "case 2.3" $ isValidComponent (componentType c3) @?= True
,testCase "case 2.4" $ isValidComponent (componentType c4) @?= True
,testCase "case error internal (int/event)" $ isValidComponent (componentType cerr1) @?= False
,testCase "case error internal (int/inf int)" $ isValidComponent (componentType cerr1b) @?= False
,testCase "case error timeout (2 timeouts)" $ isValidComponent (componentType cerr2) @?= False
,testCase "case error timeout (other than reception)" $ isValidComponent (componentType cerr3) @?= False
,testCase "case error timestep" $ isValidComponent (componentType cerr4) @?= False
]
uCToTA :: TestTree
uCToTA =
testGroup "Unit tests for cToTA"
[testCase "case 2.1" $ cToTA c1 @?= ta1
,testCase "case 2.1 with internal event" $ cToTA c1tau @?= ta1tau
,testCase "case 2.1 with timeout event" $ cToTA c1theta @?= ta1theta
,testCase "case 2.2" $ cToTA c2 @?= ta2
,testCase "case 2.3" $ cToTA c3 @?= ta3
,testCase "case 2.4" $ cToTA c4 @?= ta4]
uCToCTree :: TestTree
uCToCTree = testGroup
"Unit tests for cToCTree"
[testCase "case 2.7 (common names in subtrees)" $ cToCTree c7 @?= tree1]
uCTreeToTAList :: TestTree
uCTreeToTAList = testGroup
"Unit tests for cTreeToTAList"
[ testCase "case 2.7 (common names in subtrees)"
$ cTreeToTAList tree1
@?= tas1
]
b1 :: VName
b1 = Name ["1"]
b2 :: VName
b2 = Name ["2"]
b3 :: VName
b3 = Name ["3"]
b4 :: VName
b4 = Name ["4"]
a :: Operation
a = Operation $ Name ["a"]
b :: Operation
b = Operation $ Name ["b"]
c :: Operation
c = Operation $ Name ["c"]
m1 :: Message
m1 = Message (Name ["m1"]) (MessageType "...")
listDone :: Int -> Map (Name String) VariableTyping
listDone n = fromList
[ ( Name ["done"]
, VariableTyping (Name ["done"]) (IntType bounds) (Just $ Expression "0")
)
]
where bounds = Bounds 0 n
setDone :: Int -> VariableAssignment
setDone n = VariableAssignment (Name ["done"]) (Expression (show n))
ta1 :: VTA
ta1 = TimedAutomaton
n1
[Location "_2", Location "_1", Location "_0", Location "0", Location "1", Location "2"]
(Location "0")
[]
[Location "0", Location "1", Location "2"]
[Clock "0"]
(listDone 3)
[CTReceive a, CTReceive c, CTTau]
[ Edge (Location "1") CTTau [] [] [setDone 3] (Location "_2")
, Edge (Location "_2") (CTReceive c) [] [] [setDone 2] (Location "2")
, Edge (Location "0") CTTau [] [] [setDone 3] (Location "_1")
, Edge (Location "_1") (CTReceive a) [] [] [setDone 1] (Location "1")
, Edge (Location "2") CTTau [] [] [setDone 3] (Location "_0")
, Edge (Location "_0") CTTau [] [] [setDone 3] (Location "2")
]
[]
ta1tau :: VTA
ta1tau = TimedAutomaton
n1
[Location "0", Location "1", Location "2", Location "3"]
(Location "0")
[]
[]
[]
(listDone 3)
[CTReceive a, CTReceive c, CTTau]
[ Edge (Location "0") (CTReceive a) [] [] [setDone 1] (Location "1")
, Edge (Location "1") CTTau [] [] [setDone 3] (Location "2")
, Edge (Location "2") (CTReceive c) [] [] [setDone 2] (Location "3")
, Edge (Location "3") CTTau [] [] [setDone 3] (Location "3")
]
[]
ta1theta :: VTA
ta1theta = TimedAutomaton
n1
[Location "0", Location "1", Location "2"]
(Location "0")
[]
[]
[]
(listDone 3)
[CTReceive a, CTReceive c, CTTau]
[ Edge (Location "0") (CTReceive a) [] [] [setDone 1] (Location "1")
, Edge (Location "1") (CTReceive c) [] [] [setDone 2] (Location "2")
, Edge (Location "2") CTTau [] [] [setDone 3] (Location "2")
]
[]
ta2 :: VTA
ta2 = TimedAutomaton
n2
[Location "0", Location "1", Location "2"]
(Location "0")
[]
[]
[]
(listDone 3)
[CTInvoke a, CTReceive b, CTTau]
[ Edge (Location "0") (CTInvoke a) [] [] [setDone 1] (Location "1")
, Edge (Location "1") (CTReceive b) [] [] [setDone 2] (Location "2")
, Edge (Location "2") CTTau [] [] [setDone 3] (Location "2")
]
[]
ta3 :: VTA
ta3 = TimedAutomaton
n3
[Location "0", Location "1"]
(Location "0")
[]
[]
[]
(listDone 2)
[CTReceive a, CTTau]
[ Edge (Location "0") (CTReceive a) [] [] [setDone 1] (Location "1")
, Edge (Location "1") CTTau [] [] [setDone 2] (Location "1")
]
[]
ta4 :: VTA
ta4 = TimedAutomaton
n4
[Location "0", Location "1", Location "2"]
(Location "0")
[]
[]
[]
(listDone 3)
[CTInvoke a, CTInvoke b, CTTau]
[ Edge (Location "0") (CTInvoke a) [] [] [setDone 1] (Location "1")
, Edge (Location "1") (CTInvoke b) [] [] [setDone 2] (Location "2")
, Edge (Location "2") CTTau [] [] [setDone 3] (Location "2")
]
[]
n1 :: VName
n1 = Name ["c1"]
nameC1 :: VName
nameC1 = Name ["Type1"]
c1 :: ComponentInstance
c1 = ComponentInstance n1 $ BasicComponent nameC1 sig beh
where
sig = Signature [a, c]
[]
(fromList [(a, m1), (c, m1)])
(fromList [(a, Nothing), (c, Nothing)])
beh = LabelledTransitionSystem
n1
[EventLabel . CReceive $ a, EventLabel . CReceive $ c]
[State "0", State "1", State "2"]
(State "0")
[State "2"]
[ Transition (State "0") (EventLabel . CReceive $ a) (State "1")
, Transition (State "1") (EventLabel . CReceive $ c) (State "2")
]
c1tau :: ComponentInstance
c1tau = ComponentInstance n1 $ BasicComponent nameC1 sig beh
where
sig = Signature [a, c]
[]
(fromList [(a, m1), (c, m1)])
(fromList [(a, Nothing), (c, Nothing)])
beh = LabelledTransitionSystem
n1
[EventLabel . CReceive $ a, EventLabel . CReceive $ c, InternalLabel (TimeValue 2) (TimeValue 4)]
[State "0", State "1", State "2", State "3"]
(State "0")
[State "3"]
[ Transition (State "0") (EventLabel . CReceive $ a) (State "1")
, Transition (State "1") (InternalLabel (TimeValue 2) (TimeValue 4)) (State "2")
, Transition (State "2") (EventLabel . CReceive $ c) (State "3")
]
c1theta :: ComponentInstance
c1theta = ComponentInstance n1 $ BasicComponent nameC1 sig beh
where
sig = Signature [a, c]
[]
(fromList [(a, m1), (c, m1)])
(fromList [(a, Just m1), (c, Nothing)])
beh = LabelledTransitionSystem
n1
[ EventLabel . CReceive $ a
, EventLabel . CReply $ a
, EventLabel . CReceive $ c
, TimeoutLabel 15
, InternalLabel (TimeValue 2) (TimeValue 4)
, InternalLabel (TimeValue 0) InfiniteValue]
[State "0", State "1", State "2", State "3", State "4", State "5"]
(State "0")
[State "5"]
[ Transition (State "0") (EventLabel . CReceive $ a) (State "1")
, Transition (State "1") (EventLabel . CReceive $ c) (State "2")
, Transition (State "1") (TimeoutLabel 15) (State "3")
, Transition (State "2") (InternalLabel (TimeValue 0) InfiniteValue) (State "4")
, Transition (State "3") (InternalLabel (TimeValue 2) (TimeValue 4)) (State "4")
, Transition (State "4") (EventLabel . CReply $ a) (State "5")
]
n2 :: VName
n2 = Name ["c2"]
nameC2 :: VName
nameC2 = Name ["Type2"]
c2 :: ComponentInstance
c2 = ComponentInstance n2 $ BasicComponent nameC2 sig beh
where
sig = Signature [b]
[a]
(fromList [(a, m1), (b, m1)])
(fromList [(a, Nothing), (b, Nothing)])
beh = LabelledTransitionSystem
n2
[EventLabel . CInvoke $ a, EventLabel . CReceive $ b]
[State "0", State "1", State "2"]
(State "0")
[State "2"]
[ Transition (State "0") (EventLabel . CInvoke $ a) (State "1")
, Transition (State "1") (EventLabel . CReceive $ b) (State "2")
]
n3 :: VName
n3 = Name ["c3"]
nameC3 :: VName
nameC3 = Name ["Type3"]
c3 :: ComponentInstance
c3 = ComponentInstance n3 $ BasicComponent nameC3 sig beh
where
sig = Signature [a] [] (fromList [(a, m1)]) (fromList [(a, Nothing)])
beh = LabelledTransitionSystem
n3
[EventLabel . CReceive $ a]
[State "0", State "1"]
(State "0")
[State "1"]
[Transition (State "0") (EventLabel . CReceive $ a) (State "1")]
n4 :: VName
n4 = Name ["c4"]
nameC4 :: VName
nameC4 = Name ["Type4"]
c4 :: ComponentInstance
c4 = ComponentInstance n4 $ BasicComponent nameC4 sig beh
where
sig = Signature []
[a, b]
(fromList [(a, m1), (b, m1)])
(fromList [(a, Nothing), (b, Nothing)])
beh = LabelledTransitionSystem
n4
[EventLabel . CInvoke $ a, EventLabel . CInvoke $ b]
[State "0", State "1", State "2"]
(State "0")
[State "2"]
[ Transition (State "0") (EventLabel . CInvoke $ a) (State "1")
, Transition (State "1") (EventLabel . CInvoke $ b) (State "2")
]
n5 :: VName
n5 = Name ["c5"]
c5 :: ComponentInstance
c5 = ComponentInstance n5 $ CompositeComponent n5 sig cs inb exb
where
sig = Signature [b, c]
[]
(fromList [(b, m1), (c, m1)])
(fromList [(b, Nothing), (c, Nothing)])
cs = [c1, c2]
inb = [Binding Internal b1 (JoinPoint n2 a) (JoinPoint n1 a)]
exb =
[ Binding External b2 (JoinPoint self b) (JoinPoint n2 b)
, Binding External b3 (JoinPoint self c) (JoinPoint n1 c)
]
n6 :: VName
n6 = Name ["c6"]
c6 :: ComponentInstance
c6 = ComponentInstance n6 $ CompositeComponent n6 sig cs inb exb
where
sig = Signature [] [b] (fromList [(b, m1)]) (fromList [(b, Nothing)])
cs = [c3, c4]
inb = [Binding Internal b1 (JoinPoint n4 a) (JoinPoint n3 a)]
exb = [Binding External b2 (JoinPoint n4 b) (JoinPoint self b)]
n7 :: VName
n7 = Name ["c7"]
c7 :: ComponentInstance
c7 = ComponentInstance n7 $ CompositeComponent n7 sig cs inb exb
where
sig = Signature [c] [] (fromList [(c, m1)]) (fromList [(c, Nothing)])
cs = [c5, c6]
inb = [Binding Internal b1 (JoinPoint n6 b) (JoinPoint n5 b)]
exb = [Binding External b2 (JoinPoint self c) (JoinPoint n5 c)]
-- error internal (int/event)
cerr1 :: ComponentInstance
cerr1 = ComponentInstance n1 $ BasicComponent nameC1 sig beh
where
sig = Signature [a]
[]
(fromList [(a, m1)])
(fromList [(a, Nothing)])
beh = LabelledTransitionSystem
n1
[EventLabel . CReceive $ a, InternalLabel (TimeValue 2) (TimeValue 4)]
[State "0", State "1", State "2"]
(State "0")
[State "1", State "2"]
[ Transition (State "0") (InternalLabel (TimeValue 2) (TimeValue 4)) (State "1")
, Transition (State "0") (EventLabel . CReceive $ c) (State "2")
]
-- error internal (int/inf int)
cerr1b :: ComponentInstance
cerr1b = ComponentInstance n1 $ BasicComponent nameC1 sig beh
where
sig = Signature [a]
[]
(fromList [(a, m1)])
(fromList [(a, Nothing)])
beh = LabelledTransitionSystem
n1
[EventLabel . CReceive $ a, InternalLabel (TimeValue 2) (TimeValue 4), InternalLabel (TimeValue 0) InfiniteValue]
[State "0", State "1", State "2"]
(State "0")
[State "1", State "2"]
[ Transition (State "0") (InternalLabel (TimeValue 2) (TimeValue 4)) (State "1")
, Transition (State "0") (InternalLabel (TimeValue 0) InfiniteValue) (State "2")
]
-- error timeout (2 timeouts)
cerr2 :: ComponentInstance
cerr2 = ComponentInstance n1 $ BasicComponent nameC1 sig beh
where
sig = Signature [a]
[]
(fromList [(a, m1)])
(fromList [(a, Nothing)])
beh = LabelledTransitionSystem
n1
[EventLabel . CReceive $ a, TimeoutLabel 15, TimeoutLabel 10]
[State "0", State "1", State "2", State "3"]
(State "0")
[State "2", State "3"]
[ Transition (State "0") (EventLabel . CReceive $a) (State "1")
, Transition (State "1") (TimeoutLabel 15) (State "2")
, Transition (State "1") (TimeoutLabel 10) (State "3")
]
-- error timeout (other than reception)
cerr3 :: ComponentInstance
cerr3 = ComponentInstance n1 $ BasicComponent nameC1 sig beh
where
sig = Signature [a]
[b]
(fromList [(a, m1),(b,m1)])
(fromList [(a, Nothing),(b, Nothing)])
beh = LabelledTransitionSystem
n1
[EventLabel . CReceive $ a, TimeoutLabel 15, EventLabel . CInvoke $ b]
[State "0", State "1", State "2", State "3"]
(State "0")
[State "2", State "3"]
[ Transition (State "0") (EventLabel . CReceive $ a) (State "1")
, Transition (State "1") (TimeoutLabel 15) (State "2")
, Transition (State "1") (EventLabel . CInvoke $ b) (State "3")
]
-- error time step
cerr4 :: ComponentInstance
cerr4 = ComponentInstance n1 $ BasicComponent nameC1 sig beh
where
sig = Signature [a]
[]
(fromList [(a, m1)])
(fromList [(a, Nothing)])
beh = LabelledTransitionSystem
n1
[EventLabel . CReceive $ a, InternalLabel (TimeValue 2) (TimeValue 4), InternalLabel (TimeValue 2) InfiniteValue]
[State "0", State "1", State "2"]
(State "0")
[State "1", State "2"]
[ Transition (State "0") (InternalLabel (TimeValue 2) (TimeValue 4)) (State "1")
, Transition (State "0") (InternalLabel (TimeValue 2) InfiniteValue) (State "2")
]
tree1 :: VCTree
tree1 = Node c7 [(n5, st5), (n6, st6)]
where
st5 = Node c5 [(n1, st1), (n2, st2)]
st6 = Node c6 [(n3, st3), (n4, st4)]
st1 = Leaf c1
st2 = Leaf c2
st3 = Leaf c3
st4 = Leaf c4
tree1' :: VTATree
tree1' = Node c7 [(n5, st5'), (n6, st6')]
where
st5' = Node c5 [(n1, st1'), (n2, st2')]
st6' = Node c6 [(n3, st3'), (n4, st4')]
st1' = Leaf ta1
st2' = Leaf ta2
st3' = Leaf ta3
st4' = Leaf ta4
ta1' :: VTA
ta1' = prefixBy (n7 <> n5) $ relabel sub1 ta1
where
sub1 =
[ (CTReceive a, CTReceive $ indexBy (n7 <> n5 <> b1) a)
, (CTReceive c, CTReceive $ indexBy (n7 <> b2) c)
]
ta2' :: VTA
ta2' = prefixBy (n7 <> n5) $ relabel sub2 ta2
where
sub2 =
[ (CTInvoke a , CTInvoke $ indexBy (n7 <> n5 <> b1) a)
, (CTReceive b, CTReceive $ indexBy (n7 <> b1) b)
]
ta3' :: VTA
ta3' = prefixBy (n7 <> n6) $ relabel sub3 ta3
where sub3 = [(CTReceive a, CTReceive $ indexBy (n7 <> n6 <> b1) a)]
ta4' :: VTA
ta4' = prefixBy (n7 <> n6) $ relabel sub4 ta4
where
sub4 =
[ (CTInvoke a, CTInvoke $ indexBy (n7 <> n6 <> b1) a)
, (CTInvoke b, CTInvoke $ indexBy (n7 <> b1) b)
]
tas1 :: [VTA]
tas1 = [ta1', ta2', ta3', ta4']
| pascalpoizat/veca-haskell | test/VecaTests.hs | apache-2.0 | 16,917 | 0 | 13 | 4,797 | 6,572 | 3,481 | 3,091 | 414 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module DB.Models.Tournament (
Tournament(..)
) where
import Data.Dates (DateTime(..)) -- only required for mock!
import Control.Monad (liftM)
import Data.Tournament
import DB.Model (Model)
import qualified DB.Model as Model
import qualified DB.Models.Location
instance Eq Tournament where
t1 == t2 = _id t1 == _id t2
instance Ord Tournament where
compare t1 t2 = compare (_id t1) (_id t2)
instance Model Tournament where
id = _id
all = do
locations <- Model.all
return [
Tournament {
_id = 0,
date = DateTime 2016 5 15 10 0 0,
name = "Milicka Wiosna",
location = locations !! 1,
tournamentType = Pairs,
scoring = TopScore,
rank = Regional,
fee = 30
},
Tournament {
_id = 1,
date = DateTime 2016 5 21 10 0 0,
name = "Błękitna Wstęga Ordy",
location = locations !! 5,
tournamentType = Teams,
scoring = Patton,
rank = National,
fee = 80
},
Tournament {
_id = 2,
date = DateTime 2016 5 16 10 0 0,
name = "Gwardia - Kuźniki",
location = locations !! 5,
tournamentType = Pairs,
scoring = TopScore,
rank = Districtal,
fee = 15
},
Tournament {
_id = 3,
date = DateTime 2016 5 25 10 0 0,
name = "Poznański Mityng Brydżowy",
location = locations !! 2,
tournamentType = Pairs,
scoring = TopScore,
rank = National,
fee = 40
},
Tournament {
_id = 4,
date = DateTime 2016 6 5 10 0 0,
name = "Puchar Prezydenta Mielca",
location = head locations,
tournamentType = Pairs,
scoring = TopScore,
rank = Regional,
fee = 30
},
Tournament {
_id = 5,
date = DateTime 2016 6 15 10 0 0,
name = "Coś tam gdzieś tam",
location = locations !! 5,
tournamentType = Pairs,
scoring = IMP,
rank = Districtal,
fee = 20
},
Tournament {
_id = 6,
date = DateTime 2016 5 29 10 0 0,
name = "Budimex Grand Prix Polski Par",
location = locations !! 2,
tournamentType = Pairs,
scoring = TopScore,
rank = National,
fee = 80
},
Tournament {
_id = 7,
date = DateTime 2016 6 6 10 0 0,
name = "Gwardia - Kuźniki",
location = locations !! 5,
tournamentType = Pairs,
scoring = TopScore,
rank = Districtal,
fee = 15
},
Tournament {
_id = 8,
date = DateTime 2016 8 28 10 0 0,
name = "Budimex Grand Prix Polski Par",
location = locations !! 3,
tournamentType = Pairs,
scoring = TopScore,
rank = National,
fee = 80
},
Tournament {
_id = 9,
date = DateTime 2016 7 12 10 0 0,
name = "Kongresowy Turniej Par na IMPy",
location = locations !! 4,
tournamentType = Pairs,
scoring = IMP,
rank = National,
fee = 30
}
]
| Sventimir/turniejowo | src/DB/Models/Tournament.hs | apache-2.0 | 5,107 | 0 | 12 | 3,157 | 868 | 523 | 345 | 108 | 0 |
module Model.Simple.IVar where
import Control.Concurrent.MVar
import Control.Exception
import Control.Monad
import GHC.IO
import Model.Exception
data IVar a = IVar {-# UNPACK #-} !(MVar a) a
newIVar :: IO (IVar a)
newIVar = do
x <- newEmptyMVar
IVar x <$> unsafeDupableInterleaveIO (readMVar x) `catch` \BlockedIndefinitelyOnMVar -> throw BlockedIndefinitelyOnIVar
readIVar :: IVar a -> a
readIVar (IVar _ a) = a
writeIVar :: Eq a => IVar a -> a -> IO ()
writeIVar (IVar m _) a = do
t <- tryPutMVar m a
unless t $ do
b <- readMVar m
unless (a == b) $ throwIO Contradiction
unsafeWriteIVar :: IVar a -> a -> IO ()
unsafeWriteIVar (IVar m _) a = () <$ tryPutMVar m a
| ekmett/models | src/Model/Simple/IVar.hs | bsd-2-clause | 689 | 0 | 13 | 141 | 288 | 143 | 145 | 21 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDockWidget.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:30
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QDockWidget (
QqDockWidget(..)
,setFloating
,setTitleBarWidget
,titleBarWidget
,qDockWidget_delete
,qDockWidget_deleteLater
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QDockWidget
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 (QDockWidget ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QDockWidget_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QDockWidget_userMethod" qtc_QDockWidget_userMethod :: Ptr (TQDockWidget a) -> CInt -> IO ()
instance QuserMethod (QDockWidgetSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QDockWidget_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QDockWidget ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QDockWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QDockWidget_userMethodVariant" qtc_QDockWidget_userMethodVariant :: Ptr (TQDockWidget a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QDockWidgetSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QDockWidget_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqDockWidget x1 where
qDockWidget :: x1 -> IO (QDockWidget ())
instance QqDockWidget (()) where
qDockWidget ()
= withQDockWidgetResult $
qtc_QDockWidget
foreign import ccall "qtc_QDockWidget" qtc_QDockWidget :: IO (Ptr (TQDockWidget ()))
instance QqDockWidget ((String)) where
qDockWidget (x1)
= withQDockWidgetResult $
withCWString x1 $ \cstr_x1 ->
qtc_QDockWidget1 cstr_x1
foreign import ccall "qtc_QDockWidget1" qtc_QDockWidget1 :: CWString -> IO (Ptr (TQDockWidget ()))
instance QqDockWidget ((QWidget t1)) where
qDockWidget (x1)
= withQDockWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget2 cobj_x1
foreign import ccall "qtc_QDockWidget2" qtc_QDockWidget2 :: Ptr (TQWidget t1) -> IO (Ptr (TQDockWidget ()))
instance QqDockWidget ((QWidget t1, WindowFlags)) where
qDockWidget (x1, x2)
= withQDockWidgetResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget3 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QDockWidget3" qtc_QDockWidget3 :: Ptr (TQWidget t1) -> CLong -> IO (Ptr (TQDockWidget ()))
instance QqDockWidget ((String, QWidget t2)) where
qDockWidget (x1, x2)
= withQDockWidgetResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDockWidget4 cstr_x1 cobj_x2
foreign import ccall "qtc_QDockWidget4" qtc_QDockWidget4 :: CWString -> Ptr (TQWidget t2) -> IO (Ptr (TQDockWidget ()))
instance QqDockWidget ((String, QWidget t2, WindowFlags)) where
qDockWidget (x1, x2, x3)
= withQDockWidgetResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDockWidget5 cstr_x1 cobj_x2 (toCLong $ qFlags_toInt x3)
foreign import ccall "qtc_QDockWidget5" qtc_QDockWidget5 :: CWString -> Ptr (TQWidget t2) -> CLong -> IO (Ptr (TQDockWidget ()))
instance QallowedAreas (QDockWidget a) (()) (IO (DockWidgetAreas)) where
allowedAreas x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_allowedAreas cobj_x0
foreign import ccall "qtc_QDockWidget_allowedAreas" qtc_QDockWidget_allowedAreas :: Ptr (TQDockWidget a) -> IO CLong
instance QchangeEvent (QDockWidget ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_changeEvent_h" qtc_QDockWidget_changeEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QDockWidgetSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_changeEvent_h cobj_x0 cobj_x1
instance QcloseEvent (QDockWidget ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_closeEvent_h" qtc_QDockWidget_closeEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QDockWidgetSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_closeEvent_h cobj_x0 cobj_x1
instance Qevent (QDockWidget ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_event_h" qtc_QDockWidget_event_h :: Ptr (TQDockWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QDockWidgetSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_event_h cobj_x0 cobj_x1
instance Qfeatures (QDockWidget a) (()) (IO (DockWidgetFeatures)) where
features x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_features cobj_x0
foreign import ccall "qtc_QDockWidget_features" qtc_QDockWidget_features :: Ptr (TQDockWidget a) -> IO CLong
instance QinitStyleOption (QDockWidget ()) ((QStyleOptionDockWidget t1)) where
initStyleOption x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_initStyleOption cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_initStyleOption" qtc_QDockWidget_initStyleOption :: Ptr (TQDockWidget a) -> Ptr (TQStyleOptionDockWidget t1) -> IO ()
instance QinitStyleOption (QDockWidgetSc a) ((QStyleOptionDockWidget t1)) where
initStyleOption x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_initStyleOption cobj_x0 cobj_x1
instance QisAreaAllowed (QDockWidget a) ((DockWidgetArea)) where
isAreaAllowed x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_isAreaAllowed cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QDockWidget_isAreaAllowed" qtc_QDockWidget_isAreaAllowed :: Ptr (TQDockWidget a) -> CLong -> IO CBool
instance QisFloating (QDockWidget a) (()) where
isFloating x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_isFloating cobj_x0
foreign import ccall "qtc_QDockWidget_isFloating" qtc_QDockWidget_isFloating :: Ptr (TQDockWidget a) -> IO CBool
instance QpaintEvent (QDockWidget ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_paintEvent_h" qtc_QDockWidget_paintEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QDockWidgetSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_paintEvent_h cobj_x0 cobj_x1
instance QsetAllowedAreas (QDockWidget a) ((DockWidgetAreas)) where
setAllowedAreas x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_setAllowedAreas cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QDockWidget_setAllowedAreas" qtc_QDockWidget_setAllowedAreas :: Ptr (TQDockWidget a) -> CLong -> IO ()
instance QsetFeatures (QDockWidget a) ((DockWidgetFeatures)) where
setFeatures x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_setFeatures cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QDockWidget_setFeatures" qtc_QDockWidget_setFeatures :: Ptr (TQDockWidget a) -> CLong -> IO ()
setFloating :: QDockWidget a -> ((Bool)) -> IO ()
setFloating x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_setFloating cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDockWidget_setFloating" qtc_QDockWidget_setFloating :: Ptr (TQDockWidget a) -> CBool -> IO ()
setTitleBarWidget :: QDockWidget a -> ((QWidget t1)) -> IO ()
setTitleBarWidget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_setTitleBarWidget cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_setTitleBarWidget" qtc_QDockWidget_setTitleBarWidget :: Ptr (TQDockWidget a) -> Ptr (TQWidget t1) -> IO ()
instance QsetWidget (QDockWidget a) ((QWidget t1)) where
setWidget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_setWidget cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_setWidget" qtc_QDockWidget_setWidget :: Ptr (TQDockWidget a) -> Ptr (TQWidget t1) -> IO ()
titleBarWidget :: QDockWidget a -> (()) -> IO (QWidget ())
titleBarWidget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_titleBarWidget cobj_x0
foreign import ccall "qtc_QDockWidget_titleBarWidget" qtc_QDockWidget_titleBarWidget :: Ptr (TQDockWidget a) -> IO (Ptr (TQWidget ()))
instance QtoggleViewAction (QDockWidget a) (()) where
toggleViewAction x0 ()
= withQActionResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_toggleViewAction cobj_x0
foreign import ccall "qtc_QDockWidget_toggleViewAction" qtc_QDockWidget_toggleViewAction :: Ptr (TQDockWidget a) -> IO (Ptr (TQAction ()))
instance Qwidget (QDockWidget a) (()) where
widget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_widget cobj_x0
foreign import ccall "qtc_QDockWidget_widget" qtc_QDockWidget_widget :: Ptr (TQDockWidget a) -> IO (Ptr (TQWidget ()))
qDockWidget_delete :: QDockWidget a -> IO ()
qDockWidget_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_delete cobj_x0
foreign import ccall "qtc_QDockWidget_delete" qtc_QDockWidget_delete :: Ptr (TQDockWidget a) -> IO ()
qDockWidget_deleteLater :: QDockWidget a -> IO ()
qDockWidget_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_deleteLater cobj_x0
foreign import ccall "qtc_QDockWidget_deleteLater" qtc_QDockWidget_deleteLater :: Ptr (TQDockWidget a) -> IO ()
instance QactionEvent (QDockWidget ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_actionEvent_h" qtc_QDockWidget_actionEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QDockWidgetSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QDockWidget ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_addAction" qtc_QDockWidget_addAction :: Ptr (TQDockWidget a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QDockWidgetSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_addAction cobj_x0 cobj_x1
instance QcontextMenuEvent (QDockWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_contextMenuEvent_h" qtc_QDockWidget_contextMenuEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QDockWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_contextMenuEvent_h cobj_x0 cobj_x1
instance Qcreate (QDockWidget ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_create cobj_x0
foreign import ccall "qtc_QDockWidget_create" qtc_QDockWidget_create :: Ptr (TQDockWidget a) -> IO ()
instance Qcreate (QDockWidgetSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_create cobj_x0
instance Qcreate (QDockWidget ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_create1" qtc_QDockWidget_create1 :: Ptr (TQDockWidget a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QDockWidgetSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_create1 cobj_x0 cobj_x1
instance Qcreate (QDockWidget ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QDockWidget_create2" qtc_QDockWidget_create2 :: Ptr (TQDockWidget a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QDockWidgetSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QDockWidget ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QDockWidget_create3" qtc_QDockWidget_create3 :: Ptr (TQDockWidget a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QDockWidgetSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QDockWidget ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_destroy cobj_x0
foreign import ccall "qtc_QDockWidget_destroy" qtc_QDockWidget_destroy :: Ptr (TQDockWidget a) -> IO ()
instance Qdestroy (QDockWidgetSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_destroy cobj_x0
instance Qdestroy (QDockWidget ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDockWidget_destroy1" qtc_QDockWidget_destroy1 :: Ptr (TQDockWidget a) -> CBool -> IO ()
instance Qdestroy (QDockWidgetSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QDockWidget ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QDockWidget_destroy2" qtc_QDockWidget_destroy2 :: Ptr (TQDockWidget a) -> CBool -> CBool -> IO ()
instance Qdestroy (QDockWidgetSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QDockWidget ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_devType_h cobj_x0
foreign import ccall "qtc_QDockWidget_devType_h" qtc_QDockWidget_devType_h :: Ptr (TQDockWidget a) -> IO CInt
instance QdevType (QDockWidgetSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_devType_h cobj_x0
instance QdragEnterEvent (QDockWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_dragEnterEvent_h" qtc_QDockWidget_dragEnterEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QDockWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QDockWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_dragLeaveEvent_h" qtc_QDockWidget_dragLeaveEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QDockWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QDockWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_dragMoveEvent_h" qtc_QDockWidget_dragMoveEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QDockWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QDockWidget ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_dropEvent_h" qtc_QDockWidget_dropEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QDockWidgetSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QDockWidget ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDockWidget_enabledChange" qtc_QDockWidget_enabledChange :: Ptr (TQDockWidget a) -> CBool -> IO ()
instance QenabledChange (QDockWidgetSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QDockWidget ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_enterEvent_h" qtc_QDockWidget_enterEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QDockWidgetSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_enterEvent_h cobj_x0 cobj_x1
instance QfocusInEvent (QDockWidget ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_focusInEvent_h" qtc_QDockWidget_focusInEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QDockWidgetSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_focusInEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QDockWidget ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_focusNextChild cobj_x0
foreign import ccall "qtc_QDockWidget_focusNextChild" qtc_QDockWidget_focusNextChild :: Ptr (TQDockWidget a) -> IO CBool
instance QfocusNextChild (QDockWidgetSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_focusNextChild cobj_x0
instance QfocusNextPrevChild (QDockWidget ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDockWidget_focusNextPrevChild" qtc_QDockWidget_focusNextPrevChild :: Ptr (TQDockWidget a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QDockWidgetSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusOutEvent (QDockWidget ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_focusOutEvent_h" qtc_QDockWidget_focusOutEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QDockWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_focusOutEvent_h cobj_x0 cobj_x1
instance QfocusPreviousChild (QDockWidget ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_focusPreviousChild cobj_x0
foreign import ccall "qtc_QDockWidget_focusPreviousChild" qtc_QDockWidget_focusPreviousChild :: Ptr (TQDockWidget a) -> IO CBool
instance QfocusPreviousChild (QDockWidgetSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_focusPreviousChild cobj_x0
instance QfontChange (QDockWidget ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_fontChange" qtc_QDockWidget_fontChange :: Ptr (TQDockWidget a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QDockWidgetSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QDockWidget ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QDockWidget_heightForWidth_h" qtc_QDockWidget_heightForWidth_h :: Ptr (TQDockWidget a) -> CInt -> IO CInt
instance QheightForWidth (QDockWidgetSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QDockWidget ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_hideEvent_h" qtc_QDockWidget_hideEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QDockWidgetSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_hideEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QDockWidget ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_inputMethodEvent" qtc_QDockWidget_inputMethodEvent :: Ptr (TQDockWidget a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QDockWidgetSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QDockWidget ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QDockWidget_inputMethodQuery_h" qtc_QDockWidget_inputMethodQuery_h :: Ptr (TQDockWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QDockWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QkeyPressEvent (QDockWidget ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_keyPressEvent_h" qtc_QDockWidget_keyPressEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QDockWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_keyPressEvent_h cobj_x0 cobj_x1
instance QkeyReleaseEvent (QDockWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_keyReleaseEvent_h" qtc_QDockWidget_keyReleaseEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QDockWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_keyReleaseEvent_h cobj_x0 cobj_x1
instance QlanguageChange (QDockWidget ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_languageChange cobj_x0
foreign import ccall "qtc_QDockWidget_languageChange" qtc_QDockWidget_languageChange :: Ptr (TQDockWidget a) -> IO ()
instance QlanguageChange (QDockWidgetSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_languageChange cobj_x0
instance QleaveEvent (QDockWidget ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_leaveEvent_h" qtc_QDockWidget_leaveEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QDockWidgetSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QDockWidget ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QDockWidget_metric" qtc_QDockWidget_metric :: Ptr (TQDockWidget a) -> CLong -> IO CInt
instance Qmetric (QDockWidgetSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance QqminimumSizeHint (QDockWidget ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QDockWidget_minimumSizeHint_h" qtc_QDockWidget_minimumSizeHint_h :: Ptr (TQDockWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QDockWidgetSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QDockWidget ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QDockWidget_minimumSizeHint_qth_h" qtc_QDockWidget_minimumSizeHint_qth_h :: Ptr (TQDockWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QDockWidgetSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QmouseDoubleClickEvent (QDockWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_mouseDoubleClickEvent_h" qtc_QDockWidget_mouseDoubleClickEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QDockWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QDockWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_mouseMoveEvent_h" qtc_QDockWidget_mouseMoveEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QDockWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QDockWidget ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_mousePressEvent_h" qtc_QDockWidget_mousePressEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QDockWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QDockWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_mouseReleaseEvent_h" qtc_QDockWidget_mouseReleaseEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QDockWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_mouseReleaseEvent_h cobj_x0 cobj_x1
instance Qmove (QDockWidget ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QDockWidget_move1" qtc_QDockWidget_move1 :: Ptr (TQDockWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QDockWidgetSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QDockWidget ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QDockWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QDockWidget_move_qth" qtc_QDockWidget_move_qth :: Ptr (TQDockWidget a) -> CInt -> CInt -> IO ()
instance Qmove (QDockWidgetSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QDockWidget_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QDockWidget ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_move cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_move" qtc_QDockWidget_move :: Ptr (TQDockWidget a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QDockWidgetSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_move cobj_x0 cobj_x1
instance QmoveEvent (QDockWidget ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_moveEvent_h" qtc_QDockWidget_moveEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QDockWidgetSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QDockWidget ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_paintEngine_h cobj_x0
foreign import ccall "qtc_QDockWidget_paintEngine_h" qtc_QDockWidget_paintEngine_h :: Ptr (TQDockWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QDockWidgetSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_paintEngine_h cobj_x0
instance QpaletteChange (QDockWidget ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_paletteChange" qtc_QDockWidget_paletteChange :: Ptr (TQDockWidget a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QDockWidgetSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QDockWidget ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_repaint cobj_x0
foreign import ccall "qtc_QDockWidget_repaint" qtc_QDockWidget_repaint :: Ptr (TQDockWidget a) -> IO ()
instance Qrepaint (QDockWidgetSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_repaint cobj_x0
instance Qrepaint (QDockWidget ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QDockWidget_repaint2" qtc_QDockWidget_repaint2 :: Ptr (TQDockWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QDockWidgetSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QDockWidget ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_repaint1" qtc_QDockWidget_repaint1 :: Ptr (TQDockWidget a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QDockWidgetSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QDockWidget ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_resetInputContext cobj_x0
foreign import ccall "qtc_QDockWidget_resetInputContext" qtc_QDockWidget_resetInputContext :: Ptr (TQDockWidget a) -> IO ()
instance QresetInputContext (QDockWidgetSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_resetInputContext cobj_x0
instance Qresize (QDockWidget ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QDockWidget_resize1" qtc_QDockWidget_resize1 :: Ptr (TQDockWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QDockWidgetSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QDockWidget ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_resize" qtc_QDockWidget_resize :: Ptr (TQDockWidget a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QDockWidgetSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_resize cobj_x0 cobj_x1
instance Qresize (QDockWidget ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QDockWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QDockWidget_resize_qth" qtc_QDockWidget_resize_qth :: Ptr (TQDockWidget a) -> CInt -> CInt -> IO ()
instance Qresize (QDockWidgetSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QDockWidget_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QresizeEvent (QDockWidget ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_resizeEvent_h" qtc_QDockWidget_resizeEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QDockWidgetSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_resizeEvent_h cobj_x0 cobj_x1
instance QsetGeometry (QDockWidget ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QDockWidget_setGeometry1" qtc_QDockWidget_setGeometry1 :: Ptr (TQDockWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QDockWidgetSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QDockWidget ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_setGeometry" qtc_QDockWidget_setGeometry :: Ptr (TQDockWidget a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QDockWidgetSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QDockWidget ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QDockWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QDockWidget_setGeometry_qth" qtc_QDockWidget_setGeometry_qth :: Ptr (TQDockWidget a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QDockWidgetSc 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_QDockWidget_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QDockWidget ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDockWidget_setMouseTracking" qtc_QDockWidget_setMouseTracking :: Ptr (TQDockWidget a) -> CBool -> IO ()
instance QsetMouseTracking (QDockWidgetSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_setMouseTracking cobj_x0 (toCBool x1)
instance QsetVisible (QDockWidget ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDockWidget_setVisible_h" qtc_QDockWidget_setVisible_h :: Ptr (TQDockWidget a) -> CBool -> IO ()
instance QsetVisible (QDockWidgetSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QDockWidget ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_showEvent_h" qtc_QDockWidget_showEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QDockWidgetSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_showEvent_h cobj_x0 cobj_x1
instance QqsizeHint (QDockWidget ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_sizeHint_h cobj_x0
foreign import ccall "qtc_QDockWidget_sizeHint_h" qtc_QDockWidget_sizeHint_h :: Ptr (TQDockWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QDockWidgetSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_sizeHint_h cobj_x0
instance QsizeHint (QDockWidget ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QDockWidget_sizeHint_qth_h" qtc_QDockWidget_sizeHint_qth_h :: Ptr (TQDockWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QDockWidgetSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QtabletEvent (QDockWidget ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_tabletEvent_h" qtc_QDockWidget_tabletEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QDockWidgetSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QDockWidget ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_updateMicroFocus cobj_x0
foreign import ccall "qtc_QDockWidget_updateMicroFocus" qtc_QDockWidget_updateMicroFocus :: Ptr (TQDockWidget a) -> IO ()
instance QupdateMicroFocus (QDockWidgetSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_updateMicroFocus cobj_x0
instance QwheelEvent (QDockWidget ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_wheelEvent_h" qtc_QDockWidget_wheelEvent_h :: Ptr (TQDockWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QDockWidgetSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_wheelEvent_h cobj_x0 cobj_x1
instance QwindowActivationChange (QDockWidget ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QDockWidget_windowActivationChange" qtc_QDockWidget_windowActivationChange :: Ptr (TQDockWidget a) -> CBool -> IO ()
instance QwindowActivationChange (QDockWidgetSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QDockWidget ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_childEvent" qtc_QDockWidget_childEvent :: Ptr (TQDockWidget a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QDockWidgetSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QDockWidget ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDockWidget_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QDockWidget_connectNotify" qtc_QDockWidget_connectNotify :: Ptr (TQDockWidget a) -> CWString -> IO ()
instance QconnectNotify (QDockWidgetSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDockWidget_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QDockWidget ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_customEvent" qtc_QDockWidget_customEvent :: Ptr (TQDockWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QDockWidgetSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QDockWidget ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDockWidget_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QDockWidget_disconnectNotify" qtc_QDockWidget_disconnectNotify :: Ptr (TQDockWidget a) -> CWString -> IO ()
instance QdisconnectNotify (QDockWidgetSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDockWidget_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QDockWidget ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDockWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QDockWidget_eventFilter_h" qtc_QDockWidget_eventFilter_h :: Ptr (TQDockWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QDockWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QDockWidget_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QDockWidget ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDockWidget_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QDockWidget_receivers" qtc_QDockWidget_receivers :: Ptr (TQDockWidget a) -> CWString -> IO CInt
instance Qreceivers (QDockWidgetSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QDockWidget_receivers cobj_x0 cstr_x1
instance Qsender (QDockWidget ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_sender cobj_x0
foreign import ccall "qtc_QDockWidget_sender" qtc_QDockWidget_sender :: Ptr (TQDockWidget a) -> IO (Ptr (TQObject ()))
instance Qsender (QDockWidgetSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QDockWidget_sender cobj_x0
instance QtimerEvent (QDockWidget ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QDockWidget_timerEvent" qtc_QDockWidget_timerEvent :: Ptr (TQDockWidget a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QDockWidgetSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDockWidget_timerEvent cobj_x0 cobj_x1
| keera-studios/hsQt | Qtc/Gui/QDockWidget.hs | bsd-2-clause | 49,191 | 0 | 14 | 7,890 | 15,905 | 8,068 | 7,837 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Applicative ((<$>))
import Control.Monad (when)
import Data.List (intersperse, nub)
import Data.Maybe
import Development.Shake
import Development.Shake.FilePath
import Development.Shake.Util
import Distribution.Cab.Sandbox
import Distribution.Package
import Distribution.PackageDescription
import Distribution.PackageDescription.Parse
import Distribution.Verbosity
import qualified GHC.Paths as Path
import qualified System.Directory as D
import System.Environment (getArgs)
import System.Environment (withArgs)
build :: FilePath
build = "_build"
srcDirs :: [FilePath]
srcDirs = ["src", "cocoa"]
data AppSetting = AppSetting { app :: String
, ldFlags :: [String]
, packDBs :: [FilePath]
, includes :: [FilePath]
} deriving (Read, Show, Eq, Ord)
main :: IO ()
main = do
cab <- head . filter ((== ".cabal") . takeExtension) <$> (D.getDirectoryContents =<< D.getCurrentDirectory)
packdesc <- readPackageDescription silent cab
msandbox <- getSandbox
let deps0 = buildDepends $ packageDescription packdesc
exes = map (condTreeData . snd) $ condExecutables packdesc
name = fst $ last $ condExecutables packdesc
deps1 = condTreeConstraints $ snd $ last $ condExecutables packdesc
dbs = maybeToList msandbox
incs = map (</> "include") [Path.libdir, Path.libdir ++ "/../.."]
targ = last exes
deps = deps0 ++ deps1 ++ targetBuildDepends (buildInfo targ)
packs = prefixing "-package" $ nub $ map getPackageName deps
frams = prefixing "-framework" $ frameworks $ buildInfo targ
opts = ["-optl-ObjC", "-threaded"]
setting = AppSetting { app = name
, ldFlags = packs ++ frams ++ opts
, packDBs = dbs
, includes = incs
}
in shakeArgs shakeOptions{shakeFiles=build} $ buildWith setting
prefixing :: a -> [a] -> [a]
prefixing _ [] = []
prefixing str xs = str : intersperse str xs
getPackageName :: Dependency -> String
getPackageName (Dependency (PackageName name) _) = name
buildWith :: AppSetting -> Rules ()
buildWith AppSetting {..} = do
let dbs = prefixing "-package-db" packDBs
dest = app <.> "app"
pref = app ++ "Preferences" <.> "app"
skeleton = build </> app <.> "app"
exe = build </> app
xcode = "xcode_proj" </> app </> app <.> "xcodeproj"
want [dest]
phony "clean" $ do
putNormal "cleaning..."
removeFilesAfter "" ["//*_objc.h","//*_objc.m","//*_stub.h"]
xcodeRemove <- doesDirectoryExist $ "xcode_proj" </> app </> "build"
when xcodeRemove $
removeFilesAfter ("xcode_proj" </> app </> "build") ["//*"]
remove <- doesDirectoryExist build
when remove $
removeFilesAfter build ["//*"]
remove' <- doesDirectoryExist dest
when remove $
removeFilesAfter dest ["//*"]
dest *> \out -> do
putNormal "setting up for bundle..."
need [skeleton, exe, build </> pref]
remove <- doesDirectoryExist dest
when remove $ removeFilesAfter dest ["//*"]
() <- cmd "mv" "-f" skeleton out
copyFile' exe (out </> "Contents" </> "MacOS" </> app)
() <- cmd "mkdir" (out </> "Contents" </> "SharedSupport")
() <- cmd "cp" "-r" ("xcode_proj" </> app </> "build/Release" </> pref)
(out </> "Contents" </> "SharedSupport" </> pref)
copyFile' ("data/AppIcon.icns") (out </> "Contents" </> "Resources" </> "AppIcon.icns")
putNormal "Application bundle successfully compiled."
build </> pref *> \out -> do
need [xcode]
putNormal "compiling xcodeproj..."
() <- cmd "xcodebuild -project" xcode "-target" (app ++ "Preferences")
cmd "cp" "-r" ("xcode_proj" </> app </> "build/Release" </> app <.> "app") out
build </> app <.> "app" *> \out -> do
need [xcode]
putNormal "compiling xcodeproj..."
() <- cmd "xcodebuild -project" xcode "-target" app
cmd "cp" "-r" ("xcode_proj" </> app </> "build/Release" </> app <.> "app") out
build </> app *> \out -> do
hss0 <- getDirectoryFiles "cocoa" ["//*.hs"]
hss1 <- getDirectoryFiles "src" ["//*.hs"]
let objs = [build </> hs -<.> "o" | hs <- hss0 ++ hss1, hs `notElem` ["Setup.hs", "Builder.hs"]]
need objs
addObs <- getDirectoryFiles "" ["_build//*_objc.o"]
putNormal $ "linking executable... "
command_ [] "ghc" $ map ("-i"++) srcDirs ++
[ "-o", out, "-odir", build, "-hidir", build, "-stubdir"
, build, "-outputdir", build] ++ objs ++ addObs ++ ldFlags ++ dbs
["_build//*.o", "_build//*.hi"] &*> \ [out, hi] -> do
putNormal $ "building object: " ++ out
let hs0 = dropDirectory1 $ out -<.> "hs"
isSrc <- doesFileExist $ "src" </> hs0
let hs | isSrc = "src" </> hs0
| otherwise = "cocoa" </> hs0
dep = out -<.> "dep"
obcBase = dropExtension hs ++ "_objc"
obcm = obcBase <.> "m"
obch = obcBase <.> "h"
command_ [] "ghc" $ map ("-i"++) srcDirs ++ [ "-M", "-odir", build, "-hidir", build
, "-dep-suffix", "", "-dep-makefile", dep, hs] ++ dbs
needMakefileDependencies dep
command_ [] "ghc" $ map ("-i"++) srcDirs ++ ["-c", hs, "-dynamic"
, "-o", out] ++ dbs ++ [ "-odir", build, "-hidir"
, build, ("-i" ++ build)]
gen'd <- doesFileExist obcm
when gen'd $ do
putNormal $ "compiling gen'd file: " ++ obcm
() <- cmd "mv" obcm (build </> dropDirectory1 obcm)
() <- cmd "mv" obch (build </> dropDirectory1 obch)
() <- cmd "cc" "-fobjc-arc"
(map ("-I"++) includes)
"-c -o" (build </> dropDirectory1 obcBase <.> "o") (build </> dropDirectory1 obcm)
cmd "rm" "-f" $ dropExtension (dropDirectory1 out) ++ "_stub" <.> "h"
putNormal $ "built: " ++ out
| konn/hskk | Builder.hs | bsd-3-clause | 6,247 | 0 | 19 | 1,823 | 1,909 | 979 | 930 | 132 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Data.GrowingArray.Generic
( GrowingArray
, new
, newSingleton
, insert
, unsafeFreeze
) where
import Control.Monad.Primitive
import Data.Primitive.MutVar
import Data.Vector.Generic (Vector, Mutable)
import qualified Data.Vector.Generic as V
import Data.Vector.Generic.Mutable (MVector)
import qualified Data.Vector.Generic.Mutable as MV
data GrowingArray s v a = GrowingArray
{ _items :: !(MutVar s (v s a))
, _count :: !(MutVar s Int)
}
{-# INLINE new #-}
new :: (PrimMonad m, MVector v a)
=> Int -> m (GrowingArray (PrimState m) v a)
new c = do
itemsVar <- MV.new c >>= newMutVar
countVar <- newMutVar 0
return GrowingArray
{ _items = itemsVar
, _count = countVar
}
{-# INLINE newSingleton #-}
newSingleton :: (PrimMonad m, MVector v a)
=> a -> m (GrowingArray (PrimState m) v a)
newSingleton e = do
items <- MV.new 1
itemsVar <- newMutVar items
MV.unsafeWrite items 0 e
countVar <- newMutVar 1
return GrowingArray
{ _items = itemsVar
, _count = countVar
}
{-# INLINE insert #-}
insert :: (PrimMonad m, MVector v a)
=> GrowingArray (PrimState m) v a
-> a
-> m ()
insert GrowingArray{..} e = do
count <- readMutVar _count
items <- do
currentItems <- readMutVar _items
let growBy factor = do
newItems <- MV.unsafeGrow currentItems factor
writeMutVar _items newItems
return newItems
case MV.length currentItems of
0 -> growBy 1
l | l /= count -> return currentItems
| otherwise -> growBy (count * 2)
MV.unsafeWrite items count e
writeMutVar _count (count + 1)
unsafeFreeze :: (PrimMonad m, Vector v a)
=> GrowingArray (PrimState m) (Mutable v) a -> m (v a)
unsafeFreeze GrowingArray{..} = do
count <- readMutVar _count
currentItems <- readMutVar _items
V.unsafeFreeze $ MV.unsafeTake count currentItems
| schernichkin/BSPM | graphomania/src/Data/GrowingArray/Generic.hs | bsd-3-clause | 1,973 | 0 | 17 | 508 | 672 | 339 | 333 | 65 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Day8
( day8
) where
import Control.Applicative
import Data.Array.Repa ((:.) (..), Z (..))
import qualified Data.Array.Repa as R
import qualified Data.Array.Repa.Eval as RE
import Data.Attoparsec.Text hiding (take)
import Data.Either
import qualified Data.Text as T
{- Day 8: Two-Factor Authentication -}
data RotationType = Row | Column deriving (Show)
data Coord = X Int | Y Int deriving (Show)
data Command = Rect (Int,Int) | Rotation RotationType Coord Int deriving (Show)
{- Parsing stuff -}
parseRotationType :: Parser RotationType
parseRotationType =
string "row" *> pure Row
<|> string "column" *> pure Column
parseCoord :: Parser Coord
parseCoord = parseX <|> parseY
where
parseX = X <$> (string "x=" *> decimal)
parseY = Y <$> (string "y=" *> decimal)
parseRectangle :: Parser Command
parseRectangle = do
_ <- string "rect "
a <- decimal
_ <- char 'x'
b <- decimal
return $ Rect (a,b)
parseRotation :: Parser Command
parseRotation = do
_ <- string "rotate "
rotType <- parseRotationType
_ <- space
coord <- parseCoord
_ <- string " by "
i <- decimal
return $ Rotation rotType coord i
parseCommand :: Parser Command
parseCommand = parseRectangle <|> parseRotation
{- Screen -}
type Cell = Int
type Grid = R.Array R.U R.DIM2 Cell
-- | size: The screen is 50 pixels wide and 6 pixels tall
initGrid :: Grid
initGrid = RE.fromList (Z :. 50 :. 6) $ replicate (6 * 50) 0
drawRect :: Grid -> Int -> Int -> Grid
drawRect grid width height =
R.computeS $ R.fromFunction (Z :. 50 :. 6) sp
where
sp sh@(Z :. x :. y)
| x < width && y < height = 1
| otherwise = grid R.! sh
rotCol :: Grid -> Int -> Int -> Grid
rotCol grid col a =
R.computeS $ R.fromFunction (Z :. 50 :. 6) sp
where
sp (Z :. x :. y) =
let y' = if x == col then (y - a) `mod` 6 else y
in grid R.! (Z :. x :. y')
rotRow :: Grid -> Int -> Int -> Grid
rotRow grid row a =
R.computeS $ R.fromFunction (Z :. 50 :. 6) sp
where
sp (Z :. x :. y) =
let x' = if y == row then (x - a) `mod` 50 else x
in grid R.! (Z :. x' :. y)
step :: Grid -> Command -> Grid
step grid (Rect (width,height)) = drawRect grid width height
step grid (Rotation Row (Y row) i) = rotRow grid row i
step grid (Rotation Column (X col) i) = rotCol grid col i
step grid _ = grid
countLightOn :: Grid -> Int
countLightOn = R.sumAllS
day8 :: IO ()
day8 = do
input <- T.lines . T.pack <$> readFile "resources/day8.txt"
let results = rights $ map (parseOnly parseCommand) input
let finalGrid = foldl step initGrid results
print $ countLightOn finalGrid
putStrLn ""
drawGrid finalGrid
{- Part Two -}
drawGrid :: Grid -> IO ()
drawGrid grid = do
let matrix = [ [grid R.! (Z :. x :. y) | x <- [0..49]] | y <- [0..5] ]
mapM_ (putStrLn . map toChar) matrix
where
toChar 1 = '#'
toChar _ = ' '
| Rydgel/advent-of-code-2016 | src/Day8.hs | bsd-3-clause | 3,009 | 0 | 15 | 759 | 1,187 | 619 | 568 | 83 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Syncthing.Types.Model
( Model(..)
, ModelState(..)
) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (MonadPlus (mzero))
import Data.Aeson (FromJSON, Value (..), parseJSON, (.:))
import Data.Text (Text)
import Data.Time.Clock (UTCTime)
import Network.Syncthing.Internal.Utils (toUTC)
-- | The current state of activity of a folder.
data ModelState
= Idle
| Scanning
| Cleaning
| Syncing
deriving (Eq, Show)
-- | Information about the current status of a folder.
data Model = Model {
getGlobalBytes :: Integer
, getGlobalDeleted :: Integer
, getGlobalFiles :: Integer
, getInSyncBytes :: Integer
, getInSyncFiles :: Integer
, getLocalBytes :: Integer
, getLocalDeleted :: Integer
, getLocalFiles :: Integer
, getNeedBytes :: Integer
, getNeedFiles :: Integer
, getState :: Maybe ModelState
, getStateChanged :: Maybe UTCTime
, getInvalid :: Maybe Text
, getModelVersion :: Int
} deriving (Eq, Show)
instance FromJSON Model where
parseJSON (Object v) =
Model <$> (v .: "globalBytes")
<*> (v .: "globalDeleted")
<*> (v .: "globalFiles")
<*> (v .: "inSyncBytes")
<*> (v .: "inSyncFiles")
<*> (v .: "localBytes")
<*> (v .: "localDeleted")
<*> (v .: "localFiles")
<*> (v .: "needBytes")
<*> (v .: "needFiles")
<*> (decodeModelState <$> (v .: "state"))
<*> (toUTC <$> (v .: "stateChanged"))
<*> (decodeInvalid <$> (v .: "invalid"))
<*> (v .: "version")
parseJSON _ = mzero
decodeModelState :: Text -> Maybe ModelState
decodeModelState = flip lookup
[ ("idle", Idle)
, ("scanning", Scanning)
, ("cleaning", Cleaning)
, ("syncing", Syncing)
]
decodeInvalid :: Text -> Maybe Text
decodeInvalid "" = Nothing
decodeInvalid s = Just s
| jetho/syncthing-hs | Network/Syncthing/Types/Model.hs | bsd-3-clause | 2,219 | 0 | 21 | 775 | 550 | 326 | 224 | 58 | 1 |
{-|
Copyright : (c) Dave Laing, 2017
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable
-}
module Fragment.TyVar.Helpers (
tyVar
) where
import Control.Lens (review)
import Ast.Type
tyVar :: a -> Type ki ty a
tyVar = review _TyVar
| dalaing/type-systems | src/Fragment/TyVar/Helpers.hs | bsd-3-clause | 302 | 0 | 6 | 61 | 52 | 30 | 22 | 6 | 1 |
module Util where
import Types
rangeMatch :: Range -> Char -> Maybe Char
rangeMatch Nothing c = Just c
rangeMatch (Just as) c
| c `elem` as = Just c
| otherwise = Nothing
| matthiasgoergens/redgrep | src/Util.hs | bsd-3-clause | 180 | 0 | 8 | 43 | 76 | 38 | 38 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- | Tests.
module Main where
import Clockin
import Data.Maybe
import Data.Monoid
import Data.Time.Format
import Data.Time.LocalTime
import System.Exit
import System.Locale
-- | Test that the 'inToday' function works properly.
main :: IO ()
main =
either (\(ts,expected,actual,cur) ->
do mapM_ (putStrLn . asEntry) ts
putStrLn ("Current time: " <> cur)
putStrLn ("Expected: " <> show expected)
putStrLn ("Actual: " <> show actual)
exitFailure)
(const (putStrLn "OK"))
(sequence [matches [i "10:00",o "11:00"] "04:00" (-1 * (1*60*60))
,matches [i "00:00",o "02:00",i "03:00",o "04:00"] "05:00" (-1 * (3*60*60))
,matches [i "00:00",o "02:00",i "03:00"] "05:00" (-1 * (4 * 60 * 60))
,matches [i' "10:00",o' "11:00"] "01:00" 0])
where asEntry (In i) = "i " <> formatTime defaultTimeLocale "%F %R" (inTime i)
asEntry (Out o) = "o " <> formatTime defaultTimeLocale "%F %R" (outTime o)
matches times n e = if r == e then Right () else Left (times,e,r,c)
where c = formatTime defaultTimeLocale "%F %R" (now' n)
r = inToday (now' n) (reverse times)
now' :: String -> LocalTime
now' n = (fromJust . parseTime defaultTimeLocale "%F%R" . (today<>)) n
i n =
In (ClockIn "Some project"
Nothing
((fromJust . parseTime defaultTimeLocale "%F%R" . (today<>)) n))
i' n =
In (ClockIn "Some project"
Nothing
((fromJust . parseTime defaultTimeLocale "%F%R" . (yesterday<>)) n))
o n =
Out (ClockOut "Some project"
Nothing
Nothing
((fromJust . parseTime defaultTimeLocale "%F%R" . (today<>)) n))
o' n =
Out (ClockOut "Some project"
Nothing
Nothing
((fromJust . parseTime defaultTimeLocale "%F%R" . (yesterday<>)) n))
today = "2014-01-20"
yesterday = "2014-01-19"
| chrisdone/clockin | src/Test.hs | bsd-3-clause | 2,206 | 0 | 15 | 786 | 723 | 376 | 347 | 49 | 3 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
module Lazyfoo.Lesson17 (main) where
import Prelude hiding (foldl1)
import Control.Applicative
import Control.Monad
import Data.Foldable
import Data.Monoid
import Data.Maybe
import Foreign.C.Types
import Linear
import Linear.Affine
import SDL (($=))
import qualified SDL
import Paths_sdl2 (getDataFileName)
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
data Texture = Texture SDL.Texture (V2 CInt)
loadTexture :: SDL.Renderer -> FilePath -> IO Texture
loadTexture r filePath = do
surface <- getDataFileName filePath >>= SDL.loadBMP
size <- SDL.surfaceDimensions surface
format <- SDL.surfaceFormat surface
key <- SDL.mapRGB format (V3 0 maxBound maxBound)
SDL.colorKey surface $= Just key
t <- SDL.createTextureFromSurface r surface
SDL.freeSurface surface
return (Texture t size)
renderTexture :: SDL.Renderer -> Texture -> Point V2 CInt -> Maybe (SDL.Rectangle CInt) -> Maybe CDouble -> Maybe (Point V2 CInt) -> Maybe (V2 Bool) -> IO ()
renderTexture r (Texture t size) xy clip theta center flips =
let dstSize =
maybe size (\(SDL.Rectangle _ size') -> size') clip
in SDL.renderCopyEx r
t
clip
(Just (SDL.Rectangle xy dstSize))
(fromMaybe 0 theta)
center
(fromMaybe (pure False) flips)
data ButtonSprite = MouseOut | MouseOver | MouseDown | MouseUp
data Button = Button (Point V2 CInt) ButtonSprite
buttonSize :: V2 CInt
buttonWidth, buttonHeight :: CInt
buttonSize@(V2 buttonWidth buttonHeight) = V2 300 200
handleEvent :: Point V2 CInt -> SDL.EventPayload -> Button -> Button
handleEvent mousePos e (Button buttonPos _) =
let inside = foldl1 (&&) ((>=) <$> mousePos <*> buttonPos) &&
foldl1 (&&) ((<=) <$> mousePos <*> buttonPos .+^ buttonSize)
sprite
| inside = case e of
SDL.MouseButtonEvent{..}
| mouseButtonEventMotion == SDL.MouseButtonDown -> MouseDown
| mouseButtonEventMotion == SDL.MouseButtonUp -> MouseUp
| otherwise -> MouseOver
_ -> MouseOver
| otherwise = MouseOut
in Button buttonPos sprite
renderButton :: SDL.Renderer -> Texture -> Button -> IO ()
renderButton r spriteSheet (Button xy sprite) =
renderTexture r spriteSheet xy (Just spriteClipRect) Nothing Nothing Nothing
where
spriteClipRect =
let i = case sprite of
MouseOut -> 0
MouseOver -> 1
MouseDown -> 2
MouseUp -> 3
in SDL.Rectangle (P (V2 0 (i * 200))) (V2 300 200)
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo]
SDL.HintRenderScaleQuality $= SDL.ScaleLinear
do renderQuality <- SDL.get SDL.HintRenderScaleQuality
when (renderQuality /= SDL.ScaleLinear) $
putStrLn "Warning: Linear texture filtering not enabled!"
window <-
SDL.createWindow
"SDL Tutorial"
SDL.defaultWindow {SDL.windowInitialSize = V2 screenWidth screenHeight}
SDL.showWindow window
renderer <-
SDL.createRenderer
window
(-1)
(SDL.RendererConfig
{ SDL.rendererAccelerated = True
, SDL.rendererSoftware = False
, SDL.rendererTargetTexture = False
, SDL.rendererPresentVSync = True
})
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
buttonSpriteSheet <- loadTexture renderer "examples/lazyfoo/button.bmp"
let loop buttons = do
let collectEvents = do
e <- SDL.pollEvent
case e of
Nothing -> return []
Just e' -> (e' :) <$> collectEvents
events <- collectEvents
mousePos <- SDL.getMouseLocation
let (Any quit, Endo updateButton) =
foldMap (\case
SDL.QuitEvent -> (Any True, mempty)
e -> (mempty, Endo (handleEvent mousePos e))) $
map SDL.eventPayload events
SDL.renderDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
SDL.renderClear renderer
let buttons' = map (\b -> updateButton b) buttons
for_ buttons' (renderButton renderer buttonSpriteSheet)
SDL.renderPresent renderer
unless quit (loop buttons')
loop (let newButton xy = Button xy MouseOut
in [ newButton (P (V2 0 0))
, newButton (P (V2 (screenWidth - buttonWidth) 0))
, newButton (P (V2 0 (screenHeight - buttonHeight)))
, newButton (P (V2 screenWidth screenHeight - buttonSize))
])
SDL.destroyRenderer renderer
SDL.destroyWindow window
SDL.quit
| svenkeidel/sdl2 | examples/lazyfoo/Lesson17.hs | bsd-3-clause | 4,846 | 3 | 17 | 1,357 | 1,456 | 732 | 724 | 119 | 4 |
module Lava.Test where
import Lava.Signal
import Lava.Sequential
import Lava.Generic
import Lava.LavaRandom
( newRnd
)
----------------------------------------------------------------
-- test
test :: (Constructive a, Show b, Generic b) => (a -> b) -> IO [b]
test circ =
do rnd <- newRnd
let res = simulateSeq (\_ -> circ (random rnd)) (replicate 100 ())
print res
return res
----------------------------------------------------------------
-- the end.
| dfordivam/lava | Lava/Test.hs | bsd-3-clause | 479 | 0 | 15 | 86 | 146 | 77 | 69 | 12 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.Version20
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.Version20 (
-- * Types
GLbitfield,
GLboolean,
GLbyte,
GLchar,
GLclampd,
GLclampf,
GLdouble,
GLenum,
GLfloat,
GLint,
GLintptr,
GLshort,
GLsizei,
GLsizeiptr,
GLubyte,
GLuint,
GLushort,
GLvoid,
-- * Enums
gl_2D,
gl_2_BYTES,
gl_3D,
gl_3D_COLOR,
gl_3D_COLOR_TEXTURE,
gl_3_BYTES,
gl_4D_COLOR_TEXTURE,
gl_4_BYTES,
gl_ACCUM,
gl_ACCUM_ALPHA_BITS,
gl_ACCUM_BLUE_BITS,
gl_ACCUM_BUFFER_BIT,
gl_ACCUM_CLEAR_VALUE,
gl_ACCUM_GREEN_BITS,
gl_ACCUM_RED_BITS,
gl_ACTIVE_ATTRIBUTES,
gl_ACTIVE_ATTRIBUTE_MAX_LENGTH,
gl_ACTIVE_TEXTURE,
gl_ACTIVE_UNIFORMS,
gl_ACTIVE_UNIFORM_MAX_LENGTH,
gl_ADD,
gl_ADD_SIGNED,
gl_ALIASED_LINE_WIDTH_RANGE,
gl_ALIASED_POINT_SIZE_RANGE,
gl_ALL_ATTRIB_BITS,
gl_ALPHA,
gl_ALPHA12,
gl_ALPHA16,
gl_ALPHA4,
gl_ALPHA8,
gl_ALPHA_BIAS,
gl_ALPHA_BITS,
gl_ALPHA_SCALE,
gl_ALPHA_TEST,
gl_ALPHA_TEST_FUNC,
gl_ALPHA_TEST_REF,
gl_ALWAYS,
gl_AMBIENT,
gl_AMBIENT_AND_DIFFUSE,
gl_AND,
gl_AND_INVERTED,
gl_AND_REVERSE,
gl_ARRAY_BUFFER,
gl_ARRAY_BUFFER_BINDING,
gl_ATTACHED_SHADERS,
gl_ATTRIB_STACK_DEPTH,
gl_AUTO_NORMAL,
gl_AUX0,
gl_AUX1,
gl_AUX2,
gl_AUX3,
gl_AUX_BUFFERS,
gl_BACK,
gl_BACK_LEFT,
gl_BACK_RIGHT,
gl_BGR,
gl_BGRA,
gl_BITMAP,
gl_BITMAP_TOKEN,
gl_BLEND,
gl_BLEND_DST,
gl_BLEND_DST_ALPHA,
gl_BLEND_DST_RGB,
gl_BLEND_EQUATION_ALPHA,
gl_BLEND_EQUATION_RGB,
gl_BLEND_SRC,
gl_BLEND_SRC_ALPHA,
gl_BLEND_SRC_RGB,
gl_BLUE,
gl_BLUE_BIAS,
gl_BLUE_BITS,
gl_BLUE_SCALE,
gl_BOOL,
gl_BOOL_VEC2,
gl_BOOL_VEC3,
gl_BOOL_VEC4,
gl_BUFFER_ACCESS,
gl_BUFFER_MAPPED,
gl_BUFFER_MAP_POINTER,
gl_BUFFER_SIZE,
gl_BUFFER_USAGE,
gl_BYTE,
gl_C3F_V3F,
gl_C4F_N3F_V3F,
gl_C4UB_V2F,
gl_C4UB_V3F,
gl_CCW,
gl_CLAMP,
gl_CLAMP_TO_BORDER,
gl_CLAMP_TO_EDGE,
gl_CLEAR,
gl_CLIENT_ACTIVE_TEXTURE,
gl_CLIENT_ALL_ATTRIB_BITS,
gl_CLIENT_ATTRIB_STACK_DEPTH,
gl_CLIENT_PIXEL_STORE_BIT,
gl_CLIENT_VERTEX_ARRAY_BIT,
gl_CLIP_PLANE0,
gl_CLIP_PLANE1,
gl_CLIP_PLANE2,
gl_CLIP_PLANE3,
gl_CLIP_PLANE4,
gl_CLIP_PLANE5,
gl_COEFF,
gl_COLOR,
gl_COLOR_ARRAY,
gl_COLOR_ARRAY_BUFFER_BINDING,
gl_COLOR_ARRAY_POINTER,
gl_COLOR_ARRAY_SIZE,
gl_COLOR_ARRAY_STRIDE,
gl_COLOR_ARRAY_TYPE,
gl_COLOR_BUFFER_BIT,
gl_COLOR_CLEAR_VALUE,
gl_COLOR_INDEX,
gl_COLOR_INDEXES,
gl_COLOR_LOGIC_OP,
gl_COLOR_MATERIAL,
gl_COLOR_MATERIAL_FACE,
gl_COLOR_MATERIAL_PARAMETER,
gl_COLOR_SUM,
gl_COLOR_WRITEMASK,
gl_COMBINE,
gl_COMBINE_ALPHA,
gl_COMBINE_RGB,
gl_COMPARE_R_TO_TEXTURE,
gl_COMPILE,
gl_COMPILE_AND_EXECUTE,
gl_COMPILE_STATUS,
gl_COMPRESSED_ALPHA,
gl_COMPRESSED_INTENSITY,
gl_COMPRESSED_LUMINANCE,
gl_COMPRESSED_LUMINANCE_ALPHA,
gl_COMPRESSED_RGB,
gl_COMPRESSED_RGBA,
gl_COMPRESSED_TEXTURE_FORMATS,
gl_CONSTANT,
gl_CONSTANT_ALPHA,
gl_CONSTANT_ATTENUATION,
gl_CONSTANT_COLOR,
gl_COORD_REPLACE,
gl_COPY,
gl_COPY_INVERTED,
gl_COPY_PIXEL_TOKEN,
gl_CULL_FACE,
gl_CULL_FACE_MODE,
gl_CURRENT_BIT,
gl_CURRENT_COLOR,
gl_CURRENT_FOG_COORD,
gl_CURRENT_FOG_COORDINATE,
gl_CURRENT_INDEX,
gl_CURRENT_NORMAL,
gl_CURRENT_PROGRAM,
gl_CURRENT_QUERY,
gl_CURRENT_RASTER_COLOR,
gl_CURRENT_RASTER_DISTANCE,
gl_CURRENT_RASTER_INDEX,
gl_CURRENT_RASTER_POSITION,
gl_CURRENT_RASTER_POSITION_VALID,
gl_CURRENT_RASTER_TEXTURE_COORDS,
gl_CURRENT_SECONDARY_COLOR,
gl_CURRENT_TEXTURE_COORDS,
gl_CURRENT_VERTEX_ATTRIB,
gl_CW,
gl_DECAL,
gl_DECR,
gl_DECR_WRAP,
gl_DELETE_STATUS,
gl_DEPTH,
gl_DEPTH_BIAS,
gl_DEPTH_BITS,
gl_DEPTH_BUFFER_BIT,
gl_DEPTH_CLEAR_VALUE,
gl_DEPTH_COMPONENT,
gl_DEPTH_COMPONENT16,
gl_DEPTH_COMPONENT24,
gl_DEPTH_COMPONENT32,
gl_DEPTH_FUNC,
gl_DEPTH_RANGE,
gl_DEPTH_SCALE,
gl_DEPTH_TEST,
gl_DEPTH_TEXTURE_MODE,
gl_DEPTH_WRITEMASK,
gl_DIFFUSE,
gl_DITHER,
gl_DOMAIN,
gl_DONT_CARE,
gl_DOT3_RGB,
gl_DOT3_RGBA,
gl_DOUBLE,
gl_DOUBLEBUFFER,
gl_DRAW_BUFFER,
gl_DRAW_BUFFER0,
gl_DRAW_BUFFER1,
gl_DRAW_BUFFER10,
gl_DRAW_BUFFER11,
gl_DRAW_BUFFER12,
gl_DRAW_BUFFER13,
gl_DRAW_BUFFER14,
gl_DRAW_BUFFER15,
gl_DRAW_BUFFER2,
gl_DRAW_BUFFER3,
gl_DRAW_BUFFER4,
gl_DRAW_BUFFER5,
gl_DRAW_BUFFER6,
gl_DRAW_BUFFER7,
gl_DRAW_BUFFER8,
gl_DRAW_BUFFER9,
gl_DRAW_PIXEL_TOKEN,
gl_DST_ALPHA,
gl_DST_COLOR,
gl_DYNAMIC_COPY,
gl_DYNAMIC_DRAW,
gl_DYNAMIC_READ,
gl_EDGE_FLAG,
gl_EDGE_FLAG_ARRAY,
gl_EDGE_FLAG_ARRAY_BUFFER_BINDING,
gl_EDGE_FLAG_ARRAY_POINTER,
gl_EDGE_FLAG_ARRAY_STRIDE,
gl_ELEMENT_ARRAY_BUFFER,
gl_ELEMENT_ARRAY_BUFFER_BINDING,
gl_EMISSION,
gl_ENABLE_BIT,
gl_EQUAL,
gl_EQUIV,
gl_EVAL_BIT,
gl_EXP,
gl_EXP2,
gl_EXTENSIONS,
gl_EYE_LINEAR,
gl_EYE_PLANE,
gl_FALSE,
gl_FASTEST,
gl_FEEDBACK,
gl_FEEDBACK_BUFFER_POINTER,
gl_FEEDBACK_BUFFER_SIZE,
gl_FEEDBACK_BUFFER_TYPE,
gl_FILL,
gl_FLAT,
gl_FLOAT,
gl_FLOAT_MAT2,
gl_FLOAT_MAT3,
gl_FLOAT_MAT4,
gl_FLOAT_VEC2,
gl_FLOAT_VEC3,
gl_FLOAT_VEC4,
gl_FOG,
gl_FOG_BIT,
gl_FOG_COLOR,
gl_FOG_COORD,
gl_FOG_COORDINATE,
gl_FOG_COORDINATE_ARRAY,
gl_FOG_COORDINATE_ARRAY_BUFFER_BINDING,
gl_FOG_COORDINATE_ARRAY_POINTER,
gl_FOG_COORDINATE_ARRAY_STRIDE,
gl_FOG_COORDINATE_ARRAY_TYPE,
gl_FOG_COORDINATE_SOURCE,
gl_FOG_COORD_ARRAY,
gl_FOG_COORD_ARRAY_BUFFER_BINDING,
gl_FOG_COORD_ARRAY_POINTER,
gl_FOG_COORD_ARRAY_STRIDE,
gl_FOG_COORD_ARRAY_TYPE,
gl_FOG_COORD_SRC,
gl_FOG_DENSITY,
gl_FOG_END,
gl_FOG_HINT,
gl_FOG_INDEX,
gl_FOG_MODE,
gl_FOG_START,
gl_FRAGMENT_DEPTH,
gl_FRAGMENT_SHADER,
gl_FRAGMENT_SHADER_DERIVATIVE_HINT,
gl_FRONT,
gl_FRONT_AND_BACK,
gl_FRONT_FACE,
gl_FRONT_LEFT,
gl_FRONT_RIGHT,
gl_FUNC_ADD,
gl_FUNC_REVERSE_SUBTRACT,
gl_FUNC_SUBTRACT,
gl_GENERATE_MIPMAP,
gl_GENERATE_MIPMAP_HINT,
gl_GEQUAL,
gl_GREATER,
gl_GREEN,
gl_GREEN_BIAS,
gl_GREEN_BITS,
gl_GREEN_SCALE,
gl_HINT_BIT,
gl_INCR,
gl_INCR_WRAP,
gl_INDEX_ARRAY,
gl_INDEX_ARRAY_BUFFER_BINDING,
gl_INDEX_ARRAY_POINTER,
gl_INDEX_ARRAY_STRIDE,
gl_INDEX_ARRAY_TYPE,
gl_INDEX_BITS,
gl_INDEX_CLEAR_VALUE,
gl_INDEX_LOGIC_OP,
gl_INDEX_MODE,
gl_INDEX_OFFSET,
gl_INDEX_SHIFT,
gl_INDEX_WRITEMASK,
gl_INFO_LOG_LENGTH,
gl_INT,
gl_INTENSITY,
gl_INTENSITY12,
gl_INTENSITY16,
gl_INTENSITY4,
gl_INTENSITY8,
gl_INTERPOLATE,
gl_INT_VEC2,
gl_INT_VEC3,
gl_INT_VEC4,
gl_INVALID_ENUM,
gl_INVALID_OPERATION,
gl_INVALID_VALUE,
gl_INVERT,
gl_KEEP,
gl_LEFT,
gl_LEQUAL,
gl_LESS,
gl_LIGHT0,
gl_LIGHT1,
gl_LIGHT2,
gl_LIGHT3,
gl_LIGHT4,
gl_LIGHT5,
gl_LIGHT6,
gl_LIGHT7,
gl_LIGHTING,
gl_LIGHTING_BIT,
gl_LIGHT_MODEL_AMBIENT,
gl_LIGHT_MODEL_COLOR_CONTROL,
gl_LIGHT_MODEL_LOCAL_VIEWER,
gl_LIGHT_MODEL_TWO_SIDE,
gl_LINE,
gl_LINEAR,
gl_LINEAR_ATTENUATION,
gl_LINEAR_MIPMAP_LINEAR,
gl_LINEAR_MIPMAP_NEAREST,
gl_LINES,
gl_LINE_BIT,
gl_LINE_LOOP,
gl_LINE_RESET_TOKEN,
gl_LINE_SMOOTH,
gl_LINE_SMOOTH_HINT,
gl_LINE_STIPPLE,
gl_LINE_STIPPLE_PATTERN,
gl_LINE_STIPPLE_REPEAT,
gl_LINE_STRIP,
gl_LINE_TOKEN,
gl_LINE_WIDTH,
gl_LINE_WIDTH_GRANULARITY,
gl_LINE_WIDTH_RANGE,
gl_LINK_STATUS,
gl_LIST_BASE,
gl_LIST_BIT,
gl_LIST_INDEX,
gl_LIST_MODE,
gl_LOAD,
gl_LOGIC_OP,
gl_LOGIC_OP_MODE,
gl_LOWER_LEFT,
gl_LUMINANCE,
gl_LUMINANCE12,
gl_LUMINANCE12_ALPHA12,
gl_LUMINANCE12_ALPHA4,
gl_LUMINANCE16,
gl_LUMINANCE16_ALPHA16,
gl_LUMINANCE4,
gl_LUMINANCE4_ALPHA4,
gl_LUMINANCE6_ALPHA2,
gl_LUMINANCE8,
gl_LUMINANCE8_ALPHA8,
gl_LUMINANCE_ALPHA,
gl_MAP1_COLOR_4,
gl_MAP1_GRID_DOMAIN,
gl_MAP1_GRID_SEGMENTS,
gl_MAP1_INDEX,
gl_MAP1_NORMAL,
gl_MAP1_TEXTURE_COORD_1,
gl_MAP1_TEXTURE_COORD_2,
gl_MAP1_TEXTURE_COORD_3,
gl_MAP1_TEXTURE_COORD_4,
gl_MAP1_VERTEX_3,
gl_MAP1_VERTEX_4,
gl_MAP2_COLOR_4,
gl_MAP2_GRID_DOMAIN,
gl_MAP2_GRID_SEGMENTS,
gl_MAP2_INDEX,
gl_MAP2_NORMAL,
gl_MAP2_TEXTURE_COORD_1,
gl_MAP2_TEXTURE_COORD_2,
gl_MAP2_TEXTURE_COORD_3,
gl_MAP2_TEXTURE_COORD_4,
gl_MAP2_VERTEX_3,
gl_MAP2_VERTEX_4,
gl_MAP_COLOR,
gl_MAP_STENCIL,
gl_MATRIX_MODE,
gl_MAX,
gl_MAX_3D_TEXTURE_SIZE,
gl_MAX_ATTRIB_STACK_DEPTH,
gl_MAX_CLIENT_ATTRIB_STACK_DEPTH,
gl_MAX_CLIP_PLANES,
gl_MAX_COMBINED_TEXTURE_IMAGE_UNITS,
gl_MAX_CUBE_MAP_TEXTURE_SIZE,
gl_MAX_DRAW_BUFFERS,
gl_MAX_ELEMENTS_INDICES,
gl_MAX_ELEMENTS_VERTICES,
gl_MAX_EVAL_ORDER,
gl_MAX_FRAGMENT_UNIFORM_COMPONENTS,
gl_MAX_LIGHTS,
gl_MAX_LIST_NESTING,
gl_MAX_MODELVIEW_STACK_DEPTH,
gl_MAX_NAME_STACK_DEPTH,
gl_MAX_PIXEL_MAP_TABLE,
gl_MAX_PROJECTION_STACK_DEPTH,
gl_MAX_TEXTURE_COORDS,
gl_MAX_TEXTURE_IMAGE_UNITS,
gl_MAX_TEXTURE_LOD_BIAS,
gl_MAX_TEXTURE_SIZE,
gl_MAX_TEXTURE_STACK_DEPTH,
gl_MAX_TEXTURE_UNITS,
gl_MAX_VARYING_FLOATS,
gl_MAX_VERTEX_ATTRIBS,
gl_MAX_VERTEX_TEXTURE_IMAGE_UNITS,
gl_MAX_VERTEX_UNIFORM_COMPONENTS,
gl_MAX_VIEWPORT_DIMS,
gl_MIN,
gl_MIRRORED_REPEAT,
gl_MODELVIEW,
gl_MODELVIEW_MATRIX,
gl_MODELVIEW_STACK_DEPTH,
gl_MODULATE,
gl_MULT,
gl_MULTISAMPLE,
gl_MULTISAMPLE_BIT,
gl_N3F_V3F,
gl_NAME_STACK_DEPTH,
gl_NAND,
gl_NEAREST,
gl_NEAREST_MIPMAP_LINEAR,
gl_NEAREST_MIPMAP_NEAREST,
gl_NEVER,
gl_NICEST,
gl_NONE,
gl_NOOP,
gl_NOR,
gl_NORMALIZE,
gl_NORMAL_ARRAY,
gl_NORMAL_ARRAY_BUFFER_BINDING,
gl_NORMAL_ARRAY_POINTER,
gl_NORMAL_ARRAY_STRIDE,
gl_NORMAL_ARRAY_TYPE,
gl_NORMAL_MAP,
gl_NOTEQUAL,
gl_NO_ERROR,
gl_NUM_COMPRESSED_TEXTURE_FORMATS,
gl_OBJECT_LINEAR,
gl_OBJECT_PLANE,
gl_ONE,
gl_ONE_MINUS_CONSTANT_ALPHA,
gl_ONE_MINUS_CONSTANT_COLOR,
gl_ONE_MINUS_DST_ALPHA,
gl_ONE_MINUS_DST_COLOR,
gl_ONE_MINUS_SRC_ALPHA,
gl_ONE_MINUS_SRC_COLOR,
gl_OPERAND0_ALPHA,
gl_OPERAND0_RGB,
gl_OPERAND1_ALPHA,
gl_OPERAND1_RGB,
gl_OPERAND2_ALPHA,
gl_OPERAND2_RGB,
gl_OR,
gl_ORDER,
gl_OR_INVERTED,
gl_OR_REVERSE,
gl_OUT_OF_MEMORY,
gl_PACK_ALIGNMENT,
gl_PACK_IMAGE_HEIGHT,
gl_PACK_LSB_FIRST,
gl_PACK_ROW_LENGTH,
gl_PACK_SKIP_IMAGES,
gl_PACK_SKIP_PIXELS,
gl_PACK_SKIP_ROWS,
gl_PACK_SWAP_BYTES,
gl_PASS_THROUGH_TOKEN,
gl_PERSPECTIVE_CORRECTION_HINT,
gl_PIXEL_MAP_A_TO_A,
gl_PIXEL_MAP_A_TO_A_SIZE,
gl_PIXEL_MAP_B_TO_B,
gl_PIXEL_MAP_B_TO_B_SIZE,
gl_PIXEL_MAP_G_TO_G,
gl_PIXEL_MAP_G_TO_G_SIZE,
gl_PIXEL_MAP_I_TO_A,
gl_PIXEL_MAP_I_TO_A_SIZE,
gl_PIXEL_MAP_I_TO_B,
gl_PIXEL_MAP_I_TO_B_SIZE,
gl_PIXEL_MAP_I_TO_G,
gl_PIXEL_MAP_I_TO_G_SIZE,
gl_PIXEL_MAP_I_TO_I,
gl_PIXEL_MAP_I_TO_I_SIZE,
gl_PIXEL_MAP_I_TO_R,
gl_PIXEL_MAP_I_TO_R_SIZE,
gl_PIXEL_MAP_R_TO_R,
gl_PIXEL_MAP_R_TO_R_SIZE,
gl_PIXEL_MAP_S_TO_S,
gl_PIXEL_MAP_S_TO_S_SIZE,
gl_PIXEL_MODE_BIT,
gl_POINT,
gl_POINTS,
gl_POINT_BIT,
gl_POINT_DISTANCE_ATTENUATION,
gl_POINT_FADE_THRESHOLD_SIZE,
gl_POINT_SIZE,
gl_POINT_SIZE_GRANULARITY,
gl_POINT_SIZE_MAX,
gl_POINT_SIZE_MIN,
gl_POINT_SIZE_RANGE,
gl_POINT_SMOOTH,
gl_POINT_SMOOTH_HINT,
gl_POINT_SPRITE,
gl_POINT_SPRITE_COORD_ORIGIN,
gl_POINT_TOKEN,
gl_POLYGON,
gl_POLYGON_BIT,
gl_POLYGON_MODE,
gl_POLYGON_OFFSET_FACTOR,
gl_POLYGON_OFFSET_FILL,
gl_POLYGON_OFFSET_LINE,
gl_POLYGON_OFFSET_POINT,
gl_POLYGON_OFFSET_UNITS,
gl_POLYGON_SMOOTH,
gl_POLYGON_SMOOTH_HINT,
gl_POLYGON_STIPPLE,
gl_POLYGON_STIPPLE_BIT,
gl_POLYGON_TOKEN,
gl_POSITION,
gl_PREVIOUS,
gl_PRIMARY_COLOR,
gl_PROJECTION,
gl_PROJECTION_MATRIX,
gl_PROJECTION_STACK_DEPTH,
gl_PROXY_TEXTURE_1D,
gl_PROXY_TEXTURE_2D,
gl_PROXY_TEXTURE_3D,
gl_PROXY_TEXTURE_CUBE_MAP,
gl_Q,
gl_QUADRATIC_ATTENUATION,
gl_QUADS,
gl_QUAD_STRIP,
gl_QUERY_COUNTER_BITS,
gl_QUERY_RESULT,
gl_QUERY_RESULT_AVAILABLE,
gl_R,
gl_R3_G3_B2,
gl_READ_BUFFER,
gl_READ_ONLY,
gl_READ_WRITE,
gl_RED,
gl_RED_BIAS,
gl_RED_BITS,
gl_RED_SCALE,
gl_REFLECTION_MAP,
gl_RENDER,
gl_RENDERER,
gl_RENDER_MODE,
gl_REPEAT,
gl_REPLACE,
gl_RESCALE_NORMAL,
gl_RETURN,
gl_RGB,
gl_RGB10,
gl_RGB10_A2,
gl_RGB12,
gl_RGB16,
gl_RGB4,
gl_RGB5,
gl_RGB5_A1,
gl_RGB8,
gl_RGBA,
gl_RGBA12,
gl_RGBA16,
gl_RGBA2,
gl_RGBA4,
gl_RGBA8,
gl_RGBA_MODE,
gl_RGB_SCALE,
gl_RIGHT,
gl_S,
gl_SAMPLER_1D,
gl_SAMPLER_1D_SHADOW,
gl_SAMPLER_2D,
gl_SAMPLER_2D_SHADOW,
gl_SAMPLER_3D,
gl_SAMPLER_CUBE,
gl_SAMPLES,
gl_SAMPLES_PASSED,
gl_SAMPLE_ALPHA_TO_COVERAGE,
gl_SAMPLE_ALPHA_TO_ONE,
gl_SAMPLE_BUFFERS,
gl_SAMPLE_COVERAGE,
gl_SAMPLE_COVERAGE_INVERT,
gl_SAMPLE_COVERAGE_VALUE,
gl_SCISSOR_BIT,
gl_SCISSOR_BOX,
gl_SCISSOR_TEST,
gl_SECONDARY_COLOR_ARRAY,
gl_SECONDARY_COLOR_ARRAY_BUFFER_BINDING,
gl_SECONDARY_COLOR_ARRAY_POINTER,
gl_SECONDARY_COLOR_ARRAY_SIZE,
gl_SECONDARY_COLOR_ARRAY_STRIDE,
gl_SECONDARY_COLOR_ARRAY_TYPE,
gl_SELECT,
gl_SELECTION_BUFFER_POINTER,
gl_SELECTION_BUFFER_SIZE,
gl_SEPARATE_SPECULAR_COLOR,
gl_SET,
gl_SHADER_SOURCE_LENGTH,
gl_SHADER_TYPE,
gl_SHADE_MODEL,
gl_SHADING_LANGUAGE_VERSION,
gl_SHININESS,
gl_SHORT,
gl_SINGLE_COLOR,
gl_SMOOTH,
gl_SMOOTH_LINE_WIDTH_GRANULARITY,
gl_SMOOTH_LINE_WIDTH_RANGE,
gl_SMOOTH_POINT_SIZE_GRANULARITY,
gl_SMOOTH_POINT_SIZE_RANGE,
gl_SOURCE0_ALPHA,
gl_SOURCE0_RGB,
gl_SOURCE1_ALPHA,
gl_SOURCE1_RGB,
gl_SOURCE2_ALPHA,
gl_SOURCE2_RGB,
gl_SPECULAR,
gl_SPHERE_MAP,
gl_SPOT_CUTOFF,
gl_SPOT_DIRECTION,
gl_SPOT_EXPONENT,
gl_SRC0_ALPHA,
gl_SRC0_RGB,
gl_SRC1_ALPHA,
gl_SRC1_RGB,
gl_SRC2_ALPHA,
gl_SRC2_RGB,
gl_SRC_ALPHA,
gl_SRC_ALPHA_SATURATE,
gl_SRC_COLOR,
gl_STACK_OVERFLOW,
gl_STACK_UNDERFLOW,
gl_STATIC_COPY,
gl_STATIC_DRAW,
gl_STATIC_READ,
gl_STENCIL,
gl_STENCIL_BACK_FAIL,
gl_STENCIL_BACK_FUNC,
gl_STENCIL_BACK_PASS_DEPTH_FAIL,
gl_STENCIL_BACK_PASS_DEPTH_PASS,
gl_STENCIL_BACK_REF,
gl_STENCIL_BACK_VALUE_MASK,
gl_STENCIL_BACK_WRITEMASK,
gl_STENCIL_BITS,
gl_STENCIL_BUFFER_BIT,
gl_STENCIL_CLEAR_VALUE,
gl_STENCIL_FAIL,
gl_STENCIL_FUNC,
gl_STENCIL_INDEX,
gl_STENCIL_PASS_DEPTH_FAIL,
gl_STENCIL_PASS_DEPTH_PASS,
gl_STENCIL_REF,
gl_STENCIL_TEST,
gl_STENCIL_VALUE_MASK,
gl_STENCIL_WRITEMASK,
gl_STEREO,
gl_STREAM_COPY,
gl_STREAM_DRAW,
gl_STREAM_READ,
gl_SUBPIXEL_BITS,
gl_SUBTRACT,
gl_T,
gl_T2F_C3F_V3F,
gl_T2F_C4F_N3F_V3F,
gl_T2F_C4UB_V3F,
gl_T2F_N3F_V3F,
gl_T2F_V3F,
gl_T4F_C4F_N3F_V4F,
gl_T4F_V4F,
gl_TEXTURE,
gl_TEXTURE0,
gl_TEXTURE1,
gl_TEXTURE10,
gl_TEXTURE11,
gl_TEXTURE12,
gl_TEXTURE13,
gl_TEXTURE14,
gl_TEXTURE15,
gl_TEXTURE16,
gl_TEXTURE17,
gl_TEXTURE18,
gl_TEXTURE19,
gl_TEXTURE2,
gl_TEXTURE20,
gl_TEXTURE21,
gl_TEXTURE22,
gl_TEXTURE23,
gl_TEXTURE24,
gl_TEXTURE25,
gl_TEXTURE26,
gl_TEXTURE27,
gl_TEXTURE28,
gl_TEXTURE29,
gl_TEXTURE3,
gl_TEXTURE30,
gl_TEXTURE31,
gl_TEXTURE4,
gl_TEXTURE5,
gl_TEXTURE6,
gl_TEXTURE7,
gl_TEXTURE8,
gl_TEXTURE9,
gl_TEXTURE_1D,
gl_TEXTURE_2D,
gl_TEXTURE_3D,
gl_TEXTURE_ALPHA_SIZE,
gl_TEXTURE_BASE_LEVEL,
gl_TEXTURE_BINDING_1D,
gl_TEXTURE_BINDING_2D,
gl_TEXTURE_BINDING_3D,
gl_TEXTURE_BINDING_CUBE_MAP,
gl_TEXTURE_BIT,
gl_TEXTURE_BLUE_SIZE,
gl_TEXTURE_BORDER,
gl_TEXTURE_BORDER_COLOR,
gl_TEXTURE_COMPARE_FUNC,
gl_TEXTURE_COMPARE_MODE,
gl_TEXTURE_COMPONENTS,
gl_TEXTURE_COMPRESSED,
gl_TEXTURE_COMPRESSED_IMAGE_SIZE,
gl_TEXTURE_COMPRESSION_HINT,
gl_TEXTURE_COORD_ARRAY,
gl_TEXTURE_COORD_ARRAY_BUFFER_BINDING,
gl_TEXTURE_COORD_ARRAY_POINTER,
gl_TEXTURE_COORD_ARRAY_SIZE,
gl_TEXTURE_COORD_ARRAY_STRIDE,
gl_TEXTURE_COORD_ARRAY_TYPE,
gl_TEXTURE_CUBE_MAP,
gl_TEXTURE_CUBE_MAP_NEGATIVE_X,
gl_TEXTURE_CUBE_MAP_NEGATIVE_Y,
gl_TEXTURE_CUBE_MAP_NEGATIVE_Z,
gl_TEXTURE_CUBE_MAP_POSITIVE_X,
gl_TEXTURE_CUBE_MAP_POSITIVE_Y,
gl_TEXTURE_CUBE_MAP_POSITIVE_Z,
gl_TEXTURE_DEPTH,
gl_TEXTURE_DEPTH_SIZE,
gl_TEXTURE_ENV,
gl_TEXTURE_ENV_COLOR,
gl_TEXTURE_ENV_MODE,
gl_TEXTURE_FILTER_CONTROL,
gl_TEXTURE_GEN_MODE,
gl_TEXTURE_GEN_Q,
gl_TEXTURE_GEN_R,
gl_TEXTURE_GEN_S,
gl_TEXTURE_GEN_T,
gl_TEXTURE_GREEN_SIZE,
gl_TEXTURE_HEIGHT,
gl_TEXTURE_INTENSITY_SIZE,
gl_TEXTURE_INTERNAL_FORMAT,
gl_TEXTURE_LOD_BIAS,
gl_TEXTURE_LUMINANCE_SIZE,
gl_TEXTURE_MAG_FILTER,
gl_TEXTURE_MATRIX,
gl_TEXTURE_MAX_LEVEL,
gl_TEXTURE_MAX_LOD,
gl_TEXTURE_MIN_FILTER,
gl_TEXTURE_MIN_LOD,
gl_TEXTURE_PRIORITY,
gl_TEXTURE_RED_SIZE,
gl_TEXTURE_RESIDENT,
gl_TEXTURE_STACK_DEPTH,
gl_TEXTURE_WIDTH,
gl_TEXTURE_WRAP_R,
gl_TEXTURE_WRAP_S,
gl_TEXTURE_WRAP_T,
gl_TRANSFORM_BIT,
gl_TRANSPOSE_COLOR_MATRIX,
gl_TRANSPOSE_MODELVIEW_MATRIX,
gl_TRANSPOSE_PROJECTION_MATRIX,
gl_TRANSPOSE_TEXTURE_MATRIX,
gl_TRIANGLES,
gl_TRIANGLE_FAN,
gl_TRIANGLE_STRIP,
gl_TRUE,
gl_UNPACK_ALIGNMENT,
gl_UNPACK_IMAGE_HEIGHT,
gl_UNPACK_LSB_FIRST,
gl_UNPACK_ROW_LENGTH,
gl_UNPACK_SKIP_IMAGES,
gl_UNPACK_SKIP_PIXELS,
gl_UNPACK_SKIP_ROWS,
gl_UNPACK_SWAP_BYTES,
gl_UNSIGNED_BYTE,
gl_UNSIGNED_BYTE_2_3_3_REV,
gl_UNSIGNED_BYTE_3_3_2,
gl_UNSIGNED_INT,
gl_UNSIGNED_INT_10_10_10_2,
gl_UNSIGNED_INT_2_10_10_10_REV,
gl_UNSIGNED_INT_8_8_8_8,
gl_UNSIGNED_INT_8_8_8_8_REV,
gl_UNSIGNED_SHORT,
gl_UNSIGNED_SHORT_1_5_5_5_REV,
gl_UNSIGNED_SHORT_4_4_4_4,
gl_UNSIGNED_SHORT_4_4_4_4_REV,
gl_UNSIGNED_SHORT_5_5_5_1,
gl_UNSIGNED_SHORT_5_6_5,
gl_UNSIGNED_SHORT_5_6_5_REV,
gl_UPPER_LEFT,
gl_V2F,
gl_V3F,
gl_VALIDATE_STATUS,
gl_VENDOR,
gl_VERSION,
gl_VERTEX_ARRAY,
gl_VERTEX_ARRAY_BUFFER_BINDING,
gl_VERTEX_ARRAY_POINTER,
gl_VERTEX_ARRAY_SIZE,
gl_VERTEX_ARRAY_STRIDE,
gl_VERTEX_ARRAY_TYPE,
gl_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING,
gl_VERTEX_ATTRIB_ARRAY_ENABLED,
gl_VERTEX_ATTRIB_ARRAY_NORMALIZED,
gl_VERTEX_ATTRIB_ARRAY_POINTER,
gl_VERTEX_ATTRIB_ARRAY_SIZE,
gl_VERTEX_ATTRIB_ARRAY_STRIDE,
gl_VERTEX_ATTRIB_ARRAY_TYPE,
gl_VERTEX_PROGRAM_POINT_SIZE,
gl_VERTEX_PROGRAM_TWO_SIDE,
gl_VERTEX_SHADER,
gl_VIEWPORT,
gl_VIEWPORT_BIT,
gl_WEIGHT_ARRAY_BUFFER_BINDING,
gl_WRITE_ONLY,
gl_XOR,
gl_ZERO,
gl_ZOOM_X,
gl_ZOOM_Y,
-- * Functions
glAccum,
glActiveTexture,
glAlphaFunc,
glAreTexturesResident,
glArrayElement,
glAttachShader,
glBegin,
glBeginQuery,
glBindAttribLocation,
glBindBuffer,
glBindTexture,
glBitmap,
glBlendColor,
glBlendEquation,
glBlendEquationSeparate,
glBlendFunc,
glBlendFuncSeparate,
glBufferData,
glBufferSubData,
glCallList,
glCallLists,
glClear,
glClearAccum,
glClearColor,
glClearDepth,
glClearIndex,
glClearStencil,
glClientActiveTexture,
glClipPlane,
glColor3b,
glColor3bv,
glColor3d,
glColor3dv,
glColor3f,
glColor3fv,
glColor3i,
glColor3iv,
glColor3s,
glColor3sv,
glColor3ub,
glColor3ubv,
glColor3ui,
glColor3uiv,
glColor3us,
glColor3usv,
glColor4b,
glColor4bv,
glColor4d,
glColor4dv,
glColor4f,
glColor4fv,
glColor4i,
glColor4iv,
glColor4s,
glColor4sv,
glColor4ub,
glColor4ubv,
glColor4ui,
glColor4uiv,
glColor4us,
glColor4usv,
glColorMask,
glColorMaterial,
glColorPointer,
glCompileShader,
glCompressedTexImage1D,
glCompressedTexImage2D,
glCompressedTexImage3D,
glCompressedTexSubImage1D,
glCompressedTexSubImage2D,
glCompressedTexSubImage3D,
glCopyPixels,
glCopyTexImage1D,
glCopyTexImage2D,
glCopyTexSubImage1D,
glCopyTexSubImage2D,
glCopyTexSubImage3D,
glCreateProgram,
glCreateShader,
glCullFace,
glDeleteBuffers,
glDeleteLists,
glDeleteProgram,
glDeleteQueries,
glDeleteShader,
glDeleteTextures,
glDepthFunc,
glDepthMask,
glDepthRange,
glDetachShader,
glDisable,
glDisableClientState,
glDisableVertexAttribArray,
glDrawArrays,
glDrawBuffer,
glDrawBuffers,
glDrawElements,
glDrawPixels,
glDrawRangeElements,
glEdgeFlag,
glEdgeFlagPointer,
glEdgeFlagv,
glEnable,
glEnableClientState,
glEnableVertexAttribArray,
glEnd,
glEndList,
glEndQuery,
glEvalCoord1d,
glEvalCoord1dv,
glEvalCoord1f,
glEvalCoord1fv,
glEvalCoord2d,
glEvalCoord2dv,
glEvalCoord2f,
glEvalCoord2fv,
glEvalMesh1,
glEvalMesh2,
glEvalPoint1,
glEvalPoint2,
glFeedbackBuffer,
glFinish,
glFlush,
glFogCoordPointer,
glFogCoordd,
glFogCoorddv,
glFogCoordf,
glFogCoordfv,
glFogf,
glFogfv,
glFogi,
glFogiv,
glFrontFace,
glFrustum,
glGenBuffers,
glGenLists,
glGenQueries,
glGenTextures,
glGetActiveAttrib,
glGetActiveUniform,
glGetAttachedShaders,
glGetAttribLocation,
glGetBooleanv,
glGetBufferParameteriv,
glGetBufferPointerv,
glGetBufferSubData,
glGetClipPlane,
glGetCompressedTexImage,
glGetDoublev,
glGetError,
glGetFloatv,
glGetIntegerv,
glGetLightfv,
glGetLightiv,
glGetMapdv,
glGetMapfv,
glGetMapiv,
glGetMaterialfv,
glGetMaterialiv,
glGetPixelMapfv,
glGetPixelMapuiv,
glGetPixelMapusv,
glGetPointerv,
glGetPolygonStipple,
glGetProgramInfoLog,
glGetProgramiv,
glGetQueryObjectiv,
glGetQueryObjectuiv,
glGetQueryiv,
glGetShaderInfoLog,
glGetShaderSource,
glGetShaderiv,
glGetString,
glGetTexEnvfv,
glGetTexEnviv,
glGetTexGendv,
glGetTexGenfv,
glGetTexGeniv,
glGetTexImage,
glGetTexLevelParameterfv,
glGetTexLevelParameteriv,
glGetTexParameterfv,
glGetTexParameteriv,
glGetUniformLocation,
glGetUniformfv,
glGetUniformiv,
glGetVertexAttribPointerv,
glGetVertexAttribdv,
glGetVertexAttribfv,
glGetVertexAttribiv,
glHint,
glIndexMask,
glIndexPointer,
glIndexd,
glIndexdv,
glIndexf,
glIndexfv,
glIndexi,
glIndexiv,
glIndexs,
glIndexsv,
glIndexub,
glIndexubv,
glInitNames,
glInterleavedArrays,
glIsBuffer,
glIsEnabled,
glIsList,
glIsProgram,
glIsQuery,
glIsShader,
glIsTexture,
glLightModelf,
glLightModelfv,
glLightModeli,
glLightModeliv,
glLightf,
glLightfv,
glLighti,
glLightiv,
glLineStipple,
glLineWidth,
glLinkProgram,
glListBase,
glLoadIdentity,
glLoadMatrixd,
glLoadMatrixf,
glLoadName,
glLoadTransposeMatrixd,
glLoadTransposeMatrixf,
glLogicOp,
glMap1d,
glMap1f,
glMap2d,
glMap2f,
glMapBuffer,
glMapGrid1d,
glMapGrid1f,
glMapGrid2d,
glMapGrid2f,
glMaterialf,
glMaterialfv,
glMateriali,
glMaterialiv,
glMatrixMode,
glMultMatrixd,
glMultMatrixf,
glMultTransposeMatrixd,
glMultTransposeMatrixf,
glMultiDrawArrays,
glMultiDrawElements,
glMultiTexCoord1d,
glMultiTexCoord1dv,
glMultiTexCoord1f,
glMultiTexCoord1fv,
glMultiTexCoord1i,
glMultiTexCoord1iv,
glMultiTexCoord1s,
glMultiTexCoord1sv,
glMultiTexCoord2d,
glMultiTexCoord2dv,
glMultiTexCoord2f,
glMultiTexCoord2fv,
glMultiTexCoord2i,
glMultiTexCoord2iv,
glMultiTexCoord2s,
glMultiTexCoord2sv,
glMultiTexCoord3d,
glMultiTexCoord3dv,
glMultiTexCoord3f,
glMultiTexCoord3fv,
glMultiTexCoord3i,
glMultiTexCoord3iv,
glMultiTexCoord3s,
glMultiTexCoord3sv,
glMultiTexCoord4d,
glMultiTexCoord4dv,
glMultiTexCoord4f,
glMultiTexCoord4fv,
glMultiTexCoord4i,
glMultiTexCoord4iv,
glMultiTexCoord4s,
glMultiTexCoord4sv,
glNewList,
glNormal3b,
glNormal3bv,
glNormal3d,
glNormal3dv,
glNormal3f,
glNormal3fv,
glNormal3i,
glNormal3iv,
glNormal3s,
glNormal3sv,
glNormalPointer,
glOrtho,
glPassThrough,
glPixelMapfv,
glPixelMapuiv,
glPixelMapusv,
glPixelStoref,
glPixelStorei,
glPixelTransferf,
glPixelTransferi,
glPixelZoom,
glPointParameterf,
glPointParameterfv,
glPointParameteri,
glPointParameteriv,
glPointSize,
glPolygonMode,
glPolygonOffset,
glPolygonStipple,
glPopAttrib,
glPopClientAttrib,
glPopMatrix,
glPopName,
glPrioritizeTextures,
glPushAttrib,
glPushClientAttrib,
glPushMatrix,
glPushName,
glRasterPos2d,
glRasterPos2dv,
glRasterPos2f,
glRasterPos2fv,
glRasterPos2i,
glRasterPos2iv,
glRasterPos2s,
glRasterPos2sv,
glRasterPos3d,
glRasterPos3dv,
glRasterPos3f,
glRasterPos3fv,
glRasterPos3i,
glRasterPos3iv,
glRasterPos3s,
glRasterPos3sv,
glRasterPos4d,
glRasterPos4dv,
glRasterPos4f,
glRasterPos4fv,
glRasterPos4i,
glRasterPos4iv,
glRasterPos4s,
glRasterPos4sv,
glReadBuffer,
glReadPixels,
glRectd,
glRectdv,
glRectf,
glRectfv,
glRecti,
glRectiv,
glRects,
glRectsv,
glRenderMode,
glRotated,
glRotatef,
glSampleCoverage,
glScaled,
glScalef,
glScissor,
glSecondaryColor3b,
glSecondaryColor3bv,
glSecondaryColor3d,
glSecondaryColor3dv,
glSecondaryColor3f,
glSecondaryColor3fv,
glSecondaryColor3i,
glSecondaryColor3iv,
glSecondaryColor3s,
glSecondaryColor3sv,
glSecondaryColor3ub,
glSecondaryColor3ubv,
glSecondaryColor3ui,
glSecondaryColor3uiv,
glSecondaryColor3us,
glSecondaryColor3usv,
glSecondaryColorPointer,
glSelectBuffer,
glShadeModel,
glShaderSource,
glStencilFunc,
glStencilFuncSeparate,
glStencilMask,
glStencilMaskSeparate,
glStencilOp,
glStencilOpSeparate,
glTexCoord1d,
glTexCoord1dv,
glTexCoord1f,
glTexCoord1fv,
glTexCoord1i,
glTexCoord1iv,
glTexCoord1s,
glTexCoord1sv,
glTexCoord2d,
glTexCoord2dv,
glTexCoord2f,
glTexCoord2fv,
glTexCoord2i,
glTexCoord2iv,
glTexCoord2s,
glTexCoord2sv,
glTexCoord3d,
glTexCoord3dv,
glTexCoord3f,
glTexCoord3fv,
glTexCoord3i,
glTexCoord3iv,
glTexCoord3s,
glTexCoord3sv,
glTexCoord4d,
glTexCoord4dv,
glTexCoord4f,
glTexCoord4fv,
glTexCoord4i,
glTexCoord4iv,
glTexCoord4s,
glTexCoord4sv,
glTexCoordPointer,
glTexEnvf,
glTexEnvfv,
glTexEnvi,
glTexEnviv,
glTexGend,
glTexGendv,
glTexGenf,
glTexGenfv,
glTexGeni,
glTexGeniv,
glTexImage1D,
glTexImage2D,
glTexImage3D,
glTexParameterf,
glTexParameterfv,
glTexParameteri,
glTexParameteriv,
glTexSubImage1D,
glTexSubImage2D,
glTexSubImage3D,
glTranslated,
glTranslatef,
glUniform1f,
glUniform1fv,
glUniform1i,
glUniform1iv,
glUniform2f,
glUniform2fv,
glUniform2i,
glUniform2iv,
glUniform3f,
glUniform3fv,
glUniform3i,
glUniform3iv,
glUniform4f,
glUniform4fv,
glUniform4i,
glUniform4iv,
glUniformMatrix2fv,
glUniformMatrix3fv,
glUniformMatrix4fv,
glUnmapBuffer,
glUseProgram,
glValidateProgram,
glVertex2d,
glVertex2dv,
glVertex2f,
glVertex2fv,
glVertex2i,
glVertex2iv,
glVertex2s,
glVertex2sv,
glVertex3d,
glVertex3dv,
glVertex3f,
glVertex3fv,
glVertex3i,
glVertex3iv,
glVertex3s,
glVertex3sv,
glVertex4d,
glVertex4dv,
glVertex4f,
glVertex4fv,
glVertex4i,
glVertex4iv,
glVertex4s,
glVertex4sv,
glVertexAttrib1d,
glVertexAttrib1dv,
glVertexAttrib1f,
glVertexAttrib1fv,
glVertexAttrib1s,
glVertexAttrib1sv,
glVertexAttrib2d,
glVertexAttrib2dv,
glVertexAttrib2f,
glVertexAttrib2fv,
glVertexAttrib2s,
glVertexAttrib2sv,
glVertexAttrib3d,
glVertexAttrib3dv,
glVertexAttrib3f,
glVertexAttrib3fv,
glVertexAttrib3s,
glVertexAttrib3sv,
glVertexAttrib4Nbv,
glVertexAttrib4Niv,
glVertexAttrib4Nsv,
glVertexAttrib4Nub,
glVertexAttrib4Nubv,
glVertexAttrib4Nuiv,
glVertexAttrib4Nusv,
glVertexAttrib4bv,
glVertexAttrib4d,
glVertexAttrib4dv,
glVertexAttrib4f,
glVertexAttrib4fv,
glVertexAttrib4iv,
glVertexAttrib4s,
glVertexAttrib4sv,
glVertexAttrib4ubv,
glVertexAttrib4uiv,
glVertexAttrib4usv,
glVertexAttribPointer,
glVertexPointer,
glViewport,
glWindowPos2d,
glWindowPos2dv,
glWindowPos2f,
glWindowPos2fv,
glWindowPos2i,
glWindowPos2iv,
glWindowPos2s,
glWindowPos2sv,
glWindowPos3d,
glWindowPos3dv,
glWindowPos3f,
glWindowPos3fv,
glWindowPos3i,
glWindowPos3iv,
glWindowPos3s,
glWindowPos3sv
) where
import Graphics.Rendering.OpenGL.Raw.Types
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/Version20.hs | bsd-3-clause | 28,077 | 0 | 4 | 4,313 | 4,279 | 2,860 | 1,419 | 1,414 | 0 |
-- DOM representation and parsing functionality
{-# LANGUAGE OverloadedStrings #-}
module HTML
( DTree (..)
, DElemType (..)
, DAttr (..)
, noAttr
, textElem
, fullTree
, childrenTree
, singletonTree
, parseHTML
) where
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import Data.Attoparsec.Text
import Internal.Types
import Internal.Parser
noAttr :: DAttr
noAttr = DAttr M.empty
textElem :: T.Text -> DTree
textElem = DText
-- Element node with children and attributes
fullTree :: DElemType -> DAttr -> [DTree] -> DTree
fullTree = DElem
-- Basic element node with children, no attributes
childrenTree :: DElemType -> [DTree] -> DTree
childrenTree et = fullTree et noAttr
-- Basic element node with no children, no attributes
singletonTree :: DElemType -> DTree
singletonTree et = childrenTree et []
-- Takes an HTML string (Text) and returns the parsed representation as a
-- DOM tree (or a ParseError)
parseHTML :: T.Text -> Either String DTree
parseHTML = parseOnly $ do
skipSpace
html <- htmlParser
skipSpace
endOfInput
return html
| qnnguyen/howser | src/HTML.hs | bsd-3-clause | 1,128 | 0 | 8 | 235 | 241 | 140 | 101 | 33 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.X11.Xlib.Window
-- Copyright : (c) Alastair Reid, 1999-2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- A collection of FFI declarations for interfacing with Xlib Windows.
--
-----------------------------------------------------------------------------
module Graphics.X11.Xlib.Window(
storeName,
createSimpleWindow,
createWindow,
translateCoordinates,
moveResizeWindow,
resizeWindow,
moveWindow,
reparentWindow,
mapSubwindows,
unmapSubwindows,
mapWindow,
lowerWindow,
raiseWindow,
circulateSubwindowsDown,
circulateSubwindowsUp,
circulateSubwindows,
iconifyWindow,
withdrawWindow,
destroyWindow,
destroySubwindows,
setWindowBorder,
setWindowBorderPixmap,
setWindowBorderWidth,
setWindowBackground,
setWindowBackgroundPixmap,
setWindowColormap,
addToSaveSet,
removeFromSaveSet,
changeSaveSet,
clearWindow,
clearArea,
restackWindows,
) where
import Graphics.X11.Types
import Graphics.X11.Xlib.Types
import Foreign
import Foreign.C
----------------------------------------------------------------
-- Windows
----------------------------------------------------------------
-- | interface to the X11 library function @XStoreName()@.
storeName :: Display -> Window -> String -> IO ()
storeName display window name =
withCString name $ \ c_name ->
xStoreName display window c_name
foreign import ccall unsafe "HsXlib.h XStoreName"
xStoreName :: Display -> Window -> CString -> IO ()
-- | interface to the X11 library function @XCreateSimpleWindow()@.
foreign import ccall unsafe "HsXlib.h XCreateSimpleWindow"
createSimpleWindow :: Display -> Window -> Position -> Position ->
Dimension -> Dimension -> Int -> Pixel -> Pixel -> IO Window
-- | interface to the X11 library function @XCreateWindow()@.
foreign import ccall unsafe "HsXlib.h XCreateWindow"
createWindow :: Display -> Window -> Position -> Position ->
Dimension -> Dimension -> Int -> Int -> WindowClass ->
Visual -> AttributeMask -> Ptr SetWindowAttributes -> IO Window
----------------------------------------------------------------
--ToDo: find an effective way to use Maybes
-- | interface to the X11 library function @XTranslateCoordinates()@.
translateCoordinates :: Display -> Window -> Window -> Position -> Position ->
IO (Bool,Position,Position,Window)
translateCoordinates display src_w dest_w src_x src_y =
alloca $ \ dest_x_return ->
alloca $ \ dest_y_return ->
alloca $ \ child_return -> do
res <- xTranslateCoordinates display src_w dest_w src_x src_y
dest_x_return dest_y_return child_return
dest_x <- peek dest_x_return
dest_y <- peek dest_y_return
child <- peek child_return
return (res, dest_x, dest_y, child)
foreign import ccall unsafe "HsXlib.h XTranslateCoordinates"
xTranslateCoordinates :: Display -> Window -> Window ->
Position -> Position ->
Ptr Position -> Ptr Position -> Ptr Window -> IO Bool
-- | interface to the X11 library function @XMoveResizeWindow()@.
foreign import ccall unsafe "HsXlib.h XMoveResizeWindow"
moveResizeWindow :: Display -> Window -> Position -> Position -> Dimension -> Dimension -> IO ()
-- | interface to the X11 library function @XResizeWindow()@.
foreign import ccall unsafe "HsXlib.h XResizeWindow"
resizeWindow :: Display -> Window -> Dimension -> Dimension -> IO ()
-- | interface to the X11 library function @XMoveWindow()@.
foreign import ccall unsafe "HsXlib.h XMoveWindow"
moveWindow :: Display -> Window -> Position -> Position -> IO ()
-- | interface to the X11 library function @XReparentWindow()@.
foreign import ccall unsafe "HsXlib.h XReparentWindow"
reparentWindow :: Display -> Window -> Window -> Position -> Position -> IO ()
-- | interface to the X11 library function @XMapSubwindows()@.
foreign import ccall unsafe "HsXlib.h XMapSubwindows"
mapSubwindows :: Display -> Window -> IO ()
-- | interface to the X11 library function @XUnmapSubwindows()@.
foreign import ccall unsafe "HsXlib.h XUnmapSubwindows"
unmapSubwindows :: Display -> Window -> IO ()
-- | interface to the X11 library function @XMapWindow()@.
foreign import ccall unsafe "HsXlib.h XMapWindow"
mapWindow :: Display -> Window -> IO ()
-- Disnae exist: %fun XUnmapWindows :: Display -> Window -> IO ()
-- Disnae exist: %fun XMapRaisedWindow :: Display -> Window -> IO ()
-- | interface to the X11 library function @XLowerWindow()@.
foreign import ccall unsafe "HsXlib.h XLowerWindow"
lowerWindow :: Display -> Window -> IO ()
-- | interface to the X11 library function @XRaiseWindow()@.
foreign import ccall unsafe "HsXlib.h XRaiseWindow"
raiseWindow :: Display -> Window -> IO ()
-- | interface to the X11 library function @XCirculateSubwindowsDown()@.
foreign import ccall unsafe "HsXlib.h XCirculateSubwindowsDown"
circulateSubwindowsDown :: Display -> Window -> IO ()
-- | interface to the X11 library function @XCirculateSubwindowsUp()@.
foreign import ccall unsafe "HsXlib.h XCirculateSubwindowsUp"
circulateSubwindowsUp :: Display -> Window -> IO ()
-- | interface to the X11 library function @XCirculateSubwindows()@.
foreign import ccall unsafe "HsXlib.h XCirculateSubwindows"
circulateSubwindows :: Display -> Window -> CirculationDirection -> IO ()
-- | interface to the X11 library function @XIconifyWindow()@.
iconifyWindow :: Display -> Window -> ScreenNumber -> IO ()
iconifyWindow display window screenno =
throwIfZero "iconifyWindow"
(xIconifyWindow display window screenno)
foreign import ccall unsafe "HsXlib.h XIconifyWindow"
xIconifyWindow :: Display -> Window -> ScreenNumber -> IO Status
-- | interface to the X11 library function @XWithdrawWindow()@.
withdrawWindow :: Display -> Window -> ScreenNumber -> IO ()
withdrawWindow display window screenno =
throwIfZero "withdrawWindow"
(xWithdrawWindow display window screenno)
foreign import ccall unsafe "HsXlib.h XWithdrawWindow"
xWithdrawWindow :: Display -> Window -> ScreenNumber -> IO Status
-- | interface to the X11 library function @XDestroyWindow()@.
foreign import ccall unsafe "HsXlib.h XDestroyWindow"
destroyWindow :: Display -> Window -> IO ()
-- | interface to the X11 library function @XDestroySubwindows()@.
foreign import ccall unsafe "HsXlib.h XDestroySubwindows"
destroySubwindows :: Display -> Window -> IO ()
-- | interface to the X11 library function @XSetWindowBorder()@.
foreign import ccall unsafe "HsXlib.h XSetWindowBorder"
setWindowBorder :: Display -> Window -> Pixel -> IO ()
-- | interface to the X11 library function @XSetWindowBorderPixmap()@.
foreign import ccall unsafe "HsXlib.h XSetWindowBorderPixmap"
setWindowBorderPixmap :: Display -> Window -> Pixmap -> IO ()
-- | interface to the X11 library function @XSetWindowBorderWidth()@.
foreign import ccall unsafe "HsXlib.h XSetWindowBorderWidth"
setWindowBorderWidth :: Display -> Window -> Dimension -> IO ()
-- | interface to the X11 library function @XSetWindowBackground()@.
foreign import ccall unsafe "HsXlib.h XSetWindowBackground"
setWindowBackground :: Display -> Window -> Pixel -> IO ()
-- | interface to the X11 library function @XSetWindowBackgroundPixmap()@.
foreign import ccall unsafe "HsXlib.h XSetWindowBackgroundPixmap"
setWindowBackgroundPixmap :: Display -> Window -> Pixmap -> IO ()
-- | interface to the X11 library function @XSetWindowColormap()@.
foreign import ccall unsafe "HsXlib.h XSetWindowColormap"
setWindowColormap :: Display -> Window -> Colormap -> IO ()
-- | interface to the X11 library function @XAddToSaveSet()@.
foreign import ccall unsafe "HsXlib.h XAddToSaveSet"
addToSaveSet :: Display -> Window -> IO ()
-- | interface to the X11 library function @XRemoveFromSaveSet()@.
foreign import ccall unsafe "HsXlib.h XRemoveFromSaveSet"
removeFromSaveSet :: Display -> Window -> IO ()
-- | interface to the X11 library function @XChangeSaveSet()@.
foreign import ccall unsafe "HsXlib.h XChangeSaveSet"
changeSaveSet :: Display -> Window -> ChangeSaveSetMode -> IO ()
-- | interface to the X11 library function @XClearWindow()@.
foreign import ccall unsafe "HsXlib.h XClearWindow"
clearWindow :: Display -> Window -> IO ()
-- | interface to the X11 library function @XClearArea()@.
foreign import ccall unsafe "HsXlib.h XClearArea"
clearArea :: Display -> Window ->
Position -> Position -> Dimension -> Dimension -> Bool -> IO ()
-- This is almost good enough - but doesn't call XFree
-- -- %errfun BadStatus XQueryTree :: Display -> Window -> IO (Window, Window, ListWindow) using err = XQueryTree(arg1,arg2,&res1,&res2,&res3,&res3_size)
-- %prim XQueryTree :: Display -> Window -> IO (Window, Window, ListWindow)
-- Window root_w, parent;
-- Int children_size;
-- Window *children;
-- Status r = XQueryTree(arg1,arg2,&root_w, &parent, &children, &children_size);
-- if (Success != r) { %failWith(BadStatus,r); }
-- %update(root_w,parent,children);
-- XFree(children);
-- return;
-- | interface to the X11 library function @XRestackWindows()@.
restackWindows :: Display -> [Window] -> IO ()
restackWindows display windows =
withArray windows $ \ window_array ->
xRestackWindows display window_array (length windows)
foreign import ccall unsafe "HsXlib.h XRestackWindows"
xRestackWindows :: Display -> Ptr Window -> Int -> IO ()
-- ToDo: I want to be able to write this
-- -- %fun XListInstalledColormaps :: Display -> Window -> IO ListColormap using res1 = XListInstalledColormaps(arg1,arg2,&res1_size)
-- -- But I have to write this instead - need to add a notion of cleanup code!
-- %prim XListInstalledColormaps :: Display -> Window -> IO ListColormap
-- Int r_size;
-- Colormap* r = XListInstalledColormaps(arg1,arg2,&r_size);
-- %update(r);
-- XFree(r);
-- return;
--
-- -- Again, this is almost good enough
-- -- %errfun BadStatus XGetCommand :: Display -> Window -> IO ListString using err = XGetCommand(arg1,arg2,&res1,&res1_size)
-- -- but not quite
-- -- %prim XGetCommand :: Display -> Window -> IO ListString
-- --Int argv_size;
-- --String *argv;
-- --Status r = XGetCommand(arg1,arg2,&argv,&argv_size);
-- --if (Success != r) { %failWith(BadStatus, r); }
-- -- %update(argv);
-- --XFreeStringList(argv);
-- --return;
--
-- -- %fun XSetCommand :: Display -> Window -> ListString -> IO () using XSetCommand(arg1,arg2,arg3,res3_size)
--
-- %errfun BadStatus XGetTransientForHint :: Display -> Window -> IO Window using err = XGetTransientForHint(arg1,arg2,&res1)
--
-- %fun XSetTransientForHint :: Display -> Window -> Window -> IO ()
--
-- -- XRotateWindowProperties omitted
-- -- XGetWindowProperty omitted
--
-- -- XGetWindowAttributes omitted
-- -- XChangeWindowAttributes omitted
----------------------------------------------------------------
-- End
----------------------------------------------------------------
| FranklinChen/hugs98-plus-Sep2006 | packages/X11/Graphics/X11/Xlib/Window.hs | bsd-3-clause | 11,523 | 102 | 18 | 2,176 | 1,764 | 966 | 798 | 135 | 1 |
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE BangPatterns #-}
#if __GLASGOW_HASKELL__ < 800
-- For CallStack business
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE FlexibleContexts #-}
#endif
-- | Highly random utility functions
--
module Util (
-- * Flags dependent on the compiler build
ghciSupported, debugIsOn, ncgDebugIsOn,
ghciTablesNextToCode,
isWindowsHost, isDarwinHost,
-- * General list processing
zipEqual, zipWithEqual, zipWith3Equal, zipWith4Equal,
zipLazy, stretchZipWith, zipWithAndUnzip,
zipWithLazy, zipWith3Lazy,
filterByList, filterByLists, partitionByList,
unzipWith,
mapFst, mapSnd, chkAppend,
mapAndUnzip, mapAndUnzip3, mapAccumL2,
nOfThem, filterOut, partitionWith, splitEithers,
dropWhileEndLE, spanEnd,
foldl1', foldl2, count, all2,
lengthExceeds, lengthIs, lengthAtLeast,
listLengthCmp, atLength,
equalLength, compareLength, leLength,
isSingleton, only, singleton,
notNull, snocView,
isIn, isn'tIn,
chunkList,
changeLast,
-- * Tuples
fstOf3, sndOf3, thdOf3,
firstM, first3M,
fst3, snd3, third3,
uncurry3,
liftFst, liftSnd,
-- * List operations controlled by another list
takeList, dropList, splitAtList, split,
dropTail, capitalise,
-- * For loop
nTimes,
-- * Sorting
sortWith, minWith, nubSort,
-- * Comparisons
isEqual, eqListBy, eqMaybeBy,
thenCmp, cmpList,
removeSpaces,
(<&&>), (<||>),
-- * Edit distance
fuzzyMatch, fuzzyLookup,
-- * Transitive closures
transitiveClosure,
-- * Strictness
seqList,
-- * Module names
looksLikeModuleName,
looksLikePackageName,
-- * Argument processing
getCmd, toCmdArgs, toArgs,
-- * Integers
exactLog2,
-- * Floating point
readRational,
-- * read helpers
maybeRead, maybeReadFuzzy,
-- * IO-ish utilities
doesDirNameExist,
getModificationUTCTime,
modificationTimeIfExists,
hSetTranslit,
global, consIORef, globalM,
-- * Filenames and paths
Suffix,
splitLongestPrefix,
escapeSpaces,
Direction(..), reslash,
makeRelativeTo,
-- * Utils for defining Data instances
abstractConstr, abstractDataType, mkNoRepType,
-- * Utils for printing C code
charToC,
-- * Hashing
hashString,
-- * Call stacks
GHC.Stack.CallStack,
HasCallStack,
HasDebugCallStack,
prettyCurrentCallStack,
) where
#include "HsVersions.h"
import Exception
import Panic
import Data.Data
import Data.IORef ( IORef, newIORef, atomicModifyIORef' )
import System.IO.Unsafe ( unsafePerformIO )
import Data.List hiding (group)
import GHC.Exts
import qualified GHC.Stack
import Control.Applicative ( liftA2 )
import Control.Monad ( liftM )
import GHC.IO.Encoding (mkTextEncoding, textEncodingName)
import System.IO (Handle, hGetEncoding, hSetEncoding)
import System.IO.Error as IO ( isDoesNotExistError )
import System.Directory ( doesDirectoryExist, getModificationTime )
import System.FilePath
import Data.Char ( isUpper, isAlphaNum, isSpace, chr, ord, isDigit, toUpper)
import Data.Int
import Data.Ratio ( (%) )
import Data.Ord ( comparing )
import Data.Bits
import Data.Word
import qualified Data.IntMap as IM
import qualified Data.Set as Set
import Data.Time
infixr 9 `thenCmp`
{-
************************************************************************
* *
\subsection{Is DEBUG on, are we on Windows, etc?}
* *
************************************************************************
These booleans are global constants, set by CPP flags. They allow us to
recompile a single module (this one) to change whether or not debug output
appears. They sometimes let us avoid even running CPP elsewhere.
It's important that the flags are literal constants (True/False). Then,
with -0, tests of the flags in other modules will simplify to the correct
branch of the conditional, thereby dropping debug code altogether when
the flags are off.
-}
ghciSupported :: Bool
#ifdef GHCI
ghciSupported = True
#else
ghciSupported = False
#endif
debugIsOn :: Bool
#ifdef DEBUG
debugIsOn = True
#else
debugIsOn = False
#endif
ncgDebugIsOn :: Bool
#ifdef NCG_DEBUG
ncgDebugIsOn = True
#else
ncgDebugIsOn = False
#endif
ghciTablesNextToCode :: Bool
#ifdef GHCI_TABLES_NEXT_TO_CODE
ghciTablesNextToCode = True
#else
ghciTablesNextToCode = False
#endif
isWindowsHost :: Bool
#ifdef mingw32_HOST_OS
isWindowsHost = True
#else
isWindowsHost = False
#endif
isDarwinHost :: Bool
#ifdef darwin_HOST_OS
isDarwinHost = True
#else
isDarwinHost = False
#endif
{-
************************************************************************
* *
\subsection{A for loop}
* *
************************************************************************
-}
-- | Compose a function with itself n times. (nth rather than twice)
nTimes :: Int -> (a -> a) -> (a -> a)
nTimes 0 _ = id
nTimes 1 f = f
nTimes n f = f . nTimes (n-1) f
fstOf3 :: (a,b,c) -> a
sndOf3 :: (a,b,c) -> b
thdOf3 :: (a,b,c) -> c
fstOf3 (a,_,_) = a
sndOf3 (_,b,_) = b
thdOf3 (_,_,c) = c
fst3 :: (a -> d) -> (a, b, c) -> (d, b, c)
fst3 f (a, b, c) = (f a, b, c)
snd3 :: (b -> d) -> (a, b, c) -> (a, d, c)
snd3 f (a, b, c) = (a, f b, c)
third3 :: (c -> d) -> (a, b, c) -> (a, b, d)
third3 f (a, b, c) = (a, b, f c)
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 f (a, b, c) = f a b c
liftFst :: (a -> b) -> (a, c) -> (b, c)
liftFst f (a,c) = (f a, c)
liftSnd :: (a -> b) -> (c, a) -> (c, b)
liftSnd f (c,a) = (c, f a)
firstM :: Monad m => (a -> m c) -> (a, b) -> m (c, b)
firstM f (x, y) = liftM (\x' -> (x', y)) (f x)
first3M :: Monad m => (a -> m d) -> (a, b, c) -> m (d, b, c)
first3M f (x, y, z) = liftM (\x' -> (x', y, z)) (f x)
{-
************************************************************************
* *
\subsection[Utils-lists]{General list processing}
* *
************************************************************************
-}
filterOut :: (a->Bool) -> [a] -> [a]
-- ^ Like filter, only it reverses the sense of the test
filterOut _ [] = []
filterOut p (x:xs) | p x = filterOut p xs
| otherwise = x : filterOut p xs
partitionWith :: (a -> Either b c) -> [a] -> ([b], [c])
-- ^ Uses a function to determine which of two output lists an input element should join
partitionWith _ [] = ([],[])
partitionWith f (x:xs) = case f x of
Left b -> (b:bs, cs)
Right c -> (bs, c:cs)
where (bs,cs) = partitionWith f xs
splitEithers :: [Either a b] -> ([a], [b])
-- ^ Teases a list of 'Either's apart into two lists
splitEithers [] = ([],[])
splitEithers (e : es) = case e of
Left x -> (x:xs, ys)
Right y -> (xs, y:ys)
where (xs,ys) = splitEithers es
chkAppend :: [a] -> [a] -> [a]
-- Checks for the second arguemnt being empty
-- Used in situations where that situation is common
chkAppend xs ys
| null ys = xs
| otherwise = xs ++ ys
{-
A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
are of equal length. Alastair Reid thinks this should only happen if
DEBUGging on; hey, why not?
-}
zipEqual :: String -> [a] -> [b] -> [(a,b)]
zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
#ifndef DEBUG
zipEqual _ = zip
zipWithEqual _ = zipWith
zipWith3Equal _ = zipWith3
zipWith4Equal _ = zipWith4
#else
zipEqual _ [] [] = []
zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
zipEqual msg _ _ = panic ("zipEqual: unequal lists:"++msg)
zipWithEqual msg z (a:as) (b:bs)= z a b : zipWithEqual msg z as bs
zipWithEqual _ _ [] [] = []
zipWithEqual msg _ _ _ = panic ("zipWithEqual: unequal lists:"++msg)
zipWith3Equal msg z (a:as) (b:bs) (c:cs)
= z a b c : zipWith3Equal msg z as bs cs
zipWith3Equal _ _ [] [] [] = []
zipWith3Equal msg _ _ _ _ = panic ("zipWith3Equal: unequal lists:"++msg)
zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
= z a b c d : zipWith4Equal msg z as bs cs ds
zipWith4Equal _ _ [] [] [] [] = []
zipWith4Equal msg _ _ _ _ _ = panic ("zipWith4Equal: unequal lists:"++msg)
#endif
-- | 'zipLazy' is a kind of 'zip' that is lazy in the second list (observe the ~)
zipLazy :: [a] -> [b] -> [(a,b)]
zipLazy [] _ = []
zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
-- | 'zipWithLazy' is like 'zipWith' but is lazy in the second list.
-- The length of the output is always the same as the length of the first
-- list.
zipWithLazy :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWithLazy _ [] _ = []
zipWithLazy f (a:as) ~(b:bs) = f a b : zipWithLazy f as bs
-- | 'zipWith3Lazy' is like 'zipWith3' but is lazy in the second and third lists.
-- The length of the output is always the same as the length of the first
-- list.
zipWith3Lazy :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3Lazy _ [] _ _ = []
zipWith3Lazy f (a:as) ~(b:bs) ~(c:cs) = f a b c : zipWith3Lazy f as bs cs
-- | 'filterByList' takes a list of Bools and a list of some elements and
-- filters out these elements for which the corresponding value in the list of
-- Bools is False. This function does not check whether the lists have equal
-- length.
filterByList :: [Bool] -> [a] -> [a]
filterByList (True:bs) (x:xs) = x : filterByList bs xs
filterByList (False:bs) (_:xs) = filterByList bs xs
filterByList _ _ = []
-- | 'filterByLists' takes a list of Bools and two lists as input, and
-- outputs a new list consisting of elements from the last two input lists. For
-- each Bool in the list, if it is 'True', then it takes an element from the
-- former list. If it is 'False', it takes an element from the latter list.
-- The elements taken correspond to the index of the Bool in its list.
-- For example:
--
-- @
-- filterByLists [True, False, True, False] \"abcd\" \"wxyz\" = \"axcz\"
-- @
--
-- This function does not check whether the lists have equal length.
filterByLists :: [Bool] -> [a] -> [a] -> [a]
filterByLists (True:bs) (x:xs) (_:ys) = x : filterByLists bs xs ys
filterByLists (False:bs) (_:xs) (y:ys) = y : filterByLists bs xs ys
filterByLists _ _ _ = []
-- | 'partitionByList' takes a list of Bools and a list of some elements and
-- partitions the list according to the list of Bools. Elements corresponding
-- to 'True' go to the left; elements corresponding to 'False' go to the right.
-- For example, @partitionByList [True, False, True] [1,2,3] == ([1,3], [2])@
-- This function does not check whether the lists have equal
-- length.
partitionByList :: [Bool] -> [a] -> ([a], [a])
partitionByList = go [] []
where
go trues falses (True : bs) (x : xs) = go (x:trues) falses bs xs
go trues falses (False : bs) (x : xs) = go trues (x:falses) bs xs
go trues falses _ _ = (reverse trues, reverse falses)
stretchZipWith :: (a -> Bool) -> b -> (a->b->c) -> [a] -> [b] -> [c]
-- ^ @stretchZipWith p z f xs ys@ stretches @ys@ by inserting @z@ in
-- the places where @p@ returns @True@
stretchZipWith _ _ _ [] _ = []
stretchZipWith p z f (x:xs) ys
| p x = f x z : stretchZipWith p z f xs ys
| otherwise = case ys of
[] -> []
(y:ys) -> f x y : stretchZipWith p z f xs ys
mapFst :: (a->c) -> [(a,b)] -> [(c,b)]
mapSnd :: (b->c) -> [(a,b)] -> [(a,c)]
mapFst f xys = [(f x, y) | (x,y) <- xys]
mapSnd f xys = [(x, f y) | (x,y) <- xys]
mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
mapAndUnzip _ [] = ([], [])
mapAndUnzip f (x:xs)
= let (r1, r2) = f x
(rs1, rs2) = mapAndUnzip f xs
in
(r1:rs1, r2:rs2)
mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
mapAndUnzip3 _ [] = ([], [], [])
mapAndUnzip3 f (x:xs)
= let (r1, r2, r3) = f x
(rs1, rs2, rs3) = mapAndUnzip3 f xs
in
(r1:rs1, r2:rs2, r3:rs3)
zipWithAndUnzip :: (a -> b -> (c,d)) -> [a] -> [b] -> ([c],[d])
zipWithAndUnzip f (a:as) (b:bs)
= let (r1, r2) = f a b
(rs1, rs2) = zipWithAndUnzip f as bs
in
(r1:rs1, r2:rs2)
zipWithAndUnzip _ _ _ = ([],[])
mapAccumL2 :: (s1 -> s2 -> a -> (s1, s2, b)) -> s1 -> s2 -> [a] -> (s1, s2, [b])
mapAccumL2 f s1 s2 xs = (s1', s2', ys)
where ((s1', s2'), ys) = mapAccumL (\(s1, s2) x -> case f s1 s2 x of
(s1', s2', y) -> ((s1', s2'), y))
(s1, s2) xs
nOfThem :: Int -> a -> [a]
nOfThem n thing = replicate n thing
-- | @atLength atLen atEnd ls n@ unravels list @ls@ to position @n@. Precisely:
--
-- @
-- atLength atLenPred atEndPred ls n
-- | n < 0 = atLenPred ls
-- | length ls < n = atEndPred (n - length ls)
-- | otherwise = atLenPred (drop n ls)
-- @
atLength :: ([a] -> b) -- Called when length ls >= n, passed (drop n ls)
-- NB: arg passed to this function may be []
-> b -- Called when length ls < n
-> [a]
-> Int
-> b
atLength atLenPred atEnd ls0 n0
| n0 < 0 = atLenPred ls0
| otherwise = go n0 ls0
where
-- go's first arg n >= 0
go 0 ls = atLenPred ls
go _ [] = atEnd -- n > 0 here
go n (_:xs) = go (n-1) xs
-- Some special cases of atLength:
-- | @(lengthExceeds xs n) = (length xs > n)@
lengthExceeds :: [a] -> Int -> Bool
lengthExceeds lst n
| n < 0
= True
| otherwise
= atLength notNull False lst n
lengthAtLeast :: [a] -> Int -> Bool
lengthAtLeast = atLength (const True) False
-- | @(lengthIs xs n) = (length xs == n)@
lengthIs :: [a] -> Int -> Bool
lengthIs lst n
| n < 0
= False
| otherwise
= atLength null False lst n
listLengthCmp :: [a] -> Int -> Ordering
listLengthCmp = atLength atLen atEnd
where
atEnd = LT -- Not yet seen 'n' elts, so list length is < n.
atLen [] = EQ
atLen _ = GT
equalLength :: [a] -> [b] -> Bool
equalLength [] [] = True
equalLength (_:xs) (_:ys) = equalLength xs ys
equalLength _ _ = False
compareLength :: [a] -> [b] -> Ordering
compareLength [] [] = EQ
compareLength (_:xs) (_:ys) = compareLength xs ys
compareLength [] _ = LT
compareLength _ [] = GT
leLength :: [a] -> [b] -> Bool
-- ^ True if length xs <= length ys
leLength xs ys = case compareLength xs ys of
LT -> True
EQ -> True
GT -> False
----------------------------
singleton :: a -> [a]
singleton x = [x]
isSingleton :: [a] -> Bool
isSingleton [_] = True
isSingleton _ = False
notNull :: [a] -> Bool
notNull [] = False
notNull _ = True
only :: [a] -> a
#ifdef DEBUG
only [a] = a
#else
only (a:_) = a
#endif
only _ = panic "Util: only"
-- Debugging/specialising versions of \tr{elem} and \tr{notElem}
isIn, isn'tIn :: Eq a => String -> a -> [a] -> Bool
# ifndef DEBUG
isIn _msg x ys = x `elem` ys
isn'tIn _msg x ys = x `notElem` ys
# else /* DEBUG */
isIn msg x ys
= elem100 0 x ys
where
elem100 :: Eq a => Int -> a -> [a] -> Bool
elem100 _ _ [] = False
elem100 i x (y:ys)
| i > 100 = trace ("Over-long elem in " ++ msg) (x `elem` (y:ys))
| otherwise = x == y || elem100 (i + 1) x ys
isn'tIn msg x ys
= notElem100 0 x ys
where
notElem100 :: Eq a => Int -> a -> [a] -> Bool
notElem100 _ _ [] = True
notElem100 i x (y:ys)
| i > 100 = trace ("Over-long notElem in " ++ msg) (x `notElem` (y:ys))
| otherwise = x /= y && notElem100 (i + 1) x ys
# endif /* DEBUG */
-- | Split a list into chunks of /n/ elements
chunkList :: Int -> [a] -> [[a]]
chunkList _ [] = []
chunkList n xs = as : chunkList n bs where (as,bs) = splitAt n xs
-- | Replace the last element of a list with another element.
changeLast :: [a] -> a -> [a]
changeLast [] _ = panic "changeLast"
changeLast [_] x = [x]
changeLast (x:xs) x' = x : changeLast xs x'
{-
************************************************************************
* *
\subsubsection{Sort utils}
* *
************************************************************************
-}
minWith :: Ord b => (a -> b) -> [a] -> a
minWith get_key xs = ASSERT( not (null xs) )
head (sortWith get_key xs)
nubSort :: Ord a => [a] -> [a]
nubSort = Set.toAscList . Set.fromList
{-
************************************************************************
* *
\subsection[Utils-transitive-closure]{Transitive closure}
* *
************************************************************************
This algorithm for transitive closure is straightforward, albeit quadratic.
-}
transitiveClosure :: (a -> [a]) -- Successor function
-> (a -> a -> Bool) -- Equality predicate
-> [a]
-> [a] -- The transitive closure
transitiveClosure succ eq xs
= go [] xs
where
go done [] = done
go done (x:xs) | x `is_in` done = go done xs
| otherwise = go (x:done) (succ x ++ xs)
_ `is_in` [] = False
x `is_in` (y:ys) | eq x y = True
| otherwise = x `is_in` ys
{-
************************************************************************
* *
\subsection[Utils-accum]{Accumulating}
* *
************************************************************************
A combination of foldl with zip. It works with equal length lists.
-}
foldl2 :: (acc -> a -> b -> acc) -> acc -> [a] -> [b] -> acc
foldl2 _ z [] [] = z
foldl2 k z (a:as) (b:bs) = foldl2 k (k z a b) as bs
foldl2 _ _ _ _ = panic "Util: foldl2"
all2 :: (a -> b -> Bool) -> [a] -> [b] -> Bool
-- True if the lists are the same length, and
-- all corresponding elements satisfy the predicate
all2 _ [] [] = True
all2 p (x:xs) (y:ys) = p x y && all2 p xs ys
all2 _ _ _ = False
-- Count the number of times a predicate is true
count :: (a -> Bool) -> [a] -> Int
count p = go 0
where go !n [] = n
go !n (x:xs) | p x = go (n+1) xs
| otherwise = go n xs
{-
@splitAt@, @take@, and @drop@ but with length of another
list giving the break-off point:
-}
takeList :: [b] -> [a] -> [a]
-- (takeList as bs) trims bs to the be same length
-- as as, unless as is longer in which case it's a no-op
takeList [] _ = []
takeList (_:xs) ls =
case ls of
[] -> []
(y:ys) -> y : takeList xs ys
dropList :: [b] -> [a] -> [a]
dropList [] xs = xs
dropList _ xs@[] = xs
dropList (_:xs) (_:ys) = dropList xs ys
splitAtList :: [b] -> [a] -> ([a], [a])
splitAtList [] xs = ([], xs)
splitAtList _ xs@[] = (xs, xs)
splitAtList (_:xs) (y:ys) = (y:ys', ys'')
where
(ys', ys'') = splitAtList xs ys
-- drop from the end of a list
dropTail :: Int -> [a] -> [a]
-- Specification: dropTail n = reverse . drop n . reverse
-- Better implemention due to Joachim Breitner
-- http://www.joachim-breitner.de/blog/archives/600-On-taking-the-last-n-elements-of-a-list.html
dropTail n xs
= go (drop n xs) xs
where
go (_:ys) (x:xs) = x : go ys xs
go _ _ = [] -- Stop when ys runs out
-- It'll always run out before xs does
-- dropWhile from the end of a list. This is similar to Data.List.dropWhileEnd,
-- but is lazy in the elements and strict in the spine. For reasonably short lists,
-- such as path names and typical lines of text, dropWhileEndLE is generally
-- faster than dropWhileEnd. Its advantage is magnified when the predicate is
-- expensive--using dropWhileEndLE isSpace to strip the space off a line of text
-- is generally much faster than using dropWhileEnd isSpace for that purpose.
-- Specification: dropWhileEndLE p = reverse . dropWhile p . reverse
-- Pay attention to the short-circuit (&&)! The order of its arguments is the only
-- difference between dropWhileEnd and dropWhileEndLE.
dropWhileEndLE :: (a -> Bool) -> [a] -> [a]
dropWhileEndLE p = foldr (\x r -> if null r && p x then [] else x:r) []
-- | @spanEnd p l == reverse (span p (reverse l))@. The first list
-- returns actually comes after the second list (when you look at the
-- input list).
spanEnd :: (a -> Bool) -> [a] -> ([a], [a])
spanEnd p l = go l [] [] l
where go yes _rev_yes rev_no [] = (yes, reverse rev_no)
go yes rev_yes rev_no (x:xs)
| p x = go yes (x : rev_yes) rev_no xs
| otherwise = go xs [] (x : rev_yes ++ rev_no) xs
snocView :: [a] -> Maybe ([a],a)
-- Split off the last element
snocView [] = Nothing
snocView xs = go [] xs
where
-- Invariant: second arg is non-empty
go acc [x] = Just (reverse acc, x)
go acc (x:xs) = go (x:acc) xs
go _ [] = panic "Util: snocView"
split :: Char -> String -> [String]
split c s = case rest of
[] -> [chunk]
_:rest -> chunk : split c rest
where (chunk, rest) = break (==c) s
-- | Convert a word to title case by capitalising the first letter
capitalise :: String -> String
capitalise [] = []
capitalise (c:cs) = toUpper c : cs
{-
************************************************************************
* *
\subsection[Utils-comparison]{Comparisons}
* *
************************************************************************
-}
isEqual :: Ordering -> Bool
-- Often used in (isEqual (a `compare` b))
isEqual GT = False
isEqual EQ = True
isEqual LT = False
thenCmp :: Ordering -> Ordering -> Ordering
{-# INLINE thenCmp #-}
thenCmp EQ ordering = ordering
thenCmp ordering _ = ordering
eqListBy :: (a->a->Bool) -> [a] -> [a] -> Bool
eqListBy _ [] [] = True
eqListBy eq (x:xs) (y:ys) = eq x y && eqListBy eq xs ys
eqListBy _ _ _ = False
eqMaybeBy :: (a ->a->Bool) -> Maybe a -> Maybe a -> Bool
eqMaybeBy _ Nothing Nothing = True
eqMaybeBy eq (Just x) (Just y) = eq x y
eqMaybeBy _ _ _ = False
cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
-- `cmpList' uses a user-specified comparer
cmpList _ [] [] = EQ
cmpList _ [] _ = LT
cmpList _ _ [] = GT
cmpList cmp (a:as) (b:bs)
= case cmp a b of { EQ -> cmpList cmp as bs; xxx -> xxx }
removeSpaces :: String -> String
removeSpaces = dropWhileEndLE isSpace . dropWhile isSpace
-- Boolean operators lifted to Applicative
(<&&>) :: Applicative f => f Bool -> f Bool -> f Bool
(<&&>) = liftA2 (&&)
infixr 3 <&&> -- same as (&&)
(<||>) :: Applicative f => f Bool -> f Bool -> f Bool
(<||>) = liftA2 (||)
infixr 2 <||> -- same as (||)
{-
************************************************************************
* *
\subsection{Edit distance}
* *
************************************************************************
-}
-- | Find the "restricted" Damerau-Levenshtein edit distance between two strings.
-- See: <http://en.wikipedia.org/wiki/Damerau-Levenshtein_distance>.
-- Based on the algorithm presented in "A Bit-Vector Algorithm for Computing
-- Levenshtein and Damerau Edit Distances" in PSC'02 (Heikki Hyyro).
-- See http://www.cs.uta.fi/~helmu/pubs/psc02.pdf and
-- http://www.cs.uta.fi/~helmu/pubs/PSCerr.html for an explanation
restrictedDamerauLevenshteinDistance :: String -> String -> Int
restrictedDamerauLevenshteinDistance str1 str2
= restrictedDamerauLevenshteinDistanceWithLengths m n str1 str2
where
m = length str1
n = length str2
restrictedDamerauLevenshteinDistanceWithLengths
:: Int -> Int -> String -> String -> Int
restrictedDamerauLevenshteinDistanceWithLengths m n str1 str2
| m <= n
= if n <= 32 -- n must be larger so this check is sufficient
then restrictedDamerauLevenshteinDistance' (undefined :: Word32) m n str1 str2
else restrictedDamerauLevenshteinDistance' (undefined :: Integer) m n str1 str2
| otherwise
= if m <= 32 -- m must be larger so this check is sufficient
then restrictedDamerauLevenshteinDistance' (undefined :: Word32) n m str2 str1
else restrictedDamerauLevenshteinDistance' (undefined :: Integer) n m str2 str1
restrictedDamerauLevenshteinDistance'
:: (Bits bv, Num bv) => bv -> Int -> Int -> String -> String -> Int
restrictedDamerauLevenshteinDistance' _bv_dummy m n str1 str2
| [] <- str1 = n
| otherwise = extractAnswer $
foldl' (restrictedDamerauLevenshteinDistanceWorker
(matchVectors str1) top_bit_mask vector_mask)
(0, 0, m_ones, 0, m) str2
where
m_ones@vector_mask = (2 ^ m) - 1
top_bit_mask = (1 `shiftL` (m - 1)) `asTypeOf` _bv_dummy
extractAnswer (_, _, _, _, distance) = distance
restrictedDamerauLevenshteinDistanceWorker
:: (Bits bv, Num bv) => IM.IntMap bv -> bv -> bv
-> (bv, bv, bv, bv, Int) -> Char -> (bv, bv, bv, bv, Int)
restrictedDamerauLevenshteinDistanceWorker str1_mvs top_bit_mask vector_mask
(pm, d0, vp, vn, distance) char2
= seq str1_mvs $ seq top_bit_mask $ seq vector_mask $
seq pm' $ seq d0' $ seq vp' $ seq vn' $
seq distance'' $ seq char2 $
(pm', d0', vp', vn', distance'')
where
pm' = IM.findWithDefault 0 (ord char2) str1_mvs
d0' = ((((sizedComplement vector_mask d0) .&. pm') `shiftL` 1) .&. pm)
.|. ((((pm' .&. vp) + vp) .&. vector_mask) `xor` vp) .|. pm' .|. vn
-- No need to mask the shiftL because of the restricted range of pm
hp' = vn .|. sizedComplement vector_mask (d0' .|. vp)
hn' = d0' .&. vp
hp'_shift = ((hp' `shiftL` 1) .|. 1) .&. vector_mask
hn'_shift = (hn' `shiftL` 1) .&. vector_mask
vp' = hn'_shift .|. sizedComplement vector_mask (d0' .|. hp'_shift)
vn' = d0' .&. hp'_shift
distance' = if hp' .&. top_bit_mask /= 0 then distance + 1 else distance
distance'' = if hn' .&. top_bit_mask /= 0 then distance' - 1 else distance'
sizedComplement :: Bits bv => bv -> bv -> bv
sizedComplement vector_mask vect = vector_mask `xor` vect
matchVectors :: (Bits bv, Num bv) => String -> IM.IntMap bv
matchVectors = snd . foldl' go (0 :: Int, IM.empty)
where
go (ix, im) char = let ix' = ix + 1
im' = IM.insertWith (.|.) (ord char) (2 ^ ix) im
in seq ix' $ seq im' $ (ix', im')
{-# SPECIALIZE INLINE restrictedDamerauLevenshteinDistance'
:: Word32 -> Int -> Int -> String -> String -> Int #-}
{-# SPECIALIZE INLINE restrictedDamerauLevenshteinDistance'
:: Integer -> Int -> Int -> String -> String -> Int #-}
{-# SPECIALIZE restrictedDamerauLevenshteinDistanceWorker
:: IM.IntMap Word32 -> Word32 -> Word32
-> (Word32, Word32, Word32, Word32, Int)
-> Char -> (Word32, Word32, Word32, Word32, Int) #-}
{-# SPECIALIZE restrictedDamerauLevenshteinDistanceWorker
:: IM.IntMap Integer -> Integer -> Integer
-> (Integer, Integer, Integer, Integer, Int)
-> Char -> (Integer, Integer, Integer, Integer, Int) #-}
{-# SPECIALIZE INLINE sizedComplement :: Word32 -> Word32 -> Word32 #-}
{-# SPECIALIZE INLINE sizedComplement :: Integer -> Integer -> Integer #-}
{-# SPECIALIZE matchVectors :: String -> IM.IntMap Word32 #-}
{-# SPECIALIZE matchVectors :: String -> IM.IntMap Integer #-}
fuzzyMatch :: String -> [String] -> [String]
fuzzyMatch key vals = fuzzyLookup key [(v,v) | v <- vals]
-- | Search for possible matches to the users input in the given list,
-- returning a small number of ranked results
fuzzyLookup :: String -> [(String,a)] -> [a]
fuzzyLookup user_entered possibilites
= map fst $ take mAX_RESULTS $ sortBy (comparing snd)
[ (poss_val, distance) | (poss_str, poss_val) <- possibilites
, let distance = restrictedDamerauLevenshteinDistance
poss_str user_entered
, distance <= fuzzy_threshold ]
where
-- Work out an approriate match threshold:
-- We report a candidate if its edit distance is <= the threshold,
-- The threshhold is set to about a quarter of the # of characters the user entered
-- Length Threshold
-- 1 0 -- Don't suggest *any* candidates
-- 2 1 -- for single-char identifiers
-- 3 1
-- 4 1
-- 5 1
-- 6 2
--
fuzzy_threshold = truncate $ fromIntegral (length user_entered + 2) / (4 :: Rational)
mAX_RESULTS = 3
{-
************************************************************************
* *
\subsection[Utils-pairs]{Pairs}
* *
************************************************************************
-}
unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
seqList :: [a] -> b -> b
seqList [] b = b
seqList (x:xs) b = x `seq` seqList xs b
-- Global variables:
global :: a -> IORef a
global a = unsafePerformIO (newIORef a)
consIORef :: IORef [a] -> a -> IO ()
consIORef var x = do
atomicModifyIORef' var (\xs -> (x:xs,()))
globalM :: IO a -> IORef a
globalM ma = unsafePerformIO (ma >>= newIORef)
-- Module names:
looksLikeModuleName :: String -> Bool
looksLikeModuleName [] = False
looksLikeModuleName (c:cs) = isUpper c && go cs
where go [] = True
go ('.':cs) = looksLikeModuleName cs
go (c:cs) = (isAlphaNum c || c == '_' || c == '\'') && go cs
-- Similar to 'parse' for Distribution.Package.PackageName,
-- but we don't want to depend on Cabal.
looksLikePackageName :: String -> Bool
looksLikePackageName = all (all isAlphaNum <&&> not . (all isDigit)) . split '-'
{-
Akin to @Prelude.words@, but acts like the Bourne shell, treating
quoted strings as Haskell Strings, and also parses Haskell [String]
syntax.
-}
getCmd :: String -> Either String -- Error
(String, String) -- (Cmd, Rest)
getCmd s = case break isSpace $ dropWhile isSpace s of
([], _) -> Left ("Couldn't find command in " ++ show s)
res -> Right res
toCmdArgs :: String -> Either String -- Error
(String, [String]) -- (Cmd, Args)
toCmdArgs s = case getCmd s of
Left err -> Left err
Right (cmd, s') -> case toArgs s' of
Left err -> Left err
Right args -> Right (cmd, args)
toArgs :: String -> Either String -- Error
[String] -- Args
toArgs str
= case dropWhile isSpace str of
s@('[':_) -> case reads s of
[(args, spaces)]
| all isSpace spaces ->
Right args
_ ->
Left ("Couldn't read " ++ show str ++ " as [String]")
s -> toArgs' s
where
toArgs' :: String -> Either String [String]
-- Remove outer quotes:
-- > toArgs' "\"foo\" \"bar baz\""
-- Right ["foo", "bar baz"]
--
-- Keep inner quotes:
-- > toArgs' "-DFOO=\"bar baz\""
-- Right ["-DFOO=\"bar baz\""]
toArgs' s = case dropWhile isSpace s of
[] -> Right []
('"' : _) -> do
-- readAsString removes outer quotes
(arg, rest) <- readAsString s
(arg:) `fmap` toArgs' rest
s' -> case break (isSpace <||> (== '"')) s' of
(argPart1, s''@('"':_)) -> do
(argPart2, rest) <- readAsString s''
-- show argPart2 to keep inner quotes
((argPart1 ++ show argPart2):) `fmap` toArgs' rest
(arg, s'') -> (arg:) `fmap` toArgs' s''
readAsString :: String -> Either String (String, String)
readAsString s = case reads s of
[(arg, rest)]
-- rest must either be [] or start with a space
| all isSpace (take 1 rest) ->
Right (arg, rest)
_ ->
Left ("Couldn't read " ++ show s ++ " as String")
-----------------------------------------------------------------------------
-- Integers
-- This algorithm for determining the $\log_2$ of exact powers of 2 comes
-- from GCC. It requires bit manipulation primitives, and we use GHC
-- extensions. Tough.
exactLog2 :: Integer -> Maybe Integer
exactLog2 x
= if (x <= 0 || x >= 2147483648) then
Nothing
else
if (x .&. (-x)) /= x then
Nothing
else
Just (pow2 x)
where
pow2 x | x == 1 = 0
| otherwise = 1 + pow2 (x `shiftR` 1)
{-
-- -----------------------------------------------------------------------------
-- Floats
-}
readRational__ :: ReadS Rational -- NB: doesn't handle leading "-"
readRational__ r = do
(n,d,s) <- readFix r
(k,t) <- readExp s
return ((n%1)*10^^(k-d), t)
where
readFix r = do
(ds,s) <- lexDecDigits r
(ds',t) <- lexDotDigits s
return (read (ds++ds'), length ds', t)
readExp (e:s) | e `elem` "eE" = readExp' s
readExp s = return (0,s)
readExp' ('+':s) = readDec s
readExp' ('-':s) = do (k,t) <- readDec s
return (-k,t)
readExp' s = readDec s
readDec s = do
(ds,r) <- nonnull isDigit s
return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
r)
lexDecDigits = nonnull isDigit
lexDotDigits ('.':s) = return (span isDigit s)
lexDotDigits s = return ("",s)
nonnull p s = do (cs@(_:_),t) <- return (span p s)
return (cs,t)
readRational :: String -> Rational -- NB: *does* handle a leading "-"
readRational top_s
= case top_s of
'-' : xs -> - (read_me xs)
xs -> read_me xs
where
read_me s
= case (do { (x,"") <- readRational__ s ; return x }) of
[x] -> x
[] -> error ("readRational: no parse:" ++ top_s)
_ -> error ("readRational: ambiguous parse:" ++ top_s)
-----------------------------------------------------------------------------
-- read helpers
maybeRead :: Read a => String -> Maybe a
maybeRead str = case reads str of
[(x, "")] -> Just x
_ -> Nothing
maybeReadFuzzy :: Read a => String -> Maybe a
maybeReadFuzzy str = case reads str of
[(x, s)]
| all isSpace s ->
Just x
_ ->
Nothing
-----------------------------------------------------------------------------
-- Verify that the 'dirname' portion of a FilePath exists.
--
doesDirNameExist :: FilePath -> IO Bool
doesDirNameExist fpath = doesDirectoryExist (takeDirectory fpath)
-----------------------------------------------------------------------------
-- Backwards compatibility definition of getModificationTime
getModificationUTCTime :: FilePath -> IO UTCTime
getModificationUTCTime = getModificationTime
-- --------------------------------------------------------------
-- check existence & modification time at the same time
modificationTimeIfExists :: FilePath -> IO (Maybe UTCTime)
modificationTimeIfExists f = do
(do t <- getModificationUTCTime f; return (Just t))
`catchIO` \e -> if isDoesNotExistError e
then return Nothing
else ioError e
-- --------------------------------------------------------------
-- Change the character encoding of the given Handle to transliterate
-- on unsupported characters instead of throwing an exception
hSetTranslit :: Handle -> IO ()
hSetTranslit h = do
menc <- hGetEncoding h
case fmap textEncodingName menc of
Just name | '/' `notElem` name -> do
enc' <- mkTextEncoding $ name ++ "//TRANSLIT"
hSetEncoding h enc'
_ -> return ()
-- split a string at the last character where 'pred' is True,
-- returning a pair of strings. The first component holds the string
-- up (but not including) the last character for which 'pred' returned
-- True, the second whatever comes after (but also not including the
-- last character).
--
-- If 'pred' returns False for all characters in the string, the original
-- string is returned in the first component (and the second one is just
-- empty).
splitLongestPrefix :: String -> (Char -> Bool) -> (String,String)
splitLongestPrefix str pred
| null r_pre = (str, [])
| otherwise = (reverse (tail r_pre), reverse r_suf)
-- 'tail' drops the char satisfying 'pred'
where (r_suf, r_pre) = break pred (reverse str)
escapeSpaces :: String -> String
escapeSpaces = foldr (\c s -> if isSpace c then '\\':c:s else c:s) ""
type Suffix = String
--------------------------------------------------------------
-- * Search path
--------------------------------------------------------------
data Direction = Forwards | Backwards
reslash :: Direction -> FilePath -> FilePath
reslash d = f
where f ('/' : xs) = slash : f xs
f ('\\' : xs) = slash : f xs
f (x : xs) = x : f xs
f "" = ""
slash = case d of
Forwards -> '/'
Backwards -> '\\'
makeRelativeTo :: FilePath -> FilePath -> FilePath
this `makeRelativeTo` that = directory </> thisFilename
where (thisDirectory, thisFilename) = splitFileName this
thatDirectory = dropFileName that
directory = joinPath $ f (splitPath thisDirectory)
(splitPath thatDirectory)
f (x : xs) (y : ys)
| x == y = f xs ys
f xs ys = replicate (length ys) ".." ++ xs
{-
************************************************************************
* *
\subsection[Utils-Data]{Utils for defining Data instances}
* *
************************************************************************
These functions helps us to define Data instances for abstract types.
-}
abstractConstr :: String -> Constr
abstractConstr n = mkConstr (abstractDataType n) ("{abstract:"++n++"}") [] Prefix
abstractDataType :: String -> DataType
abstractDataType n = mkDataType n [abstractConstr n]
{-
************************************************************************
* *
\subsection[Utils-C]{Utils for printing C code}
* *
************************************************************************
-}
charToC :: Word8 -> String
charToC w =
case chr (fromIntegral w) of
'\"' -> "\\\""
'\'' -> "\\\'"
'\\' -> "\\\\"
c | c >= ' ' && c <= '~' -> [c]
| otherwise -> ['\\',
chr (ord '0' + ord c `div` 64),
chr (ord '0' + ord c `div` 8 `mod` 8),
chr (ord '0' + ord c `mod` 8)]
{-
************************************************************************
* *
\subsection[Utils-Hashing]{Utils for hashing}
* *
************************************************************************
-}
-- | A sample hash function for Strings. We keep multiplying by the
-- golden ratio and adding. The implementation is:
--
-- > hashString = foldl' f golden
-- > where f m c = fromIntegral (ord c) * magic + hashInt32 m
-- > magic = 0xdeadbeef
--
-- Where hashInt32 works just as hashInt shown above.
--
-- Knuth argues that repeated multiplication by the golden ratio
-- will minimize gaps in the hash space, and thus it's a good choice
-- for combining together multiple keys to form one.
--
-- Here we know that individual characters c are often small, and this
-- produces frequent collisions if we use ord c alone. A
-- particular problem are the shorter low ASCII and ISO-8859-1
-- character strings. We pre-multiply by a magic twiddle factor to
-- obtain a good distribution. In fact, given the following test:
--
-- > testp :: Int32 -> Int
-- > testp k = (n - ) . length . group . sort . map hs . take n $ ls
-- > where ls = [] : [c : l | l <- ls, c <- ['\0'..'\xff']]
-- > hs = foldl' f golden
-- > f m c = fromIntegral (ord c) * k + hashInt32 m
-- > n = 100000
--
-- We discover that testp magic = 0.
hashString :: String -> Int32
hashString = foldl' f golden
where f m c = fromIntegral (ord c) * magic + hashInt32 m
magic = fromIntegral (0xdeadbeef :: Word32)
golden :: Int32
golden = 1013904242 -- = round ((sqrt 5 - 1) * 2^32) :: Int32
-- was -1640531527 = round ((sqrt 5 - 1) * 2^31) :: Int32
-- but that has bad mulHi properties (even adding 2^32 to get its inverse)
-- Whereas the above works well and contains no hash duplications for
-- [-32767..65536]
-- | A sample (and useful) hash function for Int32,
-- implemented by extracting the uppermost 32 bits of the 64-bit
-- result of multiplying by a 33-bit constant. The constant is from
-- Knuth, derived from the golden ratio:
--
-- > golden = round ((sqrt 5 - 1) * 2^32)
--
-- We get good key uniqueness on small inputs
-- (a problem with previous versions):
-- (length $ group $ sort $ map hashInt32 [-32767..65536]) == 65536 + 32768
--
hashInt32 :: Int32 -> Int32
hashInt32 x = mulHi x golden + x
-- hi 32 bits of a x-bit * 32 bit -> 64-bit multiply
mulHi :: Int32 -> Int32 -> Int32
mulHi a b = fromIntegral (r `shiftR` 32)
where r :: Int64
r = fromIntegral a * fromIntegral b
-- | A compatibility wrapper for the @GHC.Stack.HasCallStack@ constraint.
#if __GLASGOW_HASKELL__ >= 800
type HasCallStack = GHC.Stack.HasCallStack
#elif MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
type HasCallStack = (?callStack :: GHC.Stack.CallStack)
-- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1
#else
type HasCallStack = (() :: Constraint)
#endif
-- | A call stack constraint, but only when 'isDebugOn'.
#if DEBUG
type HasDebugCallStack = HasCallStack
#else
type HasDebugCallStack = (() :: Constraint)
#endif
-- | Pretty-print the current callstack
#if __GLASGOW_HASKELL__ >= 800
prettyCurrentCallStack :: HasCallStack => String
prettyCurrentCallStack = GHC.Stack.prettyCallStack GHC.Stack.callStack
#elif MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
prettyCurrentCallStack :: (?callStack :: GHC.Stack.CallStack) => String
prettyCurrentCallStack = GHC.Stack.showCallStack ?callStack
#else
prettyCurrentCallStack :: HasCallStack => String
prettyCurrentCallStack = "Call stack unavailable"
#endif
| mettekou/ghc | compiler/utils/Util.hs | bsd-3-clause | 44,657 | 5 | 34 | 13,132 | 11,340 | 6,209 | 5,131 | 655 | 7 |
module CallByNeed.Evaluator
( valueOf
, run
, eval
, evalProgram
) where
import CallByNeed.Data
import CallByNeed.Parser
import Control.Applicative ((<|>))
import Control.Monad.Trans.State.Lazy (evalStateT)
type EvaluateResult = StatedTry ExpressedValue
liftMaybe :: String -> Maybe a -> StatedTry a
liftMaybe _ (Just x) = return x
liftMaybe y Nothing = throwError y
run :: String -> Try ExpressedValue
run input = do
prog <- parseProgram input
evalStateT (evalProgram prog) initStore
evalProgram :: Program -> EvaluateResult
evalProgram (Prog expr) = eval expr
eval :: Expression -> EvaluateResult
eval = flip valueOf empty
valueOf :: Expression -> Environment -> EvaluateResult
valueOf (ConstExpr x) _ = evalConstExpr x
valueOf (VarExpr var) env = evalVarExpr var env
valueOf (LetRecExpr procs recBody) env = evalLetRecExpr procs recBody env
valueOf (BinOpExpr op expr1 expr2) env = evalBinOpExpr op expr1 expr2 env
valueOf (UnaryOpExpr op expr) env = evalUnaryOpExpr op expr env
valueOf (CondExpr pairs) env = evalCondExpr pairs env
valueOf (LetExpr bindings body) env = evalLetExpr bindings body env
valueOf (ProcExpr params body) env = evalProcExpr params body env
valueOf (CallExpr rator rands) env = evalCallExpr rator rands env
valueOf (BeginExpr exprs) env = evalBeginExpr exprs env
valueOf (AssignExpr name expr) env = evalAssignExpr name expr env
getRef :: Environment -> String -> StatedTry Ref
getRef env name = do
deno <- getDeno env name
let (DenoRef ref) = deno
return ref
getDeno :: Environment -> String -> StatedTry DenotedValue
getDeno env name = liftMaybe
("Not in scope: " `mappend` show name) (apply env name)
evalAssignExpr :: String -> Expression -> Environment -> EvaluateResult
evalAssignExpr name expr env = do
val <- valueOf expr env
ref <- getRef env name
setRef ref val
return $ ExprBool False
evalBeginExpr :: [Expression] -> Environment -> EvaluateResult
evalBeginExpr [] env = throwError
"begin expression should at least have one sub expression"
evalBeginExpr exprs env = foldl func (return $ ExprBool False) exprs
where
func acc ele = do
acc
valueOf ele env
evalExpressionList :: [Expression] -> Environment -> StatedTry [ExpressedValue]
evalExpressionList lst env = reverse <$> evaledList
where
func acc expr = do
lst <- acc
ele <- valueOf expr env
return $ ele:lst
evaledList = foldl func (return []) lst
evalConstExpr :: ExpressedValue -> EvaluateResult
evalConstExpr = return
evalVarExpr :: String -> Environment -> EvaluateResult
evalVarExpr name env = do
ref <- getRef env name
thunkable <- deRef ref
case thunkable of
ExprThunk (Thunk expr savedEnv) -> evalAndSet expr savedEnv ref
notThunk -> return notThunk
where
evalAndSet expr savedEnv ref = do
val <- valueOf expr savedEnv
setRef ref val
return val
evalLetRecExpr :: [(String, [String], Expression)] -> Expression -> Environment
-> EvaluateResult
evalLetRecExpr procsSubUnits recBody env = do
newEnv <- extendRecMany procsSubUnits env
valueOf recBody newEnv
binBoolOpMap :: [(BinOp, Bool -> Bool -> Bool)]
binBoolOpMap = []
binNumToNumOpMap :: [(BinOp, Integer -> Integer -> Integer)]
binNumToNumOpMap = [(Add, (+)), (Sub, (-)), (Mul, (*)), (Div, div)]
binNumToBoolOpMap :: [(BinOp, Integer -> Integer -> Bool)]
binNumToBoolOpMap = [(Gt, (>)), (Le, (<)), (Eq, (==))]
unaryBoolOpMap :: [(UnaryOp, Bool -> Bool)]
unaryBoolOpMap = []
unaryNumToNumOpMap :: [(UnaryOp, Integer -> Integer)]
unaryNumToNumOpMap = [(Minus, negate)]
unaryNumToBoolOpMap :: [(UnaryOp, Integer -> Bool)]
unaryNumToBoolOpMap = [(IsZero, (0 ==))]
unpackNum :: String -> ExpressedValue -> StatedTry Integer
unpackNum _ (ExprNum n) = return n
unpackNum caller notNum = throwError $ concat [
caller, ": Unpacking a not number value: ", show notNum ]
unpackBool :: String -> ExpressedValue -> StatedTry Bool
unpackBool _ (ExprBool b) = return b
unpackBool caller notBool = throwError $ concat [
caller, ": Unpacking a not boolean value: ", show notBool ]
tryFind :: Eq a => String -> a -> [(a, b)] -> StatedTry b
tryFind err x pairs = liftMaybe err (lookup x pairs)
tryFindOp :: (Eq a, Show a) => a -> [(a, b)] -> StatedTry b
tryFindOp op = tryFind ("Unknown operator: " `mappend` show op) op
evalBinOpExpr :: BinOp -> Expression -> Expression -> Environment
-> EvaluateResult
evalBinOpExpr op expr1 expr2 env = do
v1 <- valueOf expr1 env
v2 <- valueOf expr2 env
numToNum v1 v2 <|> numToBool v1 v2 <|> boolToBool v1 v2
where
findOpFrom = tryFindOp op
unpackN = unpackNum $ "binary operation " `mappend` show op
unpackB = unpackBool $ "binary operation " `mappend` show op
numToNum :: ExpressedValue -> ExpressedValue -> EvaluateResult
numToNum val1 val2 = do
func <- findOpFrom binNumToNumOpMap
n1 <- unpackN val1
n2 <- unpackN val2
return . ExprNum $ func n1 n2
numToBool :: ExpressedValue -> ExpressedValue -> EvaluateResult
numToBool val1 val2 = do
func <- findOpFrom binNumToBoolOpMap
n1 <- unpackN val1
n2 <- unpackN val2
return . ExprBool $ func n1 n2
boolToBool :: ExpressedValue -> ExpressedValue -> EvaluateResult
boolToBool val1 val2 = do
func <- findOpFrom binBoolOpMap
b1 <- unpackB val1
b2 <- unpackB val2
return . ExprBool $ func b1 b2
evalUnaryOpExpr :: UnaryOp -> Expression -> Environment
-> EvaluateResult
evalUnaryOpExpr op expr env = do
v <- valueOf expr env
numToNum v <|> numToBool v <|> boolToBool v
where
findOpFrom = tryFindOp op
unpackN = unpackNum $ "unary operation " `mappend` show op
unpackB = unpackBool $ "unary operation " `mappend` show op
numToNum :: ExpressedValue -> EvaluateResult
numToNum val = do
func <- findOpFrom unaryNumToNumOpMap
n <- unpackN val
return . ExprNum $ func n
numToBool :: ExpressedValue -> EvaluateResult
numToBool val = do
func <- findOpFrom unaryNumToBoolOpMap
n <- unpackN val
return . ExprBool $ func n
boolToBool :: ExpressedValue -> EvaluateResult
boolToBool val = do
func <- findOpFrom unaryBoolOpMap
b <- unpackB val
return . ExprBool $ func b
evalCondExpr :: [(Expression, Expression)] -> Environment -> EvaluateResult
evalCondExpr [] _ = throwError "No predicate is true"
evalCondExpr ((e1, e2):pairs) env = do
val <- valueOf e1 env
case val of
ExprBool True -> valueOf e2 env
ExprBool False -> evalCondExpr pairs env
_ -> throwError $
"Predicate expression should be boolean, but got: "
`mappend` show val
evalLetExpr :: [(String, Expression)] -> Expression -> Environment
-> EvaluateResult
evalLetExpr bindings body env = evalLetExpr' bindings body env
where
recLetExpr :: String -> StatedTry Ref
-> [(String, Expression)] -> Expression -> Environment
-> EvaluateResult
recLetExpr name tryRef xs body newEnv = do
ref <- tryRef
evalLetExpr' xs body (extend name (DenoRef ref) newEnv)
evalLetExpr' :: [(String, Expression)] -> Expression -> Environment
-> EvaluateResult
evalLetExpr' [] body newEnv = valueOf body newEnv
evalLetExpr' ((name, VarExpr var):xs) body newEnv =
recLetExpr name (getRef env var) xs body newEnv
evalLetExpr' ((name, ConstExpr val):xs) body newEnv =
recLetExpr name (newRef val) xs body newEnv
evalLetExpr' ((name, ProcExpr params procBody):xs) body newEnv =
recLetExpr name
(newRef (ExprProc $ Procedure params procBody env))
xs body newEnv
evalLetExpr' ((name, expr):xs) body newEnv =
recLetExpr name (newRef (ExprThunk (Thunk expr env))) xs body newEnv
evalProcExpr :: [String] -> Expression -> Environment -> EvaluateResult
evalProcExpr params body env = return . ExprProc $ Procedure params body env
evalCallExpr :: Expression -> [Expression] -> Environment -> EvaluateResult
evalCallExpr ratorExpr randExprs env = do
rator <- valueOf ratorExpr env
proc <- unpackProc rator
refs <- valueOfOperands randExprs env
applyProcedure proc refs
where
-- | Check if the operand expression is variable expression, if it is,
-- refer to the same location, otherwise, build a new thunk and create
-- a new reference to this thunk.
valueOfOperands :: [Expression] -> Environment -> StatedTry [Ref]
valueOfOperands [] _ = return []
valueOfOperands (VarExpr name : exprs) env =
recOpVal exprs env (getRef env name)
valueOfOperands (ConstExpr val : exprs) env =
recOpVal exprs env (newRef val)
valueOfOperands (ProcExpr params body : exprs) env =
recOpVal exprs env (newRef . ExprProc $ Procedure params body env)
valueOfOperands (expr:exprs) env =
recOpVal exprs env (newRef (ExprThunk (Thunk expr env)))
recOpVal :: [Expression] -> Environment -> StatedTry Ref -> StatedTry [Ref]
recOpVal exprs env tryRef = (:) <$> tryRef <*> valueOfOperands exprs env
unpackProc :: ExpressedValue -> StatedTry Procedure
unpackProc (ExprProc proc) = return proc
unpackProc notProc = throwError $
"Operator of call expression should be procedure, but got: "
`mappend` show notProc
safeZip :: [a] -> [b] -> StatedTry [(a, b)]
safeZip [] [] = return []
safeZip (_:_) [] = throwError "Not enough arguments!"
safeZip [] (_:_) = throwError "Too many arguments!"
safeZip (x:xs) (y:ys) = ((x, y):) <$> safeZip xs ys
applyProcedure :: Procedure -> [Ref] -> EvaluateResult
applyProcedure (Procedure params body savedEnv) rands = do
pairs <- safeZip params (fmap DenoRef rands)
valueOf body (extendMany pairs savedEnv)
| li-zhirui/EoplLangs | src/CallByNeed/Evaluator.hs | bsd-3-clause | 9,949 | 0 | 13 | 2,298 | 3,297 | 1,663 | 1,634 | 219 | 9 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeApplications #-}
module Data.Diverse.WhichBench where
import qualified Criterion.Main as C
import Data.Diverse
bgroup = C.bgroup "Which"
[ C.bench "read" $ C.whnf (read @(Which '[Int, Bool])) "pickN @0 Proxy 5"
]
| louispan/data-diverse | bench/Data/Diverse/WhichBench.hs | bsd-3-clause | 268 | 0 | 15 | 47 | 75 | 43 | 32 | 7 | 1 |
{-# LANGUAGE
TemplateHaskell,
StandaloneDeriving
#-}
-----------------------------------------------------------------------------
-- |
-- Module : HGene.JSCompiler.JSBase
-- License : http://www.gnu.org/copyleft/gpl.html
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : probable
--
-- Some tools for writing html in a pretty format in haskell.
module HGene.JSCompiler.JSBase ( alert ) where
alert :: a -> IO ()
alert = undefined
| mmirman/haskogeneous | src/HGene/JSCompiler/JSBase.hs | bsd-3-clause | 489 | 0 | 7 | 78 | 42 | 29 | 13 | 6 | 1 |
--------------------------------------------------------------------
-- |
-- Module: HTrade.Backend.Backend
--
-- Main entry point for the backend service.
-- The backend service loads a set of configurations (initially from a default directory)
-- and continues to accept commands from the stdin.
module Main where
import Control.Applicative ((<$>))
import Data.List (intercalate)
import Data.Monoid ((<>))
import Control.Monad (liftM)
import Control.Monad.Trans (lift, liftIO)
import System.IO (hFlush, stdout)
import qualified HTrade.Backend.Configuration as C
import qualified HTrade.Backend.ProxyLayer as PL
import qualified HTrade.Backend.Types as PL
import HTrade.Shared.Utils (backendPort)
-- | Read, parse, and interpret a command from the given current directory.
runShell
:: String
-> C.MConfigT (PL.MProxyT IO) ()
runShell cwd = liftIO (putStr "> " >> hFlush stdout >> getLine) >>= parse . words
where
parse ("load":dir:[]) =
C.loadConfigurations dir >>= printAndRepeat dir
parse ("reload":[]) =
C.loadConfigurations cwd >>= printAndRepeat cwd
parse ("stats":[]) = do
loaded <- map PL._marketName <$> C.getLoadedMarkets
nodes <- lift PL.connectedNodes
ready <- liftM (\r -> if r then "ready" else "not ready") (lift PL.ready)
liftIO . putStrLn $
"Loaded markets: " <> intercalate ", " (map show loaded) <> "\n" <>
"Active proxy nodes: " <> show nodes <> " (layer is " <> ready <> ")"
runShell cwd
parse ("quit":[]) = C.terminateLoadedMarkets
parse _ = liftIO (putStrLn $ unlines helpMsg) >> runShell cwd
helpMsg = ["Commands:", "load <dir>", "reload", "stats", "quit"]
printAndRepeat dir msg = liftIO (print msg) >> runShell dir
-- | Launch the backend service and load initial configurations
-- from the default directory.
-- Will only terminate after a quit command has been given.
main :: IO ()
main = PL.withLayer backendPort $ C.withConfiguration $ do
confs <- C.loadConfigurations defaultDir
liftIO $ putStrLn $ "Initialized with configurations: " ++ show confs
runShell defaultDir
liftIO $ putStrLn "Terminating"
where
defaultDir = "data/configurations"
| davnils/distr-btc | src/HTrade/Backend/Backend.hs | bsd-3-clause | 2,371 | 1 | 18 | 589 | 571 | 303 | 268 | 38 | 6 |
{-# OPTIONS -fglasgow-exts #-}
module API where
import Data.Dynamic
data Unsafe = Unsafe {
field :: String
}
deriving (Typeable, Show)
unsafe :: Unsafe
unsafe = Unsafe { field = "default value" }
| abuiles/turbinado-blog | tmp/dependencies/hs-plugins-1.3.1/testsuite/makewith/unsafeio/api/API.hs | bsd-3-clause | 229 | 0 | 8 | 66 | 54 | 33 | 21 | 8 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE UnboxedTuples #-}
module Snap.Internal.Http.Server.Parser
( IRequest(..)
, HttpParseException(..)
, readChunkedTransferEncoding
, writeChunkedTransferEncoding
, parseRequest
, parseFromStream
, parseCookie
, parseUrlEncoded
, getStdContentLength
, getStdHost
, getStdTransferEncoding
, getStdCookie
, getStdContentType
, getStdConnection
) where
------------------------------------------------------------------------------
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Control.Exception (Exception, throwIO)
import Control.Monad (void, when)
import Control.Monad.IO.Class (MonadIO (liftIO))
import Data.Attoparsec.ByteString.Char8 (Parser, hexadecimal, takeTill)
import qualified Data.ByteString.Char8 as S
import Data.ByteString.Internal (ByteString (..), c2w, memchr, w2c)
#if MIN_VERSION_bytestring(0, 10, 6)
import Data.ByteString.Internal (accursedUnutterablePerformIO)
#else
import Data.ByteString.Internal (inlinePerformIO)
#endif
import qualified Data.ByteString.Unsafe as S
import Data.List (sort)
import Data.Typeable (Typeable)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Ptr (minusPtr, nullPtr, plusPtr)
import Prelude hiding (take)
------------------------------------------------------------------------------
import Blaze.ByteString.Builder.HTTP (chunkedTransferEncoding, chunkedTransferTerminator)
import Data.ByteString.Builder (Builder)
import System.IO.Streams (InputStream, OutputStream, Generator)
import qualified System.IO.Streams as Streams
import System.IO.Streams.Attoparsec (parseFromStream)
------------------------------------------------------------------------------
import Snap.Internal.Http.Types (Method (..))
import Snap.Internal.Parsing (crlf, parseCookie, parseUrlEncoded, unsafeFromNat)
import Snap.Types.Headers (Headers)
import qualified Snap.Types.Headers as H
------------------------------------------------------------------------------
newtype StandardHeaders = StandardHeaders (V.Vector (Maybe ByteString))
type MStandardHeaders = MV.IOVector (Maybe ByteString)
------------------------------------------------------------------------------
contentLengthTag, hostTag, transferEncodingTag, cookieTag, contentTypeTag,
connectionTag, nStandardHeaders :: Int
contentLengthTag = 0
hostTag = 1
transferEncodingTag = 2
cookieTag = 3
contentTypeTag = 4
connectionTag = 5
nStandardHeaders = 6
------------------------------------------------------------------------------
findStdHeaderIndex :: ByteString -> Int
findStdHeaderIndex "content-length" = contentLengthTag
findStdHeaderIndex "host" = hostTag
findStdHeaderIndex "transfer-encoding" = transferEncodingTag
findStdHeaderIndex "cookie" = cookieTag
findStdHeaderIndex "content-type" = contentTypeTag
findStdHeaderIndex "connection" = connectionTag
findStdHeaderIndex _ = -1
------------------------------------------------------------------------------
getStdContentLength, getStdHost, getStdTransferEncoding, getStdCookie,
getStdConnection, getStdContentType :: StandardHeaders -> Maybe ByteString
getStdContentLength (StandardHeaders v) = V.unsafeIndex v contentLengthTag
getStdHost (StandardHeaders v) = V.unsafeIndex v hostTag
getStdTransferEncoding (StandardHeaders v) = V.unsafeIndex v transferEncodingTag
getStdCookie (StandardHeaders v) = V.unsafeIndex v cookieTag
getStdContentType (StandardHeaders v) = V.unsafeIndex v contentTypeTag
getStdConnection (StandardHeaders v) = V.unsafeIndex v connectionTag
------------------------------------------------------------------------------
newMStandardHeaders :: IO MStandardHeaders
newMStandardHeaders = MV.replicate nStandardHeaders Nothing
------------------------------------------------------------------------------
-- | an internal version of the headers part of an HTTP request
data IRequest = IRequest
{ iMethod :: !Method
, iRequestUri :: !ByteString
, iHttpVersion :: (Int, Int)
, iRequestHeaders :: Headers
, iStdHeaders :: StandardHeaders
}
------------------------------------------------------------------------------
instance Eq IRequest where
a == b =
and [ iMethod a == iMethod b
, iRequestUri a == iRequestUri b
, iHttpVersion a == iHttpVersion b
, sort (H.toList (iRequestHeaders a))
== sort (H.toList (iRequestHeaders b))
]
------------------------------------------------------------------------------
instance Show IRequest where
show (IRequest m u (major, minor) hdrs _) =
concat [ show m
, " "
, show u
, " "
, show major
, "."
, show minor
, " "
, show hdrs
]
------------------------------------------------------------------------------
data HttpParseException = HttpParseException String deriving (Typeable, Show)
instance Exception HttpParseException
------------------------------------------------------------------------------
{-# INLINE parseRequest #-}
parseRequest :: InputStream ByteString -> IO IRequest
parseRequest input = do
line <- pLine input
let (!mStr, !s) = bSp line
let (!uri, !vStr) = bSp s
let method = methodFromString mStr
let !version = pVer vStr
let (host, uri') = getHost uri
let uri'' = if S.null uri' then "/" else uri'
stdHdrs <- newMStandardHeaders
MV.unsafeWrite stdHdrs hostTag host
hdrs <- pHeaders stdHdrs input
outStd <- StandardHeaders <$> V.unsafeFreeze stdHdrs
return $! IRequest method uri'' version hdrs outStd
where
getHost s | "http://" `S.isPrefixOf` s
= let s' = S.unsafeDrop 7 s
(!host, !uri) = breakCh '/' s'
in (Just $! host, uri)
| "https://" `S.isPrefixOf` s
= let s' = S.unsafeDrop 8 s
(!host, !uri) = breakCh '/' s'
in (Just $! host, uri)
| otherwise = (Nothing, s)
pVer s = if "HTTP/" `S.isPrefixOf` s
then pVers (S.unsafeDrop 5 s)
else (1, 0)
bSp = splitCh ' '
pVers s = (c, d)
where
(!a, !b) = splitCh '.' s
!c = unsafeFromNat a
!d = unsafeFromNat b
------------------------------------------------------------------------------
pLine :: InputStream ByteString -> IO ByteString
pLine input = go []
where
throwNoCRLF =
throwIO $
HttpParseException "parse error: expected line ending in crlf"
throwBadCRLF =
throwIO $
HttpParseException "parse error: got cr without subsequent lf"
go !l = do
!mb <- Streams.read input
!s <- maybe throwNoCRLF return mb
let !i = elemIndex '\r' s
if i < 0
then noCRLF l s
else case () of
!_ | i+1 >= S.length s -> lastIsCR l s i
| S.unsafeIndex s (i+1) == 10 -> foundCRLF l s i
| otherwise -> throwBadCRLF
foundCRLF l s !i1 = do
let !i2 = i1 + 2
let !a = S.unsafeTake i1 s
when (i2 < S.length s) $ do
let !b = S.unsafeDrop i2 s
Streams.unRead b input
-- Optimize for the common case: dl is almost always "id"
let !out = if null l then a else S.concat (reverse (a:l))
return out
noCRLF l s = go (s:l)
lastIsCR l s !idx = do
!t <- Streams.read input >>= maybe throwNoCRLF return
if S.null t
then lastIsCR l s idx
else do
let !c = S.unsafeHead t
if c /= 10
then throwBadCRLF
else do
let !a = S.unsafeTake idx s
let !b = S.unsafeDrop 1 t
when (not $ S.null b) $ Streams.unRead b input
let !out = if null l then a else S.concat (reverse (a:l))
return out
------------------------------------------------------------------------------
splitCh :: Char -> ByteString -> (ByteString, ByteString)
splitCh !c !s = if idx < 0
then (s, S.empty)
else let !a = S.unsafeTake idx s
!b = S.unsafeDrop (idx + 1) s
in (a, b)
where
!idx = elemIndex c s
{-# INLINE splitCh #-}
------------------------------------------------------------------------------
breakCh :: Char -> ByteString -> (ByteString, ByteString)
breakCh !c !s = if idx < 0
then (s, S.empty)
else let !a = S.unsafeTake idx s
!b = S.unsafeDrop idx s
in (a, b)
where
!idx = elemIndex c s
{-# INLINE breakCh #-}
------------------------------------------------------------------------------
splitHeader :: ByteString -> (ByteString, ByteString)
splitHeader !s = if idx < 0
then (s, S.empty)
else let !a = S.unsafeTake idx s
in (a, skipSp (idx + 1))
where
!idx = elemIndex ':' s
l = S.length s
skipSp !i | i >= l = S.empty
| otherwise = let c = S.unsafeIndex s i
in if isLWS $ w2c c
then skipSp $ i + 1
else S.unsafeDrop i s
{-# INLINE splitHeader #-}
------------------------------------------------------------------------------
isLWS :: Char -> Bool
isLWS c = c == ' ' || c == '\t'
{-# INLINE isLWS #-}
------------------------------------------------------------------------------
pHeaders :: MStandardHeaders -> InputStream ByteString -> IO Headers
pHeaders stdHdrs input = do
hdrs <- H.unsafeFromCaseFoldedList <$> go []
return hdrs
where
go !list = do
line <- pLine input
if S.null line
then return list
else do
let (!k0,!v) = splitHeader line
let !k = toLower k0
vf <- pCont id
let vs = vf []
let !v' = S.concat (v:vs)
let idx = findStdHeaderIndex k
when (idx >= 0) $ MV.unsafeWrite stdHdrs idx $! Just v'
let l' = ((k, v'):list)
go l'
trimBegin = S.dropWhile isLWS
pCont !dlist = do
mbS <- Streams.peek input
maybe (return dlist)
(\s -> if not (S.null s)
then if not $ isLWS $ w2c $ S.unsafeHead s
then return dlist
else procCont dlist
else Streams.read input >> pCont dlist)
mbS
procCont !dlist = do
line <- pLine input
let !t = trimBegin line
pCont (dlist . (" ":) . (t:))
------------------------------------------------------------------------------
methodFromString :: ByteString -> Method
methodFromString "GET" = GET
methodFromString "POST" = POST
methodFromString "HEAD" = HEAD
methodFromString "PUT" = PUT
methodFromString "DELETE" = DELETE
methodFromString "TRACE" = TRACE
methodFromString "OPTIONS" = OPTIONS
methodFromString "CONNECT" = CONNECT
methodFromString "PATCH" = PATCH
methodFromString s = Method s
------------------------------------------------------------------------------
readChunkedTransferEncoding :: InputStream ByteString
-> IO (InputStream ByteString)
readChunkedTransferEncoding input =
Streams.fromGenerator (consumeChunks input)
------------------------------------------------------------------------------
writeChunkedTransferEncoding :: OutputStream Builder
-> IO (OutputStream Builder)
writeChunkedTransferEncoding os = Streams.makeOutputStream f
where
f Nothing = do
Streams.write (Just chunkedTransferTerminator) os
Streams.write Nothing os
f x = Streams.write (chunkedTransferEncoding `fmap` x) os
---------------------
-- parse functions --
---------------------
------------------------------------------------------------------------------
{-
For a response body in chunked transfer encoding, iterate over
the individual chunks, reading the size parameter, then
looping over that chunk in bites of at most bUFSIZ,
yielding them to the receiveResponse InputStream accordingly.
-}
consumeChunks :: InputStream ByteString -> Generator ByteString ()
consumeChunks i1 = do
!n <- parseSize
if n > 0
then do
-- read one or more bytes, then loop to next chunk
go n
skipCRLF
consumeChunks i1
else do
-- NB: snap-server doesn't yet support chunked trailer parts
-- (see RFC7230#sec4.1.2)
-- consume final CRLF
skipCRLF
where
go 0 = return ()
go !n = do
(!x',!r) <- liftIO $ readN n i1
Streams.yield x'
go r
parseSize = do
liftIO $ parseFromStream transferChunkSize i1
skipCRLF = do
liftIO $ void (parseFromStream crlf i1)
transferChunkSize :: Parser (Int)
transferChunkSize = do
!n <- hexadecimal
-- skip over any chunk extensions (see RFC7230#sec4.1.1)
void (takeTill (== '\r'))
void crlf
return n
{-
The chunk size coming down from the client is somewhat arbitrary;
it's really just an indication of how many bytes need to be read
before the next size marker or end marker - neither of which has
anything to do with streaming on our side. Instead, we'll feed
bytes into our InputStream at an appropriate intermediate size.
-}
bUFSIZ :: Int
bUFSIZ = 32752
{-
Read the specified number of bytes up to a maximum of bUFSIZ,
returning a resultant ByteString and the number of bytes remaining.
-}
readN :: Int -> InputStream ByteString -> IO (ByteString, Int)
readN n input = do
!x' <- Streams.readExactly p input
return (x', r)
where
!d = n - bUFSIZ
!p = if d > 0 then bUFSIZ else n
!r = if d > 0 then d else 0
------------------------------------------------------------------------------
toLower :: ByteString -> ByteString
toLower = S.map lower
where
lower c0 = let !c = c2w c0
in if 65 <= c && c <= 90
then w2c $! c + 32
else c0
------------------------------------------------------------------------------
-- | A version of elemIndex that doesn't allocate a Maybe. (It returns -1 on
-- not found.)
elemIndex :: Char -> ByteString -> Int
#if MIN_VERSION_bytestring(0, 10, 6)
elemIndex c (PS !fp !start !len) = accursedUnutterablePerformIO $
#else
elemIndex c (PS !fp !start !len) = inlinePerformIO $
#endif
withForeignPtr fp $ \p0 -> do
let !p = plusPtr p0 start
q <- memchr p w8 (fromIntegral len)
return $! if q == nullPtr then (-1) else q `minusPtr` p
where
!w8 = c2w c
{-# INLINE elemIndex #-}
| sopvop/snap-server | src/Snap/Internal/Http/Server/Parser.hs | bsd-3-clause | 16,296 | 0 | 23 | 5,047 | 3,680 | 1,874 | 1,806 | 314 | 6 |
#!/usr/bin/runhaskell
-- This is an alternate version of Setup.hs which doesn't use Template Haskell.
-- It's appropriate for Cabal >= 1.18 && < 1.22
module Main where
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Distribution.Simple
import Distribution.Simple.BuildPaths
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Program
import Distribution.Simple.Program.Ld
import Distribution.Simple.Register
import Distribution.Simple.Setup
import Distribution.Simple.Utils
import Distribution.Text
import Distribution.Verbosity
import qualified Distribution.InstalledPackageInfo as I
import qualified Distribution.ModuleName as ModuleName
import Distribution.PackageDescription
import System.Environment
import System.FilePath
-- 'setEnv' function was added in base 4.7.0.0
setEnvShim :: String -> String -> IO ()
setEnvShim _ _ = return ()
-- 'LocalBuildInfo' record changed fields in Cabal 1.18
extractCLBI :: LocalBuildInfo -> ComponentLocalBuildInfo
extractCLBI x = getComponentLocalBuildInfo x CLibName
-- 'programFindLocation' field changed signature in Cabal 1.18
adaptFindLoc :: (Verbosity -> a) -> Verbosity -> ProgramSearchPath -> a
adaptFindLoc f x _ = f x
-- 'rawSystemStdInOut' function changed signature in Cabal 1.18
rawSystemStdErr v p a = rawSystemStdInOut v p a Nothing Nothing Nothing False
-- 'programPostConf' field changed signature in Cabal 1.18
noPostConf _ c = return c
-- 'generateRegistrationInfo' function will change signature in Cabal 1.22
genRegInfo verb pkg lib lbi clbi inp dir _ =
generateRegistrationInfo verb pkg lib lbi clbi inp dir
main :: IO ()
main = do
-- If system uses qtchooser(1) then encourage it to choose Qt 5
env <- getEnvironment
case lookup "QT_SELECT" env of
Nothing -> setEnvShim "QT_SELECT" "5"
_ -> return ()
-- Chain standard setup
defaultMainWithHooks simpleUserHooks {
confHook = confWithQt, buildHook = buildWithQt,
copyHook = copyWithQt, instHook = instWithQt,
regHook = regWithQt}
getCustomStr :: String -> PackageDescription -> String
getCustomStr name pkgDesc =
fromMaybe "" $ do
lib <- library pkgDesc
lookup name $ customFieldsBI $ libBuildInfo lib
getCustomFlag :: String -> PackageDescription -> Bool
getCustomFlag name pkgDesc =
fromMaybe False . simpleParse $ getCustomStr name pkgDesc
xForceGHCiLib, xMocHeaders, xFrameworkDirs, xSeparateCbits :: String
xForceGHCiLib = "x-force-ghci-lib"
xMocHeaders = "x-moc-headers"
xFrameworkDirs = "x-framework-dirs"
xSeparateCbits = "x-separate-cbits"
confWithQt :: (GenericPackageDescription, HookedBuildInfo) -> ConfigFlags ->
IO LocalBuildInfo
confWithQt (gpd,hbi) flags = do
let verb = fromFlag $ configVerbosity flags
mocPath <- findProgramLocation verb "moc"
cppPath <- findProgramLocation verb "cpp"
let mapLibBI = fmap . mapCondTree . mapBI $ substPaths mocPath cppPath
gpd' = gpd {
condLibrary = mapLibBI $ condLibrary gpd,
condExecutables = mapAllBI mocPath cppPath $ condExecutables gpd,
condTestSuites = mapAllBI mocPath cppPath $ condTestSuites gpd,
condBenchmarks = mapAllBI mocPath cppPath $ condBenchmarks gpd}
lbi <- confHook simpleUserHooks (gpd',hbi) flags
-- Find Qt moc program and store in database
(_,_,db') <- requireProgramVersion verb
mocProgram qtVersionRange (withPrograms lbi)
-- Force enable GHCi workaround library if flag set and not using shared libs
let forceGHCiLib =
(getCustomFlag xForceGHCiLib $ localPkgDescr lbi) &&
(not $ withSharedLib lbi)
-- Update LocalBuildInfo
return lbi {withPrograms = db',
withGHCiLib = withGHCiLib lbi || forceGHCiLib}
mapAllBI :: (HasBuildInfo a) => Maybe FilePath -> Maybe FilePath ->
[(x, CondTree c v a)] -> [(x, CondTree c v a)]
mapAllBI mocPath cppPath =
mapSnd . mapCondTree . mapBI $ substPaths mocPath cppPath
mapCondTree :: (a -> a) -> CondTree v c a -> CondTree v c a
mapCondTree f (CondNode val cnstr cs) =
CondNode (f val) cnstr $ map updateChildren cs
where updateChildren (cond,left,right) =
(cond, mapCondTree f left, fmap (mapCondTree f) right)
substPaths :: Maybe FilePath -> Maybe FilePath -> BuildInfo -> BuildInfo
substPaths mocPath cppPath build =
let toRoot = takeDirectory . takeDirectory . fromMaybe ""
substPath = replace "/QT_ROOT" (toRoot mocPath) .
replace "/SYS_ROOT" (toRoot cppPath)
in build {ccOptions = map substPath $ ccOptions build,
ldOptions = map substPath $ ldOptions build,
extraLibDirs = map substPath $ extraLibDirs build,
includeDirs = map substPath $ includeDirs build,
options = mapSnd (map substPath) $ options build,
customFieldsBI = mapSnd substPath $ customFieldsBI build}
buildWithQt ::
PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO ()
buildWithQt pkgDesc lbi hooks flags = do
let verb = fromFlag $ buildVerbosity flags
libs' <- maybeMapM (\lib -> fmap (\lib' ->
lib {libBuildInfo = lib'}) $ fixQtBuild verb lbi $ libBuildInfo lib) $
library pkgDesc
let pkgDesc' = pkgDesc {library = libs'}
lbi' = if (needsGHCiFix pkgDesc lbi)
then lbi {withGHCiLib = False, splitObjs = False} else lbi
buildHook simpleUserHooks pkgDesc' lbi' hooks flags
case libs' of
Just lib -> when (needsGHCiFix pkgDesc lbi) $
buildGHCiFix verb pkgDesc lbi lib
Nothing -> return ()
fixQtBuild :: Verbosity -> LocalBuildInfo -> BuildInfo -> IO BuildInfo
fixQtBuild verb lbi build = do
let moc = fromJust $ lookupProgram mocProgram $ withPrograms lbi
option name = words $ fromMaybe "" $ lookup name $ customFieldsBI build
incs = option xMocHeaders
bDir = buildDir lbi
cpps = map (\inc ->
bDir </> (takeDirectory inc) </>
("moc_" ++ (takeBaseName inc) ++ ".cpp")) incs
args = map ("-I"++) (includeDirs build) ++
map ("-F"++) (option xFrameworkDirs)
-- Run moc on each of the header files containing QObject subclasses
mapM_ (\(i,o) -> do
createDirectoryIfMissingVerbose verb True (takeDirectory o)
runProgram verb moc $ [i,"-o",o] ++ args) $ zip incs cpps
-- Add the moc generated source files to be compiled
return build {cSources = cpps ++ cSources build,
ccOptions = "-fPIC" : ccOptions build}
needsGHCiFix :: PackageDescription -> LocalBuildInfo -> Bool
needsGHCiFix pkgDesc lbi =
withGHCiLib lbi && getCustomFlag xSeparateCbits pkgDesc
mkGHCiFixLibPkgId :: PackageDescription -> PackageIdentifier
mkGHCiFixLibPkgId pkgDesc =
let pid = packageId pkgDesc
(PackageName name) = pkgName pid
in pid {pkgName = PackageName $ "cbits-" ++ name}
mkGHCiFixLibName :: PackageDescription -> String
mkGHCiFixLibName pkgDesc =
("lib" ++ display (mkGHCiFixLibPkgId pkgDesc)) <.> dllExtension
mkGHCiFixLibRefName :: PackageDescription -> String
mkGHCiFixLibRefName pkgDesc =
prefix ++ display (mkGHCiFixLibPkgId pkgDesc)
where prefix = if dllExtension == "dll" then "lib" else ""
buildGHCiFix ::
Verbosity -> PackageDescription -> LocalBuildInfo -> Library -> IO ()
buildGHCiFix verb pkgDesc lbi lib = do
let bDir = buildDir lbi
ms = map ModuleName.toFilePath $ libModules lib
hsObjs = map ((bDir </>) . (<.> "o")) ms
stubObjs <- fmap catMaybes $
mapM (findFileWithExtension ["o"] [bDir]) $ map (++ "_stub") ms
(ld,_) <- requireProgram verb ldProgram (withPrograms lbi)
combineObjectFiles verb ld
(bDir </> (("HS" ++) $ display $ packageId pkgDesc) <.> "o")
(stubObjs ++ hsObjs)
(ghc,_) <- requireProgram verb ghcProgram (withPrograms lbi)
let bi = libBuildInfo lib
runProgram verb ghc (
["-shared","-o",bDir </> (mkGHCiFixLibName pkgDesc)] ++
(ldOptions bi) ++ (map ("-l" ++) $ extraLibs bi) ++
(map ("-L" ++) $ extraLibDirs bi) ++
(map ((bDir </>) . flip replaceExtension objExtension) $ cSources bi))
return ()
mocProgram :: Program
mocProgram = Program {
programName = "moc",
programFindLocation = adaptFindLoc $
\verb -> findProgramLocation verb "moc",
programFindVersion = \verb path -> do
(oLine,eLine,_) <- rawSystemStdErr verb path ["-v"]
return $
(findSubseq (stripPrefix "(Qt ") eLine `mplus`
findSubseq (stripPrefix "moc ") oLine) >>=
simpleParse . takeWhile (\c -> isDigit c || c == '.'),
programPostConf = noPostConf
}
qtVersionRange :: VersionRange
qtVersionRange = intersectVersionRanges
(orLaterVersion $ Version [5,0] []) (earlierVersion $ Version [6,0] [])
copyWithQt ::
PackageDescription -> LocalBuildInfo -> UserHooks -> CopyFlags -> IO ()
copyWithQt pkgDesc lbi hooks flags = do
copyHook simpleUserHooks pkgDesc lbi hooks flags
let verb = fromFlag $ copyVerbosity flags
dest = fromFlag $ copyDest flags
bDir = buildDir lbi
libDir = libdir $ absoluteInstallDirs pkgDesc lbi dest
file = mkGHCiFixLibName pkgDesc
when (needsGHCiFix pkgDesc lbi) $
installOrdinaryFile verb (bDir </> file) (libDir </> file)
regWithQt ::
PackageDescription -> LocalBuildInfo -> UserHooks -> RegisterFlags -> IO ()
regWithQt pkg@PackageDescription { library = Just lib } lbi _ flags = do
let verb = fromFlag $ regVerbosity flags
inplace = fromFlag $ regInPlace flags
dist = fromFlag $ regDistPref flags
pkgDb = withPackageDB lbi
clbi = extractCLBI lbi
instPkgInfo <- genRegInfo verb pkg lib lbi clbi inplace dist pkgDb
let instPkgInfo' = instPkgInfo {
-- Add extra library for GHCi workaround
I.extraGHCiLibraries =
(if needsGHCiFix pkg lbi then [mkGHCiFixLibRefName pkg] else []) ++
I.extraGHCiLibraries instPkgInfo,
-- Add directories to framework search path
I.frameworkDirs =
words (getCustomStr xFrameworkDirs pkg) ++
I.frameworkDirs instPkgInfo}
case flagToMaybe $ regGenPkgConf flags of
Just regFile -> do
writeUTF8File (fromMaybe (display (packageId pkg) <.> "conf") regFile) $
I.showInstalledPackageInfo instPkgInfo'
_ | fromFlag (regGenScript flags) ->
die "Registration scripts are not implemented."
| otherwise ->
registerPackage verb instPkgInfo' pkg lbi inplace pkgDb
regWithQt pkgDesc _ _ flags =
setupMessage (fromFlag $ regVerbosity flags)
"Package contains no library to register:" (packageId pkgDesc)
instWithQt ::
PackageDescription -> LocalBuildInfo -> UserHooks -> InstallFlags -> IO ()
instWithQt pkgDesc lbi hooks flags = do
let copyFlags = defaultCopyFlags {
copyDistPref = installDistPref flags,
copyVerbosity = installVerbosity flags
}
regFlags = defaultRegisterFlags {
regDistPref = installDistPref flags,
regInPlace = installInPlace flags,
regPackageDB = installPackageDB flags,
regVerbosity = installVerbosity flags
}
copyWithQt pkgDesc lbi hooks copyFlags
when (hasLibs pkgDesc) $ regWithQt pkgDesc lbi hooks regFlags
class HasBuildInfo a where
mapBI :: (BuildInfo -> BuildInfo) -> a -> a
instance HasBuildInfo Library where
mapBI f x = x {libBuildInfo = f $ libBuildInfo x}
instance HasBuildInfo Executable where
mapBI f x = x {buildInfo = f $ buildInfo x}
instance HasBuildInfo TestSuite where
mapBI f x = x {testBuildInfo = f $ testBuildInfo x}
instance HasBuildInfo Benchmark where
mapBI f x = x {benchmarkBuildInfo = f $ benchmarkBuildInfo x}
maybeMapM :: (Monad m) => (a -> m b) -> (Maybe a) -> m (Maybe b)
maybeMapM f = maybe (return Nothing) $ liftM Just . f
mapSnd :: (a -> a) -> [(x, a)] -> [(x, a)]
mapSnd f = map (\(x,y) -> (x,f y))
findSubseq :: ([a] -> Maybe b) -> [a] -> Maybe b
findSubseq f [] = f []
findSubseq f xs@(_:ys) =
case f xs of
Nothing -> findSubseq f ys
Just r -> Just r
replace :: (Eq a) => [a] -> [a] -> [a] -> [a]
replace [] _ xs = xs
replace _ _ [] = []
replace src dst xs@(x:xs') =
case stripPrefix src xs of
Just xs'' -> dst ++ replace src dst xs''
Nothing -> x : replace src dst xs'
| johntyree/HsQML | SetupNoTH.hs | bsd-3-clause | 12,105 | 0 | 20 | 2,539 | 3,710 | 1,897 | 1,813 | 252 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ExistentialQuantification #-}
module Ivory.Language.Scope where
-- | Definition scopes for values.
data RefScope
= Global -- ^ Globally allocated
| forall s. Stack s -- ^ Stack allocated
| GaloisInc/ivory | ivory/src/Ivory/Language/Scope.hs | bsd-3-clause | 276 | 0 | 6 | 55 | 30 | 21 | 9 | 7 | 0 |
module Jann01 where
@Export 1.02
@Export2 "Hello"
@Hello { }
@Hello1 []
@Hello2 [ "name", "name", "name" ]
data Hello = Hello { thing :: String, value :: String }
@Hello { value = "hello" }
data Hello1 = Hello1 {
@Value
thing1 :: String,
@Override
@Mutable { name = "Hello" }
value1 :: String
}
@Hello { value = "hello" }
data Hello2 = @Hello Hello2 {
@Value
thing2 :: String,
@Override
@Mutable { name = "Hello" }
value2 :: String
}
| @Export @Hello
@Export
Hello3 { @Hello name :: String }
@Named "Hello"
val :: String
val = "String"
| rahulmutt/ghcvm | tests/suite/annotations/compile/jann01.hs | bsd-3-clause | 595 | 7 | 9 | 161 | 192 | 113 | 79 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeApplications #-}
module Main where
import qualified Codec.Serialise as Ser
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import Data.Proxy (Proxy(Proxy))
import Data.Ratio ((%), numerator, denominator)
import GHC.TypeLits (Nat, Symbol, KnownSymbol, symbolVal)
import qualified Money
import qualified Test.Tasty as Tasty
import Test.Tasty.HUnit ((@?=), (@=?))
import qualified Test.Tasty.HUnit as HU
import qualified Test.Tasty.Runners as Tasty
import Test.Tasty.QuickCheck ((===), (==>), (.&&.))
import qualified Test.Tasty.QuickCheck as QC
import Money.Serialise()
--------------------------------------------------------------------------------
main :: IO ()
main = Tasty.defaultMainWithIngredients
[ Tasty.consoleTestReporter
, Tasty.listingTests
] (Tasty.localOption (QC.QuickCheckTests 100) tests)
tests :: Tasty.TestTree
tests =
Tasty.testGroup "root"
[ testCurrencies
, testCurrencyUnits
, testExchange
, testRawSerializations
]
testCurrencies :: Tasty.TestTree
testCurrencies =
Tasty.testGroup "Currency"
[ testDense (Proxy :: Proxy "BTC") -- A cryptocurrency.
, testDense (Proxy :: Proxy "USD") -- A fiat currency with decimal fractions.
, testDense (Proxy :: Proxy "VUV") -- A fiat currency with non-decimal fractions.
, testDense (Proxy :: Proxy "XAU") -- A precious metal.
]
testCurrencyUnits :: Tasty.TestTree
testCurrencyUnits =
Tasty.testGroup "Currency units"
[ testDiscrete (Proxy :: Proxy "BTC") (Proxy :: Proxy "satoshi")
, testDiscrete (Proxy :: Proxy "BTC") (Proxy :: Proxy "bitcoin")
, testDiscrete (Proxy :: Proxy "USD") (Proxy :: Proxy "cent")
, testDiscrete (Proxy :: Proxy "USD") (Proxy :: Proxy "dollar")
, testDiscrete (Proxy :: Proxy "VUV") (Proxy :: Proxy "vatu")
, testDiscrete (Proxy :: Proxy "XAU") (Proxy :: Proxy "gram")
, testDiscrete (Proxy :: Proxy "XAU") (Proxy :: Proxy "grain")
]
testDense
:: forall currency
. KnownSymbol currency
=> Proxy currency
-> Tasty.TestTree
testDense pc =
Tasty.testGroup ("Dense " ++ show (symbolVal pc))
[ QC.testProperty "Serialise encoding roundtrip" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
Just x === hush (Ser.deserialiseOrFail (Ser.serialise x))
, QC.testProperty "Serialise encoding roundtrip (SomeDense)" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
let x' = Money.toSomeDense x
in Just x' === hush (Ser.deserialiseOrFail (Ser.serialise x'))
, QC.testProperty "Serialise encoding roundtrip (Dense through SomeDense)" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
Just x === hush (Ser.deserialiseOrFail (Ser.serialise (Money.toSomeDense x)))
, QC.testProperty "Serialise encoding roundtrip (SomeDense through Dense)" $
QC.forAll QC.arbitrary $ \(x :: Money.Dense currency) ->
Just (Money.toSomeDense x) === hush (Ser.deserialiseOrFail (Ser.serialise x))
]
testExchange :: Tasty.TestTree
testExchange =
Tasty.testGroup "Exchange"
[ testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "BTC") (Proxy :: Proxy "XAU")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "USD") (Proxy :: Proxy "XAU")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "VUV") (Proxy :: Proxy "XAU")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "BTC")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "USD")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "VUV")
, testExchangeRate (Proxy :: Proxy "XAU") (Proxy :: Proxy "XAU")
]
testDiscrete
:: forall (currency :: Symbol) (unit :: Symbol)
. ( Money.GoodScale (Money.UnitScale currency unit)
, KnownSymbol currency
, KnownSymbol unit )
=> Proxy currency
-> Proxy unit
-> Tasty.TestTree
testDiscrete pc pu =
Tasty.testGroup ("Discrete " ++ show (symbolVal pc) ++ " "
++ show (symbolVal pu))
[ QC.testProperty "Serialise encoding roundtrip" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
Just x === hush (Ser.deserialiseOrFail (Ser.serialise x))
, QC.testProperty "Serialise encoding roundtrip (SomeDiscrete)" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
let x' = Money.toSomeDiscrete x
in Just x' === hush (Ser.deserialiseOrFail (Ser.serialise x'))
, QC.testProperty "Serialise encoding roundtrip (Discrete through SomeDiscrete)" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
Just x === hush (Ser.deserialiseOrFail (Ser.serialise (Money.toSomeDiscrete x)))
, QC.testProperty "Serialise encoding roundtrip (SomeDiscrete through Discrete)" $
QC.forAll QC.arbitrary $ \(x :: Money.Discrete currency unit) ->
Just (Money.toSomeDiscrete x) === hush (Ser.deserialiseOrFail (Ser.serialise x))
]
testExchangeRate
:: forall (src :: Symbol) (dst :: Symbol)
. (KnownSymbol src, KnownSymbol dst)
=> Proxy src
-> Proxy dst
-> Tasty.TestTree
testExchangeRate ps pd =
Tasty.testGroup ("ExchangeRate " ++ show (symbolVal ps) ++ " "
++ show (symbolVal pd))
[ QC.testProperty "Serialise encoding roundtrip" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
Just x === hush (Ser.deserialiseOrFail (Ser.serialise x))
, QC.testProperty "Serialise encoding roundtrip (SomeExchangeRate)" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
let x' = Money.toSomeExchangeRate x
in Just x' === hush (Ser.deserialiseOrFail (Ser.serialise x'))
, QC.testProperty "Serialise encoding roundtrip (ExchangeRate through SomeExchangeRate)" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
Just x === hush (Ser.deserialiseOrFail (Ser.serialise (Money.toSomeExchangeRate x)))
, QC.testProperty "Serialise encoding roundtrip (SomeExchangeRate through ExchangeRate)" $
QC.forAll QC.arbitrary $ \(x :: Money.ExchangeRate src dst) ->
Just (Money.toSomeExchangeRate x) === hush (Ser.deserialiseOrFail (Ser.serialise x))
]
--------------------------------------------------------------------------------
-- Raw parsing "golden tests"
testRawSerializations :: Tasty.TestTree
testRawSerializations =
Tasty.testGroup "Raw serializations"
[ Tasty.testGroup "serialise"
[ Tasty.testGroup "decode"
[ HU.testCase "Dense" $ do
Just rawDns0 @=? hush (Ser.deserialiseOrFail rawDns0_serialise)
, HU.testCase "Discrete" $ do
Just rawDis0 @=? hush (Ser.deserialiseOrFail rawDis0_serialise)
, HU.testCase "ExchangeRate" $ do
Just rawXr0 @=? hush (Ser.deserialiseOrFail rawXr0_serialise)
]
, Tasty.testGroup "encode"
[ HU.testCase "Dense" $ rawDns0_serialise @=? Ser.serialise rawDns0
, HU.testCase "Discrete" $ rawDis0_serialise @=? Ser.serialise rawDis0
, HU.testCase "ExchangeRate" $ rawXr0_serialise @=? Ser.serialise rawXr0
]
]
]
rawDns0 :: Money.Dense "USD"
rawDns0 = Money.dense' (26%1)
rawDis0 :: Money.Discrete "USD" "cent"
rawDis0 = Money.discrete 4
rawXr0 :: Money.ExchangeRate "USD" "BTC"
Just rawXr0 = Money.exchangeRate (3%2)
rawDns0_serialise :: BL.ByteString
rawDns0_serialise = "cUSD\CAN\SUB\SOH"
rawDis0_serialise :: BL.ByteString
rawDis0_serialise = "cUSD\CANd\SOH\EOT"
rawXr0_serialise :: BL.ByteString
rawXr0_serialise = "cUSDcBTC\ETX\STX"
--------------------------------------------------------------------------------
-- Misc
hush :: Either a b -> Maybe b
hush (Left _ ) = Nothing
hush (Right b) = Just b
| k0001/haskell-money | safe-money-serialise/test/Main.hs | bsd-3-clause | 8,450 | 0 | 18 | 1,562 | 2,546 | 1,333 | 1,213 | 168 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.RDS.DeleteDBSecurityGroup
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes a DB security group.
--
-- The specified DB security group must not be associated with any DB instances.
--
-- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DeleteDBSecurityGroup.html>
module Network.AWS.RDS.DeleteDBSecurityGroup
(
-- * Request
DeleteDBSecurityGroup
-- ** Request constructor
, deleteDBSecurityGroup
-- ** Request lenses
, ddbsgDBSecurityGroupName
-- * Response
, DeleteDBSecurityGroupResponse
-- ** Response constructor
, deleteDBSecurityGroupResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.RDS.Types
import qualified GHC.Exts
newtype DeleteDBSecurityGroup = DeleteDBSecurityGroup
{ _ddbsgDBSecurityGroupName :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteDBSecurityGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ddbsgDBSecurityGroupName' @::@ 'Text'
--
deleteDBSecurityGroup :: Text -- ^ 'ddbsgDBSecurityGroupName'
-> DeleteDBSecurityGroup
deleteDBSecurityGroup p1 = DeleteDBSecurityGroup
{ _ddbsgDBSecurityGroupName = p1
}
-- | The name of the DB security group to delete.
--
-- You cannot delete the default DB security group. Constraints:
--
-- Must be 1 to 255 alphanumeric characters First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens
-- Must not be "Default" May not contain spaces
ddbsgDBSecurityGroupName :: Lens' DeleteDBSecurityGroup Text
ddbsgDBSecurityGroupName =
lens _ddbsgDBSecurityGroupName
(\s a -> s { _ddbsgDBSecurityGroupName = a })
data DeleteDBSecurityGroupResponse = DeleteDBSecurityGroupResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteDBSecurityGroupResponse' constructor.
deleteDBSecurityGroupResponse :: DeleteDBSecurityGroupResponse
deleteDBSecurityGroupResponse = DeleteDBSecurityGroupResponse
instance ToPath DeleteDBSecurityGroup where
toPath = const "/"
instance ToQuery DeleteDBSecurityGroup where
toQuery DeleteDBSecurityGroup{..} = mconcat
[ "DBSecurityGroupName" =? _ddbsgDBSecurityGroupName
]
instance ToHeaders DeleteDBSecurityGroup
instance AWSRequest DeleteDBSecurityGroup where
type Sv DeleteDBSecurityGroup = RDS
type Rs DeleteDBSecurityGroup = DeleteDBSecurityGroupResponse
request = post "DeleteDBSecurityGroup"
response = nullResponse DeleteDBSecurityGroupResponse
| romanb/amazonka | amazonka-rds/gen/Network/AWS/RDS/DeleteDBSecurityGroup.hs | mpl-2.0 | 3,524 | 0 | 9 | 703 | 336 | 209 | 127 | 47 | 1 |
{-# LANGUAGE NamedFieldPuns #-}
module VerifyImageTrans where
import Verify.Graphics.Vty.Image
import Graphics.Vty.Image.Internal
import Verify
import Data.Word
isHorizTextOfColumns :: Image -> Int -> Bool
isHorizTextOfColumns (HorizText { outputWidth = inW }) expectedW = inW == expectedW
isHorizTextOfColumns (BGFill { outputWidth = inW }) expectedW = inW == expectedW
isHorizTextOfColumns _image _expectedW = False
verifyHorizContatWoAttrChangeSimplifies :: SingleRowSingleAttrImage -> Bool
verifyHorizContatWoAttrChangeSimplifies (SingleRowSingleAttrImage _attr charCount image) =
isHorizTextOfColumns image charCount
verifyHorizContatWAttrChangeSimplifies :: SingleRowTwoAttrImage -> Bool
verifyHorizContatWAttrChangeSimplifies ( SingleRowTwoAttrImage (SingleRowSingleAttrImage attr0 charCount0 _image0)
(SingleRowSingleAttrImage attr1 charCount1 _image1)
i
)
| charCount0 == 0 || charCount1 == 0 || attr0 == attr1 = isHorizTextOfColumns i (charCount0 + charCount1)
| otherwise = False == isHorizTextOfColumns i (charCount0 + charCount1)
tests :: IO [Test]
tests = return
[ verify "verifyHorizContatWoAttrChangeSimplifies" verifyHorizContatWoAttrChangeSimplifies
, verify "verifyHorizContatWAttrChangeSimplifies" verifyHorizContatWAttrChangeSimplifies
]
| jtdaugherty/vty | test/VerifyImageTrans.hs | bsd-3-clause | 1,463 | 0 | 12 | 331 | 279 | 147 | 132 | 23 | 1 |
{-# LANGUAGE ViewPatterns, TemplateHaskell #-}
{-# LANGUAGE GeneralizedNewtypeDeriving,
ViewPatterns,
ScopedTypeVariables #-}
module Bad where
import Control.Applicative ((<$>))
import System.Directory (doesFileExist)
import qualified Data.Map as M
import Data.Map ((!), keys, Map)
data Point = Point
{ pointX, pointY :: Double
, pointName :: String
} deriving (Show)
| silkapp/stylish-haskell | examples/Bad.hs | bsd-3-clause | 411 | 0 | 8 | 89 | 84 | 56 | 28 | 13 | 0 |
--------------------------------------------------------------------
-- |
-- Module : MediaWiki.API.Output
-- Description : Serializing MediaWiki API types
-- Copyright : (c) Sigbjorn Finne, 2008
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <[email protected]>
-- Stability : provisional
-- Portability: portable
--
-- Serializing MediaWiki API types
--
--------------------------------------------------------------------
module MediaWiki.API.Output where
import MediaWiki.API.Types
import MediaWiki.API.Base
import MediaWiki.Util.Codec.Percent
import Data.List
import Data.Maybe
showRequest :: Request -> String
showRequest req =
join (showAction (reqAction req) : showMaxLag (reqMaxLag req) (showFormat (reqFormat req)))
showMaxLag :: Maybe Int -> String -> [String]
showMaxLag Nothing rs = [rs]
showMaxLag (Just l) rs = [field "maxlag" (show l), rs]
showFormat :: Format -> String
showFormat f = field "format" $ isFormatted (formatFormatted f) $
case formatKind f of
FormatJSON -> "json"
FormatPHP -> "php"
FormatWDDX -> "wddx"
FormatXML -> "xml"
FormatYAML -> "yaml"
FormatTxt -> "txt"
FormatDbg -> "dbg"
where
isFormatted False xs = xs
isFormatted _ xs = xs++"fm"
toReq :: APIRequest a => a -> [String]
toReq x =
case catMaybes $ showReq x of
[] -> []
xs -> map showP xs
where
showP (a,b) = a ++ '=':b
showQueryRequestKind :: QueryRequestKind -> [String]
showQueryRequestKind r =
case r of
InfoProp p -> toReq p
RevisionsProp p -> toReq p
LinksPropProp p -> toReq p
LangLinksProp p -> toReq p
ImagesProp p -> toReq p
ImageInfoProp p -> toReq p
TemplatesProp p -> toReq p
CategoriesProp p -> toReq p
AllCategoriesProp p -> toReq p
AllImagesProp p -> toReq p
AllLinksProp p -> toReq p
AllMessagesProp p -> toReq p
AllPagesProp p -> toReq p
AllUsersProp p -> toReq p
BacklinksProp p -> toReq p
EmbeddedInProp p -> toReq p
ImageUsageProp p -> toReq p
CategoryInfoProp p -> toReq p
CategoryMembersProp p -> toReq p
ExternalLinksProp p -> toReq p
ExternalURLUsageProp p -> toReq p
LogEventsProp p -> toReq p
RecentChangesProp p -> toReq p
SearchProp p -> toReq p
SiteInfoProp p -> toReq p
UserContribsProp p -> toReq p
UserInfoProp p -> toReq p
WatchListProp p -> toReq p
BlocksProp p -> toReq p
DeletedRevsProp p -> toReq p
UsersProp p -> toReq p
RandomProp p -> toReq p
showAction :: Action -> String
showAction act = join $
case act of
Sitematrix -> [field "action" "sitematrix"]
Login l -> (field "action" "login"): (toReq l)
Logout -> [field "action" "logout"]
Query q qr -> (field "action" "query") : (showQuery q) ++ qr
ExpandTemplates et -> (field "action" "expandtemplates") : (showExpandTemplates et)
Parse pt -> (field "action" "parse") : (showParseRequest pt)
OpenSearch os -> (field "action" "opensearch") : (showOpenSearch os)
FeedWatch f -> (field "action" "feedwatchlist") : (showFeedWatch f)
Help h -> (field "action" "help") : (showHelpRequest h)
ParamInfo pin -> (field "action" "paraminfo") : (showParamInfoRequest pin)
Unblock r -> (field "action" "unblock") : toReq r
Watch r -> (field "action" "watch") : toReq r
EmailUser r -> (field "action" "emailuser") : toReq r
Edit r -> (field "action" "edit") : toReq r
Move r -> (field "action" "move") : toReq r
Block r -> (field "action" "block") : toReq r
Protect r -> (field "action" "protect") : toReq r
Undelete r -> (field "action" "undelete") : toReq r
Delete r -> (field "action" "delete") : toReq r
Rollback r -> (field "action" "rollback") : toReq r
OtherAction at vs -> (field "action" at) : (map showValueName vs)
{-
showLoginRequest :: LoginRequest -> [String]
showLoginRequest l = catMaybes
[ Just $ field "name" (lgName l)
, Just $ field "password" (lgPassword l)
, fieldMb "version" id (lgDomain l)
]
-}
showHelpRequest :: HelpRequest -> [String]
showHelpRequest h =
maybeToList (fieldMb "version" showBool (helpVersion h))
showQuery :: QueryRequest -> [String]
showQuery q = catMaybes
[ fList "titles" (quTitles q)
, fList "pageids" (quPageIds q)
, fList "revids" (quRevIds q)
, fList "prop" (map showPropKind $ quProps q)
, fList "list" (map showListKind $ quLists q)
, fList "meta" (map showMetaKind $ quMetas q)
, fieldMb "generator" showGeneratorKind (quGenerator q)
, fieldMb "redirects" showBool (quFollowRedirects q)
, fieldMb "indexpageids" showBool (quIndexPageIds q)
]
where
fList t ls = fieldList t "|" ls
showExpandTemplates :: ExpandTemplatesRequest -> [String]
showExpandTemplates et = catMaybes
[ fieldMb "title" id (etTitle et)
, Just $ field "text" (etText et)
]
showPropKind :: PropKind -> String
showPropKind pk = prKind pk
showListKind :: ListKind -> String
showListKind lk = liKind lk
showMetaKind :: MetaKind -> String
showMetaKind mk = meKind mk
showParseRequest :: ParseRequest -> [String]
showParseRequest p = catMaybes
[ fieldMb "title" id (paTitle p)
, Just $ field "text" (paText p)
, fieldMb "page" id (paPage p)
, fieldList "prop" "|" (paProp p)
]
showOpenSearch :: OpenSearchRequest -> [String]
showOpenSearch o = catMaybes
[ Just $ field "search" (osSearch o)
, fieldMb "limit" show (osLimit o)
]
showFeedWatch :: FeedWatchListRequest -> [String]
showFeedWatch f = catMaybes
[ Just $ field "feedformat" (if feAsAtom f then "atom" else "rss")
, fieldMb "hours" show (feHours f)
, if feAllRev f then (Just $ field "allrev" "") else Nothing
]
showParamInfoRequest :: ParamInfoRequest -> [String]
showParamInfoRequest p = catMaybes
[ fieldList "modules" "," (paModules p)
, fieldList "querymodules" "|" (paQueryModules p)
]
showGeneratorKind :: GeneratorKind -> String
showGeneratorKind gk = genKind gk
showValueName :: ValueName -> String
showValueName (n,v) = field n v
showBool :: Bool -> String
showBool True = "true"
showBool _ = "false"
join :: [String] -> String
join [] = ""
join xs = concat (intersperse "&" xs)
field :: String -> String -> String
field a b = a ++ '=':b
fieldMb :: String -> (a -> String) -> Maybe a -> Maybe String
fieldMb _ _ Nothing = Nothing
fieldMb n f (Just x) = Just (field n (f x))
fieldList :: String -> String -> [String] -> Maybe String
fieldList _ _ [] = Nothing
fieldList n s xs = Just (field n (intercalate (getEncodedString s) xs))
| neobrain/neobot | mediawiki/MediaWiki/API/Output.hs | bsd-3-clause | 6,655 | 0 | 12 | 1,537 | 2,263 | 1,106 | 1,157 | 151 | 32 |
--------------------------------------------------------------------
-- |
-- Module : MediaWiki.API.Query.AllUsers
-- Description : Representing 'allusers' requests.
-- Copyright : (c) Sigbjorn Finne, 2008
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <[email protected]>
-- Stability : provisional
-- Portability: portable
--
-- Representing 'allusers' requests.
--
--------------------------------------------------------------------
module MediaWiki.API.Query.AllUsers where
import MediaWiki.API.Types
import MediaWiki.API.Utils
data AllUsersRequest
= AllUsersRequest
{ auFrom :: Maybe UserName
, auPrefix :: Maybe UserName
, auGroup :: Maybe GroupName
, auProp :: [String]
, auLimit :: Maybe Int
}
instance APIRequest AllUsersRequest where
queryKind _ = QList "allusers"
showReq r =
[ mbOpt "aufrom" id (auFrom r)
, mbOpt "auprefix" id (auPrefix r)
, mbOpt "augroup" id (auGroup r)
, opt1 "auprop" (auProp r)
, mbOpt "aulimit" show (auLimit r)
]
emptyAllUsersRequest :: AllUsersRequest
emptyAllUsersRequest = AllUsersRequest
{ auFrom = Nothing
, auPrefix = Nothing
, auGroup = Nothing
, auProp = []
, auLimit = Nothing
}
data AllUsersResponse
= AllUsersResponse
{ auUsers :: [(UserName, Maybe Int, Maybe String)]
, auContinue :: Maybe String
}
emptyAllUsersResponse :: AllUsersResponse
emptyAllUsersResponse
= AllUsersResponse
{ auUsers = []
, auContinue = Nothing
}
| neobrain/neobot | mediawiki/MediaWiki/API/Query/AllUsers.hs | bsd-3-clause | 1,521 | 0 | 11 | 330 | 305 | 179 | 126 | 34 | 1 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
-----------------
A demand analysis
-----------------
-}
{-# LANGUAGE CPP #-}
module DmdAnal ( dmdAnalProgram ) where
#include "HsVersions.h"
import DynFlags
import WwLib ( findTypeShape, deepSplitProductType_maybe )
import Demand -- All of it
import CoreSyn
import Outputable
import VarEnv
import BasicTypes
import FastString
import Data.List
import DataCon
import Id
import CoreUtils ( exprIsHNF, exprType, exprIsTrivial )
import TyCon
import Type
import Coercion ( Coercion, coVarsOfCo )
import FamInstEnv
import Util
import Maybes ( isJust )
import TysWiredIn ( unboxedPairDataCon )
import TysPrim ( realWorldStatePrimTy )
import ErrUtils ( dumpIfSet_dyn )
import Name ( getName, stableNameCmp )
import Data.Function ( on )
{-
************************************************************************
* *
\subsection{Top level stuff}
* *
************************************************************************
-}
dmdAnalProgram :: DynFlags -> FamInstEnvs -> CoreProgram -> IO CoreProgram
dmdAnalProgram dflags fam_envs binds
= do {
let { binds_plus_dmds = do_prog binds } ;
dumpIfSet_dyn dflags Opt_D_dump_strsigs "Strictness signatures" $
dumpStrSig binds_plus_dmds ;
return binds_plus_dmds
}
where
do_prog :: CoreProgram -> CoreProgram
do_prog binds = snd $ mapAccumL dmdAnalTopBind (emptyAnalEnv dflags fam_envs) binds
-- Analyse a (group of) top-level binding(s)
dmdAnalTopBind :: AnalEnv
-> CoreBind
-> (AnalEnv, CoreBind)
dmdAnalTopBind sigs (NonRec id rhs)
= (extendAnalEnv TopLevel sigs id sig, NonRec id2 rhs2)
where
( _, _, _, rhs1) = dmdAnalRhs TopLevel Nothing sigs id rhs
(sig, _, id2, rhs2) = dmdAnalRhs TopLevel Nothing (nonVirgin sigs) id rhs1
-- Do two passes to improve CPR information
-- See comments with ignore_cpr_info in mk_sig_ty
-- and with extendSigsWithLam
dmdAnalTopBind sigs (Rec pairs)
= (sigs', Rec pairs')
where
(sigs', _, pairs') = dmdFix TopLevel sigs pairs
-- We get two iterations automatically
-- c.f. the NonRec case above
{-
************************************************************************
* *
\subsection{The analyser itself}
* *
************************************************************************
Note [Ensure demand is strict]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's important not to analyse e with a lazy demand because
a) When we encounter case s of (a,b) ->
we demand s with U(d1d2)... but if the overall demand is lazy
that is wrong, and we'd need to reduce the demand on s,
which is inconvenient
b) More important, consider
f (let x = R in x+x), where f is lazy
We still want to mark x as demanded, because it will be when we
enter the let. If we analyse f's arg with a Lazy demand, we'll
just mark x as Lazy
c) The application rule wouldn't be right either
Evaluating (f x) in a L demand does *not* cause
evaluation of f in a C(L) demand!
-}
-- If e is complicated enough to become a thunk, its contents will be evaluated
-- at most once, so oneify it.
dmdTransformThunkDmd :: CoreExpr -> Demand -> Demand
dmdTransformThunkDmd e
| exprIsTrivial e = id
| otherwise = oneifyDmd
-- Do not process absent demands
-- Otherwise act like in a normal demand analysis
-- See |-* relation in the companion paper
dmdAnalStar :: AnalEnv
-> Demand -- This one takes a *Demand*
-> CoreExpr -> (BothDmdArg, CoreExpr)
dmdAnalStar env dmd e
| (cd, defer_and_use) <- toCleanDmd dmd (exprType e)
, (dmd_ty, e') <- dmdAnal env cd e
= (postProcessDmdTypeM defer_and_use dmd_ty, e')
-- Main Demand Analsysis machinery
dmdAnal, dmdAnal' :: AnalEnv
-> CleanDemand -- The main one takes a *CleanDemand*
-> CoreExpr -> (DmdType, CoreExpr)
-- The CleanDemand is always strict and not absent
-- See Note [Ensure demand is strict]
dmdAnal env d e = -- pprTrace "dmdAnal" (ppr d <+> ppr e) $
dmdAnal' env d e
dmdAnal' _ _ (Lit lit) = (nopDmdType, Lit lit)
dmdAnal' _ _ (Type ty) = (nopDmdType, Type ty) -- Doesn't happen, in fact
dmdAnal' _ _ (Coercion co)
= (unitDmdType (coercionDmdEnv co), Coercion co)
dmdAnal' env dmd (Var var)
= (dmdTransform env var dmd, Var var)
dmdAnal' env dmd (Cast e co)
= (dmd_ty `bothDmdType` mkBothDmdArg (coercionDmdEnv co), Cast e' co)
where
(dmd_ty, e') = dmdAnal env dmd e
{- ----- I don't get this, so commenting out -------
to_co = pSnd (coercionKind co)
dmd'
| Just tc <- tyConAppTyCon_maybe to_co
, isRecursiveTyCon tc = cleanEvalDmd
| otherwise = dmd
-- This coerce usually arises from a recursive
-- newtype, and we don't want to look inside them
-- for exactly the same reason that we don't look
-- inside recursive products -- we might not reach
-- a fixpoint. So revert to a vanilla Eval demand
-}
dmdAnal' env dmd (Tick t e)
= (dmd_ty, Tick t e')
where
(dmd_ty, e') = dmdAnal env dmd e
dmdAnal' env dmd (App fun (Type ty))
= (fun_ty, App fun' (Type ty))
where
(fun_ty, fun') = dmdAnal env dmd fun
-- Lots of the other code is there to make this
-- beautiful, compositional, application rule :-)
dmdAnal' env dmd (App fun arg)
= -- This case handles value arguments (type args handled above)
-- Crucially, coercions /are/ handled here, because they are
-- value arguments (Trac #10288)
let
call_dmd = mkCallDmd dmd
(fun_ty, fun') = dmdAnal env call_dmd fun
(arg_dmd, res_ty) = splitDmdTy fun_ty
(arg_ty, arg') = dmdAnalStar env (dmdTransformThunkDmd arg arg_dmd) arg
in
-- pprTrace "dmdAnal:app" (vcat
-- [ text "dmd =" <+> ppr dmd
-- , text "expr =" <+> ppr (App fun arg)
-- , text "fun dmd_ty =" <+> ppr fun_ty
-- , text "arg dmd =" <+> ppr arg_dmd
-- , text "arg dmd_ty =" <+> ppr arg_ty
-- , text "res dmd_ty =" <+> ppr res_ty
-- , text "overall res dmd_ty =" <+> ppr (res_ty `bothDmdType` arg_ty) ])
(res_ty `bothDmdType` arg_ty, App fun' arg')
-- this is an anonymous lambda, since @dmdAnalRhs@ uses @collectBinders@
dmdAnal' env dmd (Lam var body)
| isTyVar var
= let
(body_ty, body') = dmdAnal env dmd body
in
(body_ty, Lam var body')
| otherwise
= let (body_dmd, defer_and_use@(_,one_shot)) = peelCallDmd dmd
-- body_dmd - a demand to analyze the body
-- one_shot - one-shotness of the lambda
-- hence, cardinality of its free vars
env' = extendSigsWithLam env var
(body_ty, body') = dmdAnal env' body_dmd body
(lam_ty, var') = annotateLamIdBndr env notArgOfDfun body_ty one_shot var
in
(postProcessUnsat defer_and_use lam_ty, Lam var' body')
dmdAnal' env dmd (Case scrut case_bndr ty [(DataAlt dc, bndrs, rhs)])
-- Only one alternative with a product constructor
| let tycon = dataConTyCon dc
, isJust (isDataProductTyCon_maybe tycon)
, Just rec_tc' <- checkRecTc (ae_rec_tc env) tycon
= let
env_w_tc = env { ae_rec_tc = rec_tc' }
env_alt = extendAnalEnv NotTopLevel env_w_tc case_bndr case_bndr_sig
case_bndr_sig = cprProdSig (dataConRepArity dc)
-- cprProdSig: inside the alternative, the case binder has the CPR property.
-- Meaning that a case on it will successfully cancel.
-- Example:
-- f True x = case x of y { I# x' -> if x' ==# 3 then y else I# 8 }
-- f False x = I# 3
--
-- We want f to have the CPR property:
-- f b x = case fw b x of { r -> I# r }
-- fw True x = case x of y { I# x' -> if x' ==# 3 then x' else 8 }
-- fw False x = 3
(rhs_ty, rhs') = dmdAnal env_alt dmd rhs
(alt_ty1, dmds) = findBndrsDmds env rhs_ty bndrs
(alt_ty2, case_bndr_dmd) = findBndrDmd env False alt_ty1 case_bndr
id_dmds = addCaseBndrDmd case_bndr_dmd dmds
alt_ty3 | io_hack_reqd dc bndrs = deferAfterIO alt_ty2
| otherwise = alt_ty2
-- Compute demand on the scrutinee
-- See Note [Demand on scrutinee of a product case]
scrut_dmd = mkProdDmd (addDataConStrictness dc id_dmds)
(scrut_ty, scrut') = dmdAnal env scrut_dmd scrut
res_ty = alt_ty3 `bothDmdType` toBothDmdArg scrut_ty
case_bndr' = setIdDemandInfo case_bndr case_bndr_dmd
bndrs' = setBndrsDemandInfo bndrs id_dmds
in
-- pprTrace "dmdAnal:Case1" (vcat [ text "scrut" <+> ppr scrut
-- , text "dmd" <+> ppr dmd
-- , text "case_bndr_dmd" <+> ppr (idDemandInfo case_bndr')
-- , text "scrut_dmd" <+> ppr scrut_dmd
-- , text "scrut_ty" <+> ppr scrut_ty
-- , text "alt_ty" <+> ppr alt_ty2
-- , text "res_ty" <+> ppr res_ty ]) $
(res_ty, Case scrut' case_bndr' ty [(DataAlt dc, bndrs', rhs')])
dmdAnal' env dmd (Case scrut case_bndr ty alts)
= let -- Case expression with multiple alternatives
(alt_tys, alts') = mapAndUnzip (dmdAnalAlt env dmd case_bndr) alts
(scrut_ty, scrut') = dmdAnal env cleanEvalDmd scrut
(alt_ty, case_bndr') = annotateBndr env (foldr lubDmdType botDmdType alt_tys) case_bndr
-- NB: Base case is botDmdType, for empty case alternatives
-- This is a unit for lubDmdType, and the right result
-- when there really are no alternatives
res_ty = alt_ty `bothDmdType` toBothDmdArg scrut_ty
in
-- pprTrace "dmdAnal:Case2" (vcat [ text "scrut" <+> ppr scrut
-- , text "scrut_ty" <+> ppr scrut_ty
-- , text "alt_tys" <+> ppr alt_tys
-- , text "alt_ty" <+> ppr alt_ty
-- , text "res_ty" <+> ppr res_ty ]) $
(res_ty, Case scrut' case_bndr' ty alts')
dmdAnal' env dmd (Let (NonRec id rhs) body)
= (body_ty2, Let (NonRec id2 annotated_rhs) body')
where
(sig, lazy_fv, id1, rhs') = dmdAnalRhs NotTopLevel Nothing env id rhs
(body_ty, body') = dmdAnal (extendAnalEnv NotTopLevel env id sig) dmd body
(body_ty1, id2) = annotateBndr env body_ty id1
body_ty2 = addLazyFVs body_ty1 lazy_fv
-- Annotate top-level lambdas at RHS basing on the aggregated demand info
-- See Note [Annotating lambdas at right-hand side]
annotated_rhs = annLamWithShotness (idDemandInfo id2) rhs'
-- If the actual demand is better than the vanilla call
-- demand, you might think that we might do better to re-analyse
-- the RHS with the stronger demand.
-- But (a) That seldom happens, because it means that *every* path in
-- the body of the let has to use that stronger demand
-- (b) It often happens temporarily in when fixpointing, because
-- the recursive function at first seems to place a massive demand.
-- But we don't want to go to extra work when the function will
-- probably iterate to something less demanding.
-- In practice, all the times the actual demand on id2 is more than
-- the vanilla call demand seem to be due to (b). So we don't
-- bother to re-analyse the RHS.
dmdAnal' env dmd (Let (Rec pairs) body)
= let
(env', lazy_fv, pairs') = dmdFix NotTopLevel env pairs
(body_ty, body') = dmdAnal env' dmd body
body_ty1 = deleteFVs body_ty (map fst pairs)
body_ty2 = addLazyFVs body_ty1 lazy_fv
in
body_ty2 `seq`
(body_ty2, Let (Rec pairs') body')
io_hack_reqd :: DataCon -> [Var] -> Bool
-- Note [IO hack in the demand analyser]
--
-- There's a hack here for I/O operations. Consider
-- case foo x s of { (# s, r #) -> y }
-- Is this strict in 'y'. Normally yes, but what if 'foo' is an I/O
-- operation that simply terminates the program (not in an erroneous way)?
-- In that case we should not evaluate 'y' before the call to 'foo'.
-- Hackish solution: spot the IO-like situation and add a virtual branch,
-- as if we had
-- case foo x s of
-- (# s, r #) -> y
-- other -> return ()
-- So the 'y' isn't necessarily going to be evaluated
--
-- A more complete example (Trac #148, #1592) where this shows up is:
-- do { let len = <expensive> ;
-- ; when (...) (exitWith ExitSuccess)
-- ; print len }
io_hack_reqd con bndrs
| (bndr:_) <- bndrs
= con == unboxedPairDataCon &&
idType bndr `eqType` realWorldStatePrimTy
| otherwise
= False
annLamWithShotness :: Demand -> CoreExpr -> CoreExpr
annLamWithShotness d e
| Just u <- cleanUseDmd_maybe d
= go u e
| otherwise = e
where
go u e
| Just (c, u') <- peelUseCall u
, Lam bndr body <- e
= if isTyVar bndr
then Lam bndr (go u body)
else Lam (setOneShotness c bndr) (go u' body)
| otherwise
= e
setOneShotness :: Count -> Id -> Id
setOneShotness One bndr = setOneShotLambda bndr
setOneShotness Many bndr = bndr
dmdAnalAlt :: AnalEnv -> CleanDemand -> Id -> Alt Var -> (DmdType, Alt Var)
dmdAnalAlt env dmd case_bndr (con,bndrs,rhs)
| null bndrs -- Literals, DEFAULT, and nullary constructors
, (rhs_ty, rhs') <- dmdAnal env dmd rhs
= (rhs_ty, (con, [], rhs'))
| otherwise -- Non-nullary data constructors
, (rhs_ty, rhs') <- dmdAnal env dmd rhs
, (alt_ty, dmds) <- findBndrsDmds env rhs_ty bndrs
, let case_bndr_dmd = findIdDemand alt_ty case_bndr
id_dmds = addCaseBndrDmd case_bndr_dmd dmds
= (alt_ty, (con, setBndrsDemandInfo bndrs id_dmds, rhs'))
{- Note [Demand on the scrutinee of a product case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When figuring out the demand on the scrutinee of a product case,
we use the demands of the case alternative, i.e. id_dmds.
But note that these include the demand on the case binder;
see Note [Demand on case-alternative binders] in Demand.hs.
This is crucial. Example:
f x = case x of y { (a,b) -> k y a }
If we just take scrut_demand = U(L,A), then we won't pass x to the
worker, so the worker will rebuild
x = (a, absent-error)
and that'll crash.
Note [Aggregated demand for cardinality]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We use different strategies for strictness and usage/cardinality to
"unleash" demands captured on free variables by bindings. Let us
consider the example:
f1 y = let {-# NOINLINE h #-}
h = y
in (h, h)
We are interested in obtaining cardinality demand U1 on |y|, as it is
used only in a thunk, and, therefore, is not going to be updated any
more. Therefore, the demand on |y|, captured and unleashed by usage of
|h| is U1. However, if we unleash this demand every time |h| is used,
and then sum up the effects, the ultimate demand on |y| will be U1 +
U1 = U. In order to avoid it, we *first* collect the aggregate demand
on |h| in the body of let-expression, and only then apply the demand
transformer:
transf[x](U) = {y |-> U1}
so the resulting demand on |y| is U1.
The situation is, however, different for strictness, where this
aggregating approach exhibits worse results because of the nature of
|both| operation for strictness. Consider the example:
f y c =
let h x = y |seq| x
in case of
True -> h True
False -> y
It is clear that |f| is strict in |y|, however, the suggested analysis
will infer from the body of |let| that |h| is used lazily (as it is
used in one branch only), therefore lazy demand will be put on its
free variable |y|. Conversely, if the demand on |h| is unleashed right
on the spot, we will get the desired result, namely, that |f| is
strict in |y|.
Note [Annotating lambdas at right-hand side]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Let us take a look at the following example:
g f = let x = 100
h = \y -> f x y
in h 5
One can see that |h| is called just once, therefore the RHS of h can
be annotated as a one-shot lambda. This is done by the function
annLamWithShotness *a posteriori*, i.e., basing on the aggregated
usage demand on |h| from the body of |let|-expression, which is C1(U)
in this case.
In other words, for locally-bound lambdas we can infer
one-shotness.
-}
{-
Note [Add demands for strict constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this program (due to Roman):
data X a = X !a
foo :: X Int -> Int -> Int
foo (X a) n = go 0
where
go i | i < n = a + go (i+1)
| otherwise = 0
We want the worker for 'foo' too look like this:
$wfoo :: Int# -> Int# -> Int#
with the first argument unboxed, so that it is not eval'd each time
around the 'go' loop (which would otherwise happen, since 'foo' is not
strict in 'a'). It is sound for the wrapper to pass an unboxed arg
because X is strict, so its argument must be evaluated. And if we
*don't* pass an unboxed argument, we can't even repair it by adding a
`seq` thus:
foo (X a) n = a `seq` go 0
because the seq is discarded (very early) since X is strict!
There is the usual danger of reboxing, which as usual we ignore. But
if X is monomorphic, and has an UNPACK pragma, then this optimisation
is even more important. We don't want the wrapper to rebox an unboxed
argument, and pass an Int to $wfoo!
We add these extra strict demands to the demand on the *scrutinee* of
the case expression; hence the use of addDataConStrictness when
forming scrut_dmd. The case alternatives aren't strict in their
sub-components, but simply evaluating the scrutinee to HNF does force
those sub-components.
************************************************************************
* *
Demand transformer
* *
************************************************************************
-}
dmdTransform :: AnalEnv -- The strictness environment
-> Id -- The function
-> CleanDemand -- The demand on the function
-> DmdType -- The demand type of the function in this context
-- Returned DmdEnv includes the demand on
-- this function plus demand on its free variables
dmdTransform env var dmd
| isDataConWorkId var -- Data constructor
= dmdTransformDataConSig (idArity var) (idStrictness var) dmd
| gopt Opt_DmdTxDictSel (ae_dflags env),
Just _ <- isClassOpId_maybe var -- Dictionary component selector
= dmdTransformDictSelSig (idStrictness var) dmd
| isGlobalId var -- Imported function
= let res = dmdTransformSig (idStrictness var) dmd in
-- pprTrace "dmdTransform" (vcat [ppr var, ppr (idStrictness var), ppr dmd, ppr res])
res
| Just (sig, top_lvl) <- lookupSigEnv env var -- Local letrec bound thing
, let fn_ty = dmdTransformSig sig dmd
= -- pprTrace "dmdTransform" (vcat [ppr var, ppr sig, ppr dmd, ppr fn_ty]) $
if isTopLevel top_lvl
then fn_ty -- Don't record top level things
else addVarDmd fn_ty var (mkOnceUsedDmd dmd)
| otherwise -- Local non-letrec-bound thing
= unitDmdType (unitVarEnv var (mkOnceUsedDmd dmd))
{-
************************************************************************
* *
\subsection{Bindings}
* *
************************************************************************
-}
-- Recursive bindings
dmdFix :: TopLevelFlag
-> AnalEnv -- Does not include bindings for this binding
-> [(Id,CoreExpr)]
-> (AnalEnv, DmdEnv,
[(Id,CoreExpr)]) -- Binders annotated with stricness info
dmdFix top_lvl env orig_pairs
= (updSigEnv env (sigEnv final_env), lazy_fv, pairs')
-- Return to original virgin state, keeping new signatures
where
bndrs = map fst orig_pairs
initial_env = addInitialSigs top_lvl env bndrs
(final_env, lazy_fv, pairs') = loop 1 initial_env orig_pairs
loop :: Int
-> AnalEnv -- Already contains the current sigs
-> [(Id,CoreExpr)]
-> (AnalEnv, DmdEnv, [(Id,CoreExpr)])
loop n env pairs
= -- pprTrace "dmd loop" (ppr n <+> ppr bndrs $$ ppr env) $
loop' n env pairs
loop' n env pairs
| found_fixpoint
= (env', lazy_fv, pairs')
-- Note: return pairs', not pairs. pairs' is the result of
-- processing the RHSs with sigs (= sigs'), whereas pairs
-- is the result of processing the RHSs with the *previous*
-- iteration of sigs.
| n >= 10
= -- pprTrace "dmdFix loop" (ppr n <+> (vcat
-- [ text "Sigs:" <+> ppr [ (id,lookupVarEnv (sigEnv env) id,
-- lookupVarEnv (sigEnv env') id)
-- | (id,_) <- pairs],
-- text "env:" <+> ppr env,
-- text "binds:" <+> pprCoreBinding (Rec pairs)]))
(env, lazy_fv, orig_pairs) -- Safe output
-- The lazy_fv part is really important! orig_pairs has no strictness
-- info, including nothing about free vars. But if we have
-- letrec f = ....y..... in ...f...
-- where 'y' is free in f, we must record that y is mentioned,
-- otherwise y will get recorded as absent altogether
| otherwise
= loop (n+1) (nonVirgin env') pairs'
where
found_fixpoint = all (same_sig (sigEnv env) (sigEnv env')) bndrs
((env',lazy_fv), pairs') = mapAccumL my_downRhs (env, emptyDmdEnv) pairs
-- mapAccumL: Use the new signature to do the next pair
-- The occurrence analyser has arranged them in a good order
-- so this can significantly reduce the number of iterations needed
my_downRhs (env, lazy_fv) (id,rhs)
= ((env', lazy_fv'), (id', rhs'))
where
(sig, lazy_fv1, id', rhs') = dmdAnalRhs top_lvl (Just bndrs) env id rhs
lazy_fv' = plusVarEnv_C bothDmd lazy_fv lazy_fv1
env' = extendAnalEnv top_lvl env id sig
same_sig sigs sigs' var = lookup sigs var == lookup sigs' var
lookup sigs var = case lookupVarEnv sigs var of
Just (sig,_) -> sig
Nothing -> pprPanic "dmdFix" (ppr var)
-- Non-recursive bindings
dmdAnalRhs :: TopLevelFlag
-> Maybe [Id] -- Just bs <=> recursive, Nothing <=> non-recursive
-> AnalEnv -> Id -> CoreExpr
-> (StrictSig, DmdEnv, Id, CoreExpr)
-- Process the RHS of the binding, add the strictness signature
-- to the Id, and augment the environment with the signature as well.
dmdAnalRhs top_lvl rec_flag env id rhs
| Just fn <- unpackTrivial rhs -- See Note [Demand analysis for trivial right-hand sides]
, let fn_str = getStrictness env fn
fn_fv | isLocalId fn = unitVarEnv fn topDmd
| otherwise = emptyDmdEnv
-- Note [Remember to demand the function itself]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- fn_fv: don't forget to produce a demand for fn itself
-- Lacking this caused Trac #9128
-- The demand is very conservative (topDmd), but that doesn't
-- matter; trivial bindings are usually inlined, so it only
-- kicks in for top-level bindings and NOINLINE bindings
= (fn_str, fn_fv, set_idStrictness env id fn_str, rhs)
| otherwise
= (sig_ty, lazy_fv, id', mkLams bndrs' body')
where
(bndrs, body) = collectBinders rhs
env_body = foldl extendSigsWithLam env bndrs
(body_ty, body') = dmdAnal env_body body_dmd body
body_ty' = removeDmdTyArgs body_ty -- zap possible deep CPR info
(DmdType rhs_fv rhs_dmds rhs_res, bndrs')
= annotateLamBndrs env (isDFunId id) body_ty' bndrs
sig_ty = mkStrictSig (mkDmdType sig_fv rhs_dmds rhs_res')
id' = set_idStrictness env id sig_ty
-- See Note [NOINLINE and strictness]
-- See Note [Product demands for function body]
body_dmd = case deepSplitProductType_maybe (ae_fam_envs env) (exprType body) of
Nothing -> cleanEvalDmd
Just (dc, _, _, _) -> cleanEvalProdDmd (dataConRepArity dc)
-- See Note [Lazy and unleashable free variables]
-- See Note [Aggregated demand for cardinality]
rhs_fv1 = case rec_flag of
Just bs -> reuseEnv (delVarEnvList rhs_fv bs)
Nothing -> rhs_fv
(lazy_fv, sig_fv) = splitFVs is_thunk rhs_fv1
rhs_res' = trimCPRInfo trim_all trim_sums rhs_res
trim_all = is_thunk && not_strict
trim_sums = not (isTopLevel top_lvl) -- See Note [CPR for sum types]
-- See Note [CPR for thunks]
is_thunk = not (exprIsHNF rhs)
not_strict
= isTopLevel top_lvl -- Top level and recursive things don't
|| isJust rec_flag -- get their demandInfo set at all
|| not (isStrictDmd (idDemandInfo id) || ae_virgin env)
-- See Note [Optimistic CPR in the "virgin" case]
unpackTrivial :: CoreExpr -> Maybe Id
-- Returns (Just v) if the arg is really equal to v, modulo
-- casts, type applications etc
-- See Note [Demand analysis for trivial right-hand sides]
unpackTrivial (Var v) = Just v
unpackTrivial (Cast e _) = unpackTrivial e
unpackTrivial (Lam v e) | isTyVar v = unpackTrivial e
unpackTrivial (App e a) | isTypeArg a = unpackTrivial e
unpackTrivial _ = Nothing
{-
Note [Demand analysis for trivial right-hand sides]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
foo = plusInt |> co
where plusInt is an arity-2 function with known strictness. Clearly
we want plusInt's strictness to propagate to foo! But because it has
no manifest lambdas, it won't do so automatically, and indeed 'co' might
have type (Int->Int->Int) ~ T, so we *can't* eta-expand. So we have a
special case for right-hand sides that are "trivial", namely variables,
casts, type applications, and the like.
Note that this can mean that 'foo' has an arity that is smaller than that
indicated by its demand info. e.g. if co :: (Int->Int->Int) ~ T, then
foo's arity will be zero (see Note [exprArity invariant] in CoreArity),
but its demand signature will be that of plusInt. A small example is the
test case of Trac #8963.
Note [Product demands for function body]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This example comes from shootout/binary_trees:
Main.check' = \ b z ds. case z of z' { I# ip ->
case ds_d13s of
Main.Nil -> z'
Main.Node s14k s14l s14m ->
Main.check' (not b)
(Main.check' b
(case b {
False -> I# (-# s14h s14k);
True -> I# (+# s14h s14k)
})
s14l)
s14m } } }
Here we *really* want to unbox z, even though it appears to be used boxed in
the Nil case. Partly the Nil case is not a hot path. But more specifically,
the whole function gets the CPR property if we do.
So for the demand on the body of a RHS we use a product demand if it's
a product type.
************************************************************************
* *
\subsection{Strictness signatures and types}
* *
************************************************************************
-}
unitDmdType :: DmdEnv -> DmdType
unitDmdType dmd_env = DmdType dmd_env [] topRes
coercionDmdEnv :: Coercion -> DmdEnv
coercionDmdEnv co = mapVarEnv (const topDmd) (coVarsOfCo co)
-- The VarSet from coVarsOfCo is really a VarEnv Var
addVarDmd :: DmdType -> Var -> Demand -> DmdType
addVarDmd (DmdType fv ds res) var dmd
= DmdType (extendVarEnv_C bothDmd fv var dmd) ds res
addLazyFVs :: DmdType -> DmdEnv -> DmdType
addLazyFVs dmd_ty lazy_fvs
= dmd_ty `bothDmdType` mkBothDmdArg lazy_fvs
-- Using bothDmdType (rather than just both'ing the envs)
-- is vital. Consider
-- let f = \x -> (x,y)
-- in error (f 3)
-- Here, y is treated as a lazy-fv of f, but we must `bothDmd` that L
-- demand with the bottom coming up from 'error'
--
-- I got a loop in the fixpointer without this, due to an interaction
-- with the lazy_fv filtering in dmdAnalRhs. Roughly, it was
-- letrec f n x
-- = letrec g y = x `fatbar`
-- letrec h z = z + ...g...
-- in h (f (n-1) x)
-- in ...
-- In the initial iteration for f, f=Bot
-- Suppose h is found to be strict in z, but the occurrence of g in its RHS
-- is lazy. Now consider the fixpoint iteration for g, esp the demands it
-- places on its free variables. Suppose it places none. Then the
-- x `fatbar` ...call to h...
-- will give a x->V demand for x. That turns into a L demand for x,
-- which floats out of the defn for h. Without the modifyEnv, that
-- L demand doesn't get both'd with the Bot coming up from the inner
-- call to f. So we just get an L demand for x for g.
{-
Note [Do not strictify the argument dictionaries of a dfun]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The typechecker can tie recursive knots involving dfuns, so we do the
conservative thing and refrain from strictifying a dfun's argument
dictionaries.
-}
setBndrsDemandInfo :: [Var] -> [Demand] -> [Var]
setBndrsDemandInfo (b:bs) (d:ds)
| isTyVar b = b : setBndrsDemandInfo bs (d:ds)
| otherwise = setIdDemandInfo b d : setBndrsDemandInfo bs ds
setBndrsDemandInfo [] ds = ASSERT( null ds ) []
setBndrsDemandInfo bs _ = pprPanic "setBndrsDemandInfo" (ppr bs)
annotateBndr :: AnalEnv -> DmdType -> Var -> (DmdType, Var)
-- The returned env has the var deleted
-- The returned var is annotated with demand info
-- according to the result demand of the provided demand type
-- No effect on the argument demands
annotateBndr env dmd_ty var
| isId var = (dmd_ty', setIdDemandInfo var dmd)
| otherwise = (dmd_ty, var)
where
(dmd_ty', dmd) = findBndrDmd env False dmd_ty var
annotateLamBndrs :: AnalEnv -> DFunFlag -> DmdType -> [Var] -> (DmdType, [Var])
annotateLamBndrs env args_of_dfun ty bndrs = mapAccumR annotate ty bndrs
where
annotate dmd_ty bndr
| isId bndr = annotateLamIdBndr env args_of_dfun dmd_ty Many bndr
| otherwise = (dmd_ty, bndr)
annotateLamIdBndr :: AnalEnv
-> DFunFlag -- is this lambda at the top of the RHS of a dfun?
-> DmdType -- Demand type of body
-> Count -- One-shot-ness of the lambda
-> Id -- Lambda binder
-> (DmdType, -- Demand type of lambda
Id) -- and binder annotated with demand
annotateLamIdBndr env arg_of_dfun dmd_ty one_shot id
-- For lambdas we add the demand to the argument demands
-- Only called for Ids
= ASSERT( isId id )
-- pprTrace "annLamBndr" (vcat [ppr id, ppr _dmd_ty]) $
(final_ty, setOneShotness one_shot (setIdDemandInfo id dmd))
where
-- Watch out! See note [Lambda-bound unfoldings]
final_ty = case maybeUnfoldingTemplate (idUnfolding id) of
Nothing -> main_ty
Just unf -> main_ty `bothDmdType` unf_ty
where
(unf_ty, _) = dmdAnalStar env dmd unf
main_ty = addDemand dmd dmd_ty'
(dmd_ty', dmd) = findBndrDmd env arg_of_dfun dmd_ty id
deleteFVs :: DmdType -> [Var] -> DmdType
deleteFVs (DmdType fvs dmds res) bndrs
= DmdType (delVarEnvList fvs bndrs) dmds res
{-
Note [CPR for sum types]
~~~~~~~~~~~~~~~~~~~~~~~~
At the moment we do not do CPR for let-bindings that
* non-top level
* bind a sum type
Reason: I found that in some benchmarks we were losing let-no-escapes,
which messed it all up. Example
let j = \x. ....
in case y of
True -> j False
False -> j True
If we w/w this we get
let j' = \x. ....
in case y of
True -> case j' False of { (# a #) -> Just a }
False -> case j' True of { (# a #) -> Just a }
Notice that j' is not a let-no-escape any more.
However this means in turn that the *enclosing* function
may be CPR'd (via the returned Justs). But in the case of
sums, there may be Nothing alternatives; and that messes
up the sum-type CPR.
Conclusion: only do this for products. It's still not
guaranteed OK for products, but sums definitely lose sometimes.
Note [CPR for thunks]
~~~~~~~~~~~~~~~~~~~~~
If the rhs is a thunk, we usually forget the CPR info, because
it is presumably shared (else it would have been inlined, and
so we'd lose sharing if w/w'd it into a function). E.g.
let r = case expensive of
(a,b) -> (b,a)
in ...
If we marked r as having the CPR property, then we'd w/w into
let $wr = \() -> case expensive of
(a,b) -> (# b, a #)
r = case $wr () of
(# b,a #) -> (b,a)
in ...
But now r is a thunk, which won't be inlined, so we are no further ahead.
But consider
f x = let r = case expensive of (a,b) -> (b,a)
in if foo r then r else (x,x)
Does f have the CPR property? Well, no.
However, if the strictness analyser has figured out (in a previous
iteration) that it's strict, then we DON'T need to forget the CPR info.
Instead we can retain the CPR info and do the thunk-splitting transform
(see WorkWrap.splitThunk).
This made a big difference to PrelBase.modInt, which had something like
modInt = \ x -> let r = ... -> I# v in
...body strict in r...
r's RHS isn't a value yet; but modInt returns r in various branches, so
if r doesn't have the CPR property then neither does modInt
Another case I found in practice (in Complex.magnitude), looks like this:
let k = if ... then I# a else I# b
in ... body strict in k ....
(For this example, it doesn't matter whether k is returned as part of
the overall result; but it does matter that k's RHS has the CPR property.)
Left to itself, the simplifier will make a join point thus:
let $j k = ...body strict in k...
if ... then $j (I# a) else $j (I# b)
With thunk-splitting, we get instead
let $j x = let k = I#x in ...body strict in k...
in if ... then $j a else $j b
This is much better; there's a good chance the I# won't get allocated.
The difficulty with this is that we need the strictness type to
look at the body... but we now need the body to calculate the demand
on the variable, so we can decide whether its strictness type should
have a CPR in it or not. Simple solution:
a) use strictness info from the previous iteration
b) make sure we do at least 2 iterations, by doing a second
round for top-level non-recs. Top level recs will get at
least 2 iterations except for totally-bottom functions
which aren't very interesting anyway.
NB: strictly_demanded is never true of a top-level Id, or of a recursive Id.
Note [Optimistic CPR in the "virgin" case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demand and strictness info are initialized by top elements. However,
this prevents from inferring a CPR property in the first pass of the
analyser, so we keep an explicit flag ae_virgin in the AnalEnv
datatype.
We can't start with 'not-demanded' (i.e., top) because then consider
f x = let
t = ... I# x
in
if ... then t else I# y else f x'
In the first iteration we'd have no demand info for x, so assume
not-demanded; then we'd get TopRes for f's CPR info. Next iteration
we'd see that t was demanded, and so give it the CPR property, but by
now f has TopRes, so it will stay TopRes. Instead, by checking the
ae_virgin flag at the first time round, we say 'yes t is demanded' the
first time.
However, this does mean that for non-recursive bindings we must
iterate twice to be sure of not getting over-optimistic CPR info,
in the case where t turns out to be not-demanded. This is handled
by dmdAnalTopBind.
Note [NOINLINE and strictness]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The strictness analyser used to have a HACK which ensured that NOINLNE
things were not strictness-analysed. The reason was unsafePerformIO.
Left to itself, the strictness analyser would discover this strictness
for unsafePerformIO:
unsafePerformIO: C(U(AV))
But then consider this sub-expression
unsafePerformIO (\s -> let r = f x in
case writeIORef v r s of (# s1, _ #) ->
(# s1, r #)
The strictness analyser will now find that r is sure to be eval'd,
and may then hoist it out. This makes tests/lib/should_run/memo002
deadlock.
Solving this by making all NOINLINE things have no strictness info is overkill.
In particular, it's overkill for runST, which is perfectly respectable.
Consider
f x = runST (return x)
This should be strict in x.
So the new plan is to define unsafePerformIO using the 'lazy' combinator:
unsafePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
Remember, 'lazy' is a wired-in identity-function Id, of type a->a, which is
magically NON-STRICT, and is inlined after strictness analysis. So
unsafePerformIO will look non-strict, and that's what we want.
Now we don't need the hack in the strictness analyser. HOWEVER, this
decision does mean that even a NOINLINE function is not entirely
opaque: some aspect of its implementation leaks out, notably its
strictness. For example, if you have a function implemented by an
error stub, but which has RULES, you may want it not to be eliminated
in favour of error!
Note [Lazy and unleasheable free variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We put the strict and once-used FVs in the DmdType of the Id, so
that at its call sites we unleash demands on its strict fvs.
An example is 'roll' in imaginary/wheel-sieve2
Something like this:
roll x = letrec
go y = if ... then roll (x-1) else x+1
in
go ms
We want to see that roll is strict in x, which is because
go is called. So we put the DmdEnv for x in go's DmdType.
Another example:
f :: Int -> Int -> Int
f x y = let t = x+1
h z = if z==0 then t else
if z==1 then x+1 else
x + h (z-1)
in h y
Calling h does indeed evaluate x, but we can only see
that if we unleash a demand on x at the call site for t.
Incidentally, here's a place where lambda-lifting h would
lose the cigar --- we couldn't see the joint strictness in t/x
ON THE OTHER HAND
We don't want to put *all* the fv's from the RHS into the
DmdType, because that makes fixpointing very slow --- the
DmdType gets full of lazy demands that are slow to converge.
Note [Lamba-bound unfoldings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We allow a lambda-bound variable to carry an unfolding, a facility that is used
exclusively for join points; see Note [Case binders and join points]. If so,
we must be careful to demand-analyse the RHS of the unfolding! Example
\x. \y{=Just x}. <body>
Then if <body> uses 'y', then transitively it uses 'x', and we must not
forget that fact, otherwise we might make 'x' absent when it isn't.
************************************************************************
* *
\subsection{Strictness signatures}
* *
************************************************************************
-}
type DFunFlag = Bool -- indicates if the lambda being considered is in the
-- sequence of lambdas at the top of the RHS of a dfun
notArgOfDfun :: DFunFlag
notArgOfDfun = False
data AnalEnv
= AE { ae_dflags :: DynFlags
, ae_sigs :: SigEnv
, ae_virgin :: Bool -- True on first iteration only
-- See Note [Initialising strictness]
, ae_rec_tc :: RecTcChecker
, ae_fam_envs :: FamInstEnvs
}
-- We use the se_env to tell us whether to
-- record info about a variable in the DmdEnv
-- We do so if it's a LocalId, but not top-level
--
-- The DmdEnv gives the demand on the free vars of the function
-- when it is given enough args to satisfy the strictness signature
type SigEnv = VarEnv (StrictSig, TopLevelFlag)
instance Outputable AnalEnv where
ppr (AE { ae_sigs = env, ae_virgin = virgin })
= ptext (sLit "AE") <+> braces (vcat
[ ptext (sLit "ae_virgin =") <+> ppr virgin
, ptext (sLit "ae_sigs =") <+> ppr env ])
emptyAnalEnv :: DynFlags -> FamInstEnvs -> AnalEnv
emptyAnalEnv dflags fam_envs
= AE { ae_dflags = dflags
, ae_sigs = emptySigEnv
, ae_virgin = True
, ae_rec_tc = initRecTc
, ae_fam_envs = fam_envs
}
emptySigEnv :: SigEnv
emptySigEnv = emptyVarEnv
sigEnv :: AnalEnv -> SigEnv
sigEnv = ae_sigs
updSigEnv :: AnalEnv -> SigEnv -> AnalEnv
updSigEnv env sigs = env { ae_sigs = sigs }
extendAnalEnv :: TopLevelFlag -> AnalEnv -> Id -> StrictSig -> AnalEnv
extendAnalEnv top_lvl env var sig
= env { ae_sigs = extendSigEnv top_lvl (ae_sigs env) var sig }
extendSigEnv :: TopLevelFlag -> SigEnv -> Id -> StrictSig -> SigEnv
extendSigEnv top_lvl sigs var sig = extendVarEnv sigs var (sig, top_lvl)
lookupSigEnv :: AnalEnv -> Id -> Maybe (StrictSig, TopLevelFlag)
lookupSigEnv env id = lookupVarEnv (ae_sigs env) id
getStrictness :: AnalEnv -> Id -> StrictSig
getStrictness env fn
| isGlobalId fn = idStrictness fn
| Just (sig, _) <- lookupSigEnv env fn = sig
| otherwise = nopSig
addInitialSigs :: TopLevelFlag -> AnalEnv -> [Id] -> AnalEnv
-- See Note [Initialising strictness]
addInitialSigs top_lvl env@(AE { ae_sigs = sigs, ae_virgin = virgin }) ids
= env { ae_sigs = extendVarEnvList sigs [ (id, (init_sig id, top_lvl))
| id <- ids ] }
where
init_sig | virgin = \_ -> botSig
| otherwise = idStrictness
nonVirgin :: AnalEnv -> AnalEnv
nonVirgin env = env { ae_virgin = False }
extendSigsWithLam :: AnalEnv -> Id -> AnalEnv
-- Extend the AnalEnv when we meet a lambda binder
extendSigsWithLam env id
| isId id
, isStrictDmd (idDemandInfo id) || ae_virgin env
-- See Note [Optimistic CPR in the "virgin" case]
-- See Note [Initial CPR for strict binders]
, Just (dc,_,_,_) <- deepSplitProductType_maybe (ae_fam_envs env) $ idType id
= extendAnalEnv NotTopLevel env id (cprProdSig (dataConRepArity dc))
| otherwise
= env
addDataConStrictness :: DataCon -> [Demand] -> [Demand]
-- See Note [Add demands for strict constructors]
addDataConStrictness con ds
= ASSERT2( equalLength strs ds, ppr con $$ ppr strs $$ ppr ds )
zipWith add ds strs
where
strs = dataConRepStrictness con
add dmd str | isMarkedStrict str = dmd `bothDmd` seqDmd
| otherwise = dmd
-- Yes, even if 'dmd' is Absent!
findBndrsDmds :: AnalEnv -> DmdType -> [Var] -> (DmdType, [Demand])
-- Return the demands on the Ids in the [Var]
findBndrsDmds env dmd_ty bndrs
= go dmd_ty bndrs
where
go dmd_ty [] = (dmd_ty, [])
go dmd_ty (b:bs)
| isId b = let (dmd_ty1, dmds) = go dmd_ty bs
(dmd_ty2, dmd) = findBndrDmd env False dmd_ty1 b
in (dmd_ty2, dmd : dmds)
| otherwise = go dmd_ty bs
findBndrDmd :: AnalEnv -> Bool -> DmdType -> Id -> (DmdType, Demand)
-- See Note [Trimming a demand to a type] in Demand.hs
findBndrDmd env arg_of_dfun dmd_ty id
= (dmd_ty', dmd')
where
dmd' = killUsageDemand (ae_dflags env) $
strictify $
trimToType starting_dmd (findTypeShape fam_envs id_ty)
(dmd_ty', starting_dmd) = peelFV dmd_ty id
id_ty = idType id
strictify dmd
| gopt Opt_DictsStrict (ae_dflags env)
-- We never want to strictify a recursive let. At the moment
-- annotateBndr is only call for non-recursive lets; if that
-- changes, we need a RecFlag parameter and another guard here.
, not arg_of_dfun -- See Note [Do not strictify the argument dictionaries of a dfun]
= strictifyDictDmd id_ty dmd
| otherwise
= dmd
fam_envs = ae_fam_envs env
set_idStrictness :: AnalEnv -> Id -> StrictSig -> Id
set_idStrictness env id sig
= setIdStrictness id (killUsageSig (ae_dflags env) sig)
dumpStrSig :: CoreProgram -> SDoc
dumpStrSig binds = vcat (map printId ids)
where
ids = sortBy (stableNameCmp `on` getName) (concatMap getIds binds)
getIds (NonRec i _) = [ i ]
getIds (Rec bs) = map fst bs
printId id | isExportedId id = ppr id <> colon <+> pprIfaceStrictSig (idStrictness id)
| otherwise = empty
{-
Note [Initial CPR for strict binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CPR is initialized for a lambda binder in an optimistic manner, i.e,
if the binder is used strictly and at least some of its components as
a product are used, which is checked by the value of the absence
demand.
If the binder is marked demanded with a strict demand, then give it a
CPR signature, because in the likely event that this is a lambda on a
fn defn [we only use this when the lambda is being consumed with a
call demand], it'll be w/w'd and so it will be CPR-ish. E.g.
f = \x::(Int,Int). if ...strict in x... then
x
else
(a,b)
We want f to have the CPR property because x does, by the time f has been w/w'd
Also note that we only want to do this for something that definitely
has product type, else we may get over-optimistic CPR results
(e.g. from \x -> x!).
Note [Initialising strictness]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See section 9.2 (Finding fixpoints) of the paper.
Our basic plan is to initialise the strictness of each Id in a
recursive group to "bottom", and find a fixpoint from there. However,
this group B might be inside an *enclosing* recursiveb group A, in
which case we'll do the entire fixpoint shebang on for each iteration
of A. This can be illustrated by the following example:
Example:
f [] = []
f (x:xs) = let g [] = f xs
g (y:ys) = y+1 : g ys
in g (h x)
At each iteration of the fixpoint for f, the analyser has to find a
fixpoint for the enclosed function g. In the meantime, the demand
values for g at each iteration for f are *greater* than those we
encountered in the previous iteration for f. Therefore, we can begin
the fixpoint for g not with the bottom value but rather with the
result of the previous analysis. I.e., when beginning the fixpoint
process for g, we can start from the demand signature computed for g
previously and attached to the binding occurrence of g.
To speed things up, we initialise each iteration of A (the enclosing
one) from the result of the last one, which is neatly recorded in each
binder. That way we make use of earlier iterations of the fixpoint
algorithm. (Cunning plan.)
But on the *first* iteration we want to *ignore* the current strictness
of the Id, and start from "bottom". Nowadays the Id can have a current
strictness, because interface files record strictness for nested bindings.
To know when we are in the first iteration, we look at the ae_virgin
field of the AnalEnv.
-}
| christiaanb/ghc | compiler/stranal/DmdAnal.hs | bsd-3-clause | 49,748 | 0 | 14 | 14,581 | 6,054 | 3,225 | 2,829 | 408 | 3 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UnliftedNewtypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeInType #-}
module UnliftedNewtypesLevityBinder where
import GHC.Types (RuntimeRep,TYPE,Coercible)
newtype Ident :: forall (r :: RuntimeRep). TYPE r -> TYPE r where
IdentC :: forall (r :: RuntimeRep) (a :: TYPE r). a -> Ident a
bad :: forall (r :: RuntimeRep) (a :: TYPE r). a -> Ident a
bad = IdentC
| sdiehl/ghc | testsuite/tests/typecheck/should_fail/UnliftedNewtypesLevityBinder.hs | bsd-3-clause | 462 | 0 | 9 | 80 | 125 | 76 | 49 | -1 | -1 |
{-# LANGUAGE GADTs, RecordWildCards, MagicHash, ScopedTypeVariables, CPP,
UnboxedTuples #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
-- |
-- Execute GHCi messages
--
module GHCi.Run
( run, redirectInterrupts
, toSerializableException, fromSerializableException
) where
import GHCi.CreateBCO
import GHCi.InfoTable
import GHCi.FFI
import GHCi.Message
import GHCi.ObjLink
import GHCi.RemoteTypes
import GHCi.TH
import GHCi.BreakArray
import Control.Concurrent
import Control.DeepSeq
import Control.Exception
import Control.Monad
import Data.Binary
import Data.Binary.Get
import Data.ByteString (ByteString)
import qualified Data.ByteString.Unsafe as B
import GHC.Exts
import GHC.Stack
import Foreign
import Foreign.C
import GHC.Conc.Sync
import GHC.IO hiding ( bracket )
import System.Exit
import System.Mem.Weak ( deRefWeak )
import Unsafe.Coerce
-- -----------------------------------------------------------------------------
-- Implement messages
run :: Message a -> IO a
run m = case m of
InitLinker -> initObjLinker
LookupSymbol str -> fmap toRemotePtr <$> lookupSymbol str
LookupClosure str -> lookupClosure str
LoadDLL str -> loadDLL str
LoadArchive str -> loadArchive str
LoadObj str -> loadObj str
UnloadObj str -> unloadObj str
AddLibrarySearchPath str -> toRemotePtr <$> addLibrarySearchPath str
RemoveLibrarySearchPath ptr -> removeLibrarySearchPath (fromRemotePtr ptr)
ResolveObjs -> resolveObjs
FindSystemLibrary str -> findSystemLibrary str
CreateBCOs bcos -> createBCOs (concatMap (runGet get) bcos)
FreeHValueRefs rs -> mapM_ freeRemoteRef rs
EvalStmt opts r -> evalStmt opts r
ResumeStmt opts r -> resumeStmt opts r
AbandonStmt r -> abandonStmt r
EvalString r -> evalString r
EvalStringToString r s -> evalStringToString r s
EvalIO r -> evalIO r
MkCostCentres mod ccs -> mkCostCentres mod ccs
CostCentreStackInfo ptr -> ccsToStrings (fromRemotePtr ptr)
NewBreakArray sz -> mkRemoteRef =<< newBreakArray sz
EnableBreakpoint ref ix b -> do
arr <- localRef ref
_ <- if b then setBreakOn arr ix else setBreakOff arr ix
return ()
BreakpointStatus ref ix -> do
arr <- localRef ref; r <- getBreak arr ix
case r of
Nothing -> return False
Just w -> return (w /= 0)
GetBreakpointVar ref ix -> do
aps <- localRef ref
mapM mkRemoteRef =<< getIdValFromApStack aps ix
MallocData bs -> mkString bs
MallocStrings bss -> mapM mkString0 bss
PrepFFI conv args res -> toRemotePtr <$> prepForeignCall conv args res
FreeFFI p -> freeForeignCallInfo (fromRemotePtr p)
MkConInfoTable ptrs nptrs tag desc ->
toRemotePtr <$> mkConInfoTable ptrs nptrs tag desc
StartTH -> startTH
_other -> error "GHCi.Run.run"
evalStmt :: EvalOpts -> EvalExpr HValueRef -> IO (EvalStatus [HValueRef])
evalStmt opts expr = do
io <- mkIO expr
sandboxIO opts $ do
rs <- unsafeCoerce io :: IO [HValue]
mapM mkRemoteRef rs
where
mkIO (EvalThis href) = localRef href
mkIO (EvalApp l r) = do
l' <- mkIO l
r' <- mkIO r
return ((unsafeCoerce l' :: HValue -> HValue) r')
evalIO :: HValueRef -> IO (EvalResult ())
evalIO r = do
io <- localRef r
tryEval (unsafeCoerce io :: IO ())
evalString :: HValueRef -> IO (EvalResult String)
evalString r = do
io <- localRef r
tryEval $ do
r <- unsafeCoerce io :: IO String
evaluate (force r)
evalStringToString :: HValueRef -> String -> IO (EvalResult String)
evalStringToString r str = do
io <- localRef r
tryEval $ do
r <- (unsafeCoerce io :: String -> IO String) str
evaluate (force r)
-- When running a computation, we redirect ^C exceptions to the running
-- thread. ToDo: we might want a way to continue even if the target
-- thread doesn't die when it receives the exception... "this thread
-- is not responding".
--
-- Careful here: there may be ^C exceptions flying around, so we start the new
-- thread blocked (forkIO inherits mask from the parent, #1048), and unblock
-- only while we execute the user's code. We can't afford to lose the final
-- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
sandboxIO :: EvalOpts -> IO a -> IO (EvalStatus a)
sandboxIO opts io = do
-- We are running in uninterruptibleMask
breakMVar <- newEmptyMVar
statusMVar <- newEmptyMVar
withBreakAction opts breakMVar statusMVar $ do
let runIt = measureAlloc $ tryEval $ rethrow opts $ clearCCS io
if useSandboxThread opts
then do
tid <- forkIO $ do unsafeUnmask runIt >>= putMVar statusMVar
-- empty: can't block
redirectInterrupts tid $ unsafeUnmask $ takeMVar statusMVar
else
-- GLUT on OS X needs to run on the main thread. If you
-- try to use it from another thread then you just get a
-- white rectangle rendered. For this, or anything else
-- with such restrictions, you can turn the GHCi sandbox off
-- and things will be run in the main thread.
--
-- BUT, note that the debugging features (breakpoints,
-- tracing, etc.) need the expression to be running in a
-- separate thread, so debugging is only enabled when
-- using the sandbox.
runIt
-- We want to turn ^C into a break when -fbreak-on-exception is on,
-- but it's an async exception and we only break for sync exceptions.
-- Idea: if we catch and re-throw it, then the re-throw will trigger
-- a break. Great - but we don't want to re-throw all exceptions, because
-- then we'll get a double break for ordinary sync exceptions (you'd have
-- to :continue twice, which looks strange). So if the exception is
-- not "Interrupted", we unset the exception flag before throwing.
--
rethrow :: EvalOpts -> IO a -> IO a
rethrow EvalOpts{..} io =
catch io $ \se -> do
-- If -fbreak-on-error, we break unconditionally,
-- but with care of not breaking twice
if breakOnError && not breakOnException
then poke exceptionFlag 1
else case fromException se of
-- If it is a "UserInterrupt" exception, we allow
-- a possible break by way of -fbreak-on-exception
Just UserInterrupt -> return ()
-- In any other case, we don't want to break
_ -> poke exceptionFlag 0
throwIO se
--
-- While we're waiting for the sandbox thread to return a result, if
-- the current thread receives an asynchronous exception we re-throw
-- it at the sandbox thread and continue to wait.
--
-- This is for two reasons:
--
-- * So that ^C interrupts runStmt (e.g. in GHCi), allowing the
-- computation to run its exception handlers before returning the
-- exception result to the caller of runStmt.
--
-- * clients of the GHC API can terminate a runStmt in progress
-- without knowing the ThreadId of the sandbox thread (#1381)
--
-- NB. use a weak pointer to the thread, so that the thread can still
-- be considered deadlocked by the RTS and sent a BlockedIndefinitely
-- exception. A symptom of getting this wrong is that conc033(ghci)
-- will hang.
--
redirectInterrupts :: ThreadId -> IO a -> IO a
redirectInterrupts target wait = do
wtid <- mkWeakThreadId target
wait `catch` \e -> do
m <- deRefWeak wtid
case m of
Nothing -> wait
Just target -> do throwTo target (e :: SomeException); wait
measureAlloc :: IO (EvalResult a) -> IO (EvalStatus a)
measureAlloc io = do
setAllocationCounter maxBound
a <- io
ctr <- getAllocationCounter
let allocs = fromIntegral (maxBound::Int64) - fromIntegral ctr
return (EvalComplete allocs a)
-- Exceptions can't be marshaled because they're dynamically typed, so
-- everything becomes a String.
tryEval :: IO a -> IO (EvalResult a)
tryEval io = do
e <- try io
case e of
Left ex -> return (EvalException (toSerializableException ex))
Right a -> return (EvalSuccess a)
toSerializableException :: SomeException -> SerializableException
toSerializableException ex
| Just UserInterrupt <- fromException ex = EUserInterrupt
| Just (ec::ExitCode) <- fromException ex = (EExitCode ec)
| otherwise = EOtherException (show (ex :: SomeException))
fromSerializableException :: SerializableException -> SomeException
fromSerializableException EUserInterrupt = toException UserInterrupt
fromSerializableException (EExitCode c) = toException c
fromSerializableException (EOtherException str) = toException (ErrorCall str)
-- This function sets up the interpreter for catching breakpoints, and
-- resets everything when the computation has stopped running. This
-- is a not-very-good way to ensure that only the interactive
-- evaluation should generate breakpoints.
withBreakAction :: EvalOpts -> MVar () -> MVar (EvalStatus b) -> IO a -> IO a
withBreakAction opts breakMVar statusMVar act
= bracket setBreakAction resetBreakAction (\_ -> act)
where
setBreakAction = do
stablePtr <- newStablePtr onBreak
poke breakPointIOAction stablePtr
when (breakOnException opts) $ poke exceptionFlag 1
when (singleStep opts) $ setStepFlag
return stablePtr
-- Breaking on exceptions is not enabled by default, since it
-- might be a bit surprising. The exception flag is turned off
-- as soon as it is hit, or in resetBreakAction below.
onBreak :: BreakpointCallback
onBreak ix# uniq# is_exception apStack = do
tid <- myThreadId
let resume = ResumeContext
{ resumeBreakMVar = breakMVar
, resumeStatusMVar = statusMVar
, resumeThreadId = tid }
resume_r <- mkRemoteRef resume
apStack_r <- mkRemoteRef apStack
ccs <- toRemotePtr <$> getCCSOf apStack
putMVar statusMVar $ EvalBreak is_exception apStack_r (I# ix#) (I# uniq#) resume_r ccs
takeMVar breakMVar
resetBreakAction stablePtr = do
poke breakPointIOAction noBreakStablePtr
poke exceptionFlag 0
resetStepFlag
freeStablePtr stablePtr
resumeStmt
:: EvalOpts -> RemoteRef (ResumeContext [HValueRef])
-> IO (EvalStatus [HValueRef])
resumeStmt opts hvref = do
ResumeContext{..} <- localRef hvref
withBreakAction opts resumeBreakMVar resumeStatusMVar $
mask_ $ do
putMVar resumeBreakMVar () -- this awakens the stopped thread...
redirectInterrupts resumeThreadId $ takeMVar resumeStatusMVar
-- when abandoning a computation we have to
-- (a) kill the thread with an async exception, so that the
-- computation itself is stopped, and
-- (b) fill in the MVar. This step is necessary because any
-- thunks that were under evaluation will now be updated
-- with the partial computation, which still ends in takeMVar,
-- so any attempt to evaluate one of these thunks will block
-- unless we fill in the MVar.
-- (c) wait for the thread to terminate by taking its status MVar. This
-- step is necessary to prevent race conditions with
-- -fbreak-on-exception (see #5975).
-- See test break010.
abandonStmt :: RemoteRef (ResumeContext [HValueRef]) -> IO ()
abandonStmt hvref = do
ResumeContext{..} <- localRef hvref
killThread resumeThreadId
putMVar resumeBreakMVar ()
_ <- takeMVar resumeStatusMVar
return ()
foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
setStepFlag :: IO ()
setStepFlag = poke stepFlag 1
resetStepFlag :: IO ()
resetStepFlag = poke stepFlag 0
type BreakpointCallback = Int# -> Int# -> Bool -> HValue -> IO ()
foreign import ccall "&rts_breakpoint_io_action"
breakPointIOAction :: Ptr (StablePtr BreakpointCallback)
noBreakStablePtr :: StablePtr BreakpointCallback
noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
noBreakAction :: BreakpointCallback
noBreakAction _ _ False _ = putStrLn "*** Ignoring breakpoint"
noBreakAction _ _ True _ = return () -- exception: just continue
-- Malloc and copy the bytes. We don't have any way to monitor the
-- lifetime of this memory, so it just leaks.
mkString :: ByteString -> IO (RemotePtr ())
mkString bs = B.unsafeUseAsCStringLen bs $ \(cstr,len) -> do
ptr <- mallocBytes len
copyBytes ptr cstr len
return (castRemotePtr (toRemotePtr ptr))
mkString0 :: ByteString -> IO (RemotePtr ())
mkString0 bs = B.unsafeUseAsCStringLen bs $ \(cstr,len) -> do
ptr <- mallocBytes (len+1)
copyBytes ptr cstr len
pokeElemOff (ptr :: Ptr CChar) len 0
return (castRemotePtr (toRemotePtr ptr))
mkCostCentres :: String -> [(String,String)] -> IO [RemotePtr CostCentre]
#if defined(PROFILING)
mkCostCentres mod ccs = do
c_module <- newCString mod
mapM (mk_one c_module) ccs
where
mk_one c_module (decl_path,srcspan) = do
c_name <- newCString decl_path
c_srcspan <- newCString srcspan
toRemotePtr <$> c_mkCostCentre c_name c_module c_srcspan
foreign import ccall unsafe "mkCostCentre"
c_mkCostCentre :: Ptr CChar -> Ptr CChar -> Ptr CChar -> IO (Ptr CostCentre)
#else
mkCostCentres _ _ = return []
#endif
getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
getIdValFromApStack apStack (I# stackDepth) = do
case getApStackVal# apStack (stackDepth +# 1#) of
-- The +1 is magic! I don't know where it comes
-- from, but this makes things line up. --SDM
(# ok, result #) ->
case ok of
0# -> return Nothing -- AP_STACK not found
_ -> return (Just (unsafeCoerce# result))
| tolysz/prepare-ghcjs | spec-lts8/ghci/GHCi/Run.hs | bsd-3-clause | 13,523 | 0 | 18 | 2,940 | 3,064 | 1,493 | 1,571 | 228 | 34 |
module BaseStruct2Alfa{-(transModule,modPath)-} where
import TiDecorate(DeclsUseType,TiPat(..),drop_use)
import TiPrelude(prelFlip,prelOtherwise,prelTrue)
import PNT(PNT(..))
import TypedIds(IdTy(ConstrOf,Class),ConInfo(..),TypeInfo(..))
import UniqueNames as UN(PN(..),Orig(..),orig)
import HasBaseName
import NameMaps
import NameMapsDecorate
import QualNames(unqual,getQualified)
import BaseSyntax hiding (extend)
import Syntax(kstar,kpred,kprop)
import HsConstants(mod_Prelude)
import PrettyPrint
import qualified UAbstract as U
import qualified AbstractOps as U
import qualified UMatch as U
import qualified USubstitute as U
import qualified UFree as U
--import qualified DrawOptions as U(defaultArgOptions,HasName(..),ArgOptions(..))
--import qualified DrawOptionsPrinter as U(printIdOptions)
import EnvM hiding (inEnv)
import MUtils
import TI hiding (TI,getEnv,inst,tapp,sch,inEnv,extend,restrict,tupleT,conName)
--import TiT(kcCheck)
--import RemovePatBinds(remPatBinds')
--import RemoveIrrefPatsBase(removeIrrefPats)
import Lift(lift)
import TiHsName
import USCC(decls)
import PFE0(moduleInfoPath) -- grr
--import Char(isUpper)
import Maybe(fromMaybe,listToMaybe,fromJust)
import List(nub,partition,(\\),sort)
import Monad(join,mplus{-,unless-})
--import Fudgets(ctrace)
default(Int)
type DEnv = DeclsType NName
type DEnv' = DeclsUseType NName
type Env = ([ModuleName],DEnv) -- to keep track of which module is being translated
type Ctx = [Typing NName (Pred NName)]
--type NName = PN HsName
type NName = PNT
---
modPath m = moduleInfoPath m++".alfa"
class Trans src dst | src->dst where
trans :: src->EnvM Env dst
transTyped :: Maybe (HsTypeI NName) -> src -> EnvM Env dst
-- Defined at least one of trans and transTyped!
trans = transTyped Nothing
transTyped _ = trans
instance Trans src dst => Trans (Maybe src) (Maybe dst) where
transTyped t (Just e) = Just # transTyped t e
transTyped t Nothing = return Nothing
ltrans xs = mapM trans xs
--instance Trans [HsImportDeclI i] [U.Decl] where
-- trans is = return [] -- not implemented yet
instance (Trans ds1 [U.Def],
--MapNames (Bool,NName) ds1 NName ds2,
AccNames NName ds1,
MapNames NName ds0 NName ds1)
=> Trans (HsModuleI m i1 ds0) U.Module where
trans m = transModule m # getEnv
packageSynonym (PlainModule newm) (PlainModule oldm) = -- !!!
[U.decl' [U.defA $
U.Package (U.Var (transMName newm),(U.ctx [],
U.PackageInst (un (transMName oldm))))]]
joinModuleNames [m] = m
joinModuleNames ms = PlainModule . concat $ sort [s|PlainModule s<-ms] -- !!!
uPackage n ds = U.defA $ U.Package (n,(U.ctx [],U.PackageDef ds))
uPack n ds = uPackage n (decls ds)
transModule hsmodule (mo0,denv) =
U.Module (map include origMods++
[U.decl' [uPackage (U.Var m)
(map openUnqual (unqualNames ns)++
decls (withEnv env (trans ds2)))]]
)
where
PlainModule m = transM (joinModuleNames mo0) -- !!!
mo = map transM mo0
HsModule src _ e is ds0 =
{-remPatBinds' bind_names . removeIrrefPats arg_names $-} hsmodule
{-
where
--arg_names, bind_names :: [PNT]
arg_names = [ localVal ("arg" ++ show n) | n <- [1..]]
bind_names = [ localVal ("bind" ++ show n) | n <- [1..]]
-}
env = (mo,denv)
ds2 = {-mapNames snd-} ds1
ds1 = transNames mo ds0
ns = --map snd $
filter notcon $ {- nubBy eqSrc $ -} accNames (:) ds1 []
--notcon = fst
notcon (PNT _ (ConstrOf {}) _) = False
notcon _ = True
origMods = nub [m|PNT (PN _ (G m _ _)) _ _<-ns,m `notElem` mo0]
include m = U.ImportDecl (U.Import (modPath m))
unqualNames ns =
collectByFst [(m,n)|PNT (PN (UnQual n) (G m _ _)) _ _<-ns,m `notElem` mo0]
openUnqual (PlainModule m,ns) = -- !!!
U.decl' [U.defA (U.Open (un (transMName m),map oa (nub ns)))]
oa = oav . U.Var . transName
oav' v = U.OpenArg [] v Nothing
oav v = oav' v Nothing
mapPNT f (PNT i idty p) = PNT (f i) idty p
transNames self = mapNames2 TopLevel (varf,conf)
where
varf (role,ClassOrTypeNames) = mapPNT (u . tvar)
varf (role,ValueNames) = mapPNT (u . var)
conf (role,ClassOrTypeNames) = mapPNT (u . tcon)
conf (role,ValueNames) = mapPNT (u . vcon)
-- Packages can't refer to themselves...
u (PN (Qual m n) o) | m `elem` self = PN (UnQual n) o
u x = x
-- var (PN (UnQual x) o@(I m _)) = PN (Qual (transM m) x) o -- instances
var (PN (UnQual x) o@(D n _)) = PN (UnQual (x++show n)) o -- type vars
var (PN (UnQual x) o@(Sn _ s)) = PN (UnQual (x{-++sh s-})) o
-- where sh (SrcLoc f 0 0) = ""
-- sh (SrcLoc f r c) = "_"++show r++"_"++show c
var (PN (Qual _ _) o@(G m n _)) = PN (Qual (transM m) (transName n)) o
var v@(PN q o) =
if v==prelVal "super"
then localVal "super" -- hack
else PN (transQ q) o
tvar (PN (UnQual x) o@(D n _)) = PN (UnQual (x++show n)) o -- generated type var
tvar (PN (UnQual x) o@(UN.S s)) = PN (UnQual (x++"_")) o -- source type var
vcon (PN _ o@(G m n _)) = PN (UnQual (transConName n)) o
vcon c = c
tcon (PN (Qual _ _) o@(G m n _)) = PN (Qual (transM m) (transTCon n)) o
tcon (PN (UnQual _) o@(G m n _)) = PN (UnQual (transTCon n)) o
transTCon n =
case n of
"[]" -> "List"
_ -> transName n
transQ (UnQual x) = UnQual (transName x)
transQ (Qual m n) = Qual (transM m) (transName n)
transConName n = case n of
"[]" -> "Nil"
":" -> "Cons" -- Hmm. Alfa Library convension
_ -> transName n
inPrelude this = transM mod_Prelude `elem` this
transM (PlainModule m) = PlainModule (transMName m)
transM (MainModule m) = PlainModule (transMName "Main") -- !!!
transMName m = "Module_"++dots2uscore m
transName n =
case n of
"Type" -> "Type_" -- reserved identifier
"sig" -> "sig_"
"use" -> "use_"
"." -> ".." -- reserved operator
"()" -> "Unit"
'(':s -> "Tuple"++show (length s) -- tuples!
_ -> n
transD ds = decls # trans ds
{-
instance Trans Ctx [U.Def] where trans = ltrans
instance Trans (Typing NName (Pred NName)) U.Def where
trans (d:>:t) = do t' <- trans t
d' <- transVar d
return $ valdef d' ([],t') U.ePreMetaVar
-}
inModDEnv f = inModEnv (apSnd f)
extend env = inModDEnv (env+++)
extendFrom ds = extend (drop_use (envFrom ds))
extendTyvars = extendTyvars' . mapFst HsVar
extendTyvars' vs = inModDEnv (\(ks,ts)->(map tyvar vs++ks,ts))
where tyvar (v,k) = v:>:(k,Tyvar)
restrict vs = inModDEnv (\(ks,ts)->(ks,[a|a@(x:>:_)<-ts,x `notElem` vs]))
restrictFrom ps = restrict (patternVars ps)
scope ps ds = restrictFrom ps . extendFrom ds
instance (Printable e,Printable p,Printable ds,Printable t,Printable ctx,
FreeNames NName ctx,
Printable tp,DefinedNames NName tp,DefinedNames NName t,
FreeNames NName t,KindCheck NName t Kind,Types NName t,
FreeNames NName tp,Trans p U.Pat,
HasId NName p, DefinedNames NName p, AccNames NName p,
KindCheck NName tp Kind,Types NName tp,
HasId NName e,Trans e U.Exp,Trans ds [U.Def], EnvFrom ds DEnv',
Trans t U.Exp,Trans ctx [U.Exp],Trans tp U.Exp) =>
Trans (DI NName e p ds t ctx tp) [U.Def] where
trans d = trans' d =<< getMEnv
where
trans' d this =
case d of
HsTypeDecl s tp t -> tPs tp $ typeD # tlhs tp <# trans t
HsNewTypeDecl s ctx tp cd drv -> tPs tp $ dataD # tlhs tp <# ltrans [cd]
HsDataDecl s ctx tp cds drv -> tPs tp $ dataD # tlhs tp <# ltrans cds
HsClassDecl s ctx tp _ ds -> pPs tp $ classD ds =<< tlhs tp
HsInstDecl s optn c tp ds -> iPs c tp $ instDecl s optn c tp ds
-- HsDefaultDecl s t -> return (hsDefaultDecl s t)
HsTypeSig s nms c tp -> return [] -- just looks ugly...
HsFunBind s matches -> transMatches matches
HsPatBind s p rhs ds -> transPatBind p rhs ds
-- HsInfixDecl s fixity names -> return (hsInfixDecl s fixity names)
HsPrimitiveTypeDecl s ctx tp -> tPs tp $ primTypeD # tlhs tp
HsPrimitiveBind s i t -> primValueD i t
_ -> return [commentdef d]
where
pPs = kPs kpred
tPs = kPs kstar
kPs k lhs m =
do vks <- runKc k (freeTyvars lhs) lhs
extendTyvars' vks m
iPs ctx lhs m =
do vks <- runKc kpred (freeTyvars (ctx,lhs)) lhs
extendTyvars' vks (m [(v,k)|(HsVar v,k)<-vks])
tlhs tp = do (qn, ts) <- U.flatApp' # trans tp
let HsCon n = definedType tp
n' = U.Var (getQualified (getBaseName n))
k <- kinfo tp
return (n,n',k,[x|U.EVar x<-ts])
kinfo tp = do (k,i) <- knd (definedType tp)
k' <- trans k
return (k',i)
-- A hack to be able to use special syntax when defining types in the Prelude:
--unqual (U.EVar n) = n
--unqual (U.EProj (U.EVar (U.Var m)) (U.Label s)) = U.Var s
typeD (_,n,(k,_),xs) t = [valdef n (args xs k) t]
dataD lhs@(_,n,(k,_),xs) cs =
if inPrelude this && reusePreludeFromAlfa n
then primTypeD lhs
else [valdef n (args xs k) (U.ESum cs)]
where
reusePreludeFromAlfa n =
n `elem` map U.Var ["Unit","Bool","List"]
--methodnames ms = ltrans [n|HsVar n<-ns]
-- where ns:>:_ =unzipTyped ms
methodnames ms = [U.Var ("method_"++show i)|i<-[1..length ms]]
classD ds (n,n'@(U.Var nstr),(k,TI.Class ctx vs fdeps ms0),_) =
do let ss=zipWith superMethod [1..] ctx
ms=ss++ms0
vs' <- ltrans (tdom vs)
ms' <- ltrans ms
let ns' = methodnames ms
ds' <- trans{-D-} ds -- default methods
let tsig = args vs' k
cn = {-projSelf-} (U.EVar n')
c = U.app cn (map U.EVar vs')
mds <- concatMapM (methodDecl c ns' vs') (zip ns' ms)
return $ valdef n' (args vs' k) (sig ns' ms'):
defaultMethods ds'++
mds
where
d = U.Var "d"
(cvs,_) = U.flatFun k
{-
defaultMethods ds' =
U.defA $ U.Package (pkg,(U.ctx [],U.PackageDef ds'))
where pkg = U.Var ("default__"++nstr)
-}
defaultMethods = map (U.mapDefB defaultMethod)
defaultMethod (U.Value (U.Var name,rhs)) =
U.Value (U.Var (defaultName name),rhs)
defaultMethod (U.Binding (U.Var name,rhs)) =
U.Binding (U.Var (defaultName name),rhs)
defaultMethod d = d -- comments...
methodDecl c ns' vs' (n',HsVar m:>:s) =
do (gs,qt) <- kcScheme m s
gs' <- ltrans gs
qt' <- extendTyvars gs (trans qt)
let ps = zip vs' cvs++gs'++[(d,c)]
m' <- transUnqualVar m
return $ hide m' ps ++
[valdef m' (ps,([],qt'))
(sigproj ns' n' (map (U.EVar . fst) gs'))
]
superMethod i supercl =
HsVar (superName n i):>:mono supercl
sigproj ns' m' gs' =
U.app (U.EProj (U.EVar d) (var2lbl m')) gs'
dataproj ns' m' gs' =
U.ECase (U.EVar d) [U.Branch (inst,(ns',U.app (U.EVar m') gs'))]
sig ns ms = U.ESig (zipWith method ns ms)
where
method n (U.SigField x t) = U.SigField (var2lbl n) t
sig2data _ ms =
U.ESum [U.Constr (inst,(U.ctx [(lbl2var x,t)|U.SigField x t<-ms],[]))]
inst = U.Con "instance"
primTypeD (_,n,(k,_),xs) =
[if inPrelude this
then preludePrimImportD n
else postulate n (args xs k)]
preludePrimImportD n =preludePrimImportD' n Nothing
preludePrimImportAsD n = preludePrimImportD' n . Just
preludePrimImportD' n as =
U.changeProps (const [U.Public]) $
U.defA (U.Open (pb,[oav' n as]))
where
pb = un "PreludeFromAlfa"
--instDecl s Nothing ctx tp ds vks = undefined
instDecl s (Just n) ctx tp ds vks =
do ctx' <- trans ctx
vks' <- ltrans vks
t <- trans tp
--ds' <- transD ds
ds' <- trans ds
ns <- do (k,TI.Class super _ _ ms) <- kinfo tp
let ns=[n|HsVar n:>:_<-ms]
HsCon c=definedType tp
ss=map (superName c) [1..length super]
ltrans (ss++ns)
let mns = methodnames ns
n' <- trans n
let dicts = xargs ctx'
actx = vks'++dicts
targs = map (U.EVar . fst) vks'
return $
--hide n' vks' ++
[valdef n' (actx,([],t)) (str targs dicts (zip ns mns) ds')]
where
str targs dicts ns2mns ds =
U.EStr (decls (map (U.mapDefB (rename.adjust)) (bindings ds)))
where
adjust (U.Binding (n,e)) = U.Binding (n,adjustmethod e targs dicts)
adjust d = d
rename (U.Value (name,rhs)) = U.Value (mname name,rhs)
rename (U.Binding (name,rhs)) = U.Binding (mname name,rhs)
rename d = d -- comments...
mname n = fromJust (lookup n ns2mns)
{-
str2con targs dicts ns ds = U.app (U.ECon inst) (map conarg ns)
where
conarg n = fromMaybe undef (lookup n ds')
ds' = [(n,adjustmethod e targs dicts)|
U.DefA _ (U.Binding (n,e))<-bindings ds]
-}
adjustmethod e = substds . uapply e
--useDefault (U.Var n) = un (defaultName n)
--undef = U.ePreMetaVar
--undef = eUndefined `uApp` U.ePreMetaVar
bindings = U.rmTypeSign . map (U.mapDefB preserve)
where
preserve d =
case d of
U.Value (name,(ctx@(U.Ctx _ (_:_)),e,t)) | needType e ->
U.Value (name,(ctx,eTyped e t,t))
_ -> d
needType (U.ECase {}) = True
needType _ = False -- sig and data can't occur in instance decls
ifHasType v d m = ifM (inEnv (HsVar v)) m (return [commentdef d])
transMatches ms@(HsMatch _ n _ _ _:_) =
ifHasType n ms $
do sch@(gs,cs:=>t) <- schk (HsVar n)
extendTyvars gs $ do
cs' <- ltrans cs
(xs,rhs) <- umatch this (matchcons ms) # ltrans ms
(targs,tres) <- U.flatFun # trans t
--this <- getMEnv
tctx <- ltrans gs
let (ctx,(xs',tres')) = args' xs (cs'++targs) tres
cnt = length gs+length cs'
n' <- transUnqualVar n
return $
--commentdef sch:
hide' n' cnt++[valdef n' (tctx++ctx,(xs',tres')) rhs]
transPatBind = transVarBind . fromJust' . isVar
fromJust' = fromMaybe (error "Hs2Alfa.hs: pattern bindings not supported")
transVarBind qv rhs ds =
ifHasType qv d $
do v <- transUnqualVar qv
(gs,[]:=>t) <- schk (HsVar qv)
tvs <- ltrans gs
extendTyvars gs $ do
t' <- trans t
extendFrom ds $ do
rhs' <- transR ds rhs
return $ hide v gs ++ [valdef v (tvs, ([],t')) rhs']
primValueD qv t =
do v <- transUnqualVar qv
if inPrelude this
then return [preludePrimImportD v]
else do (gs,[]:=>t) <- schk (HsVar qv)
tvs <- ltrans gs
extendTyvars gs $ do
t' <- trans t
return $ hide v gs ++ [postulate v (tvs, ([], t'))]
commentdef d = U.defA $ U.CommentDef (comment (pp d))
args xs t = uncurry (args' xs) (U.flatFun t)
args' [] ts tres = ([],([],U.eFuns ts tres))
args' (x:xs) (t:ts) tres = apFst ((x,t):) (args' xs ts tres)
args' xs [] tres = ([],(xs,tres))
{- This was used in an attempt to put type and class declarations inside
packages, where auxiliary functions could be put as well without creating
name clashes. But packages can't be recursive so it didn't work.
-}
--packdef v lhs rhs = uPackage v (decls [valdef self lhs rhs])
--self = U.Var "T"
--projSelf e = U.EProj e (U.Label "T")
valdef v (ctx,(xs, t)) rhs =
U.defA $ U.Value (v,(U.ctx ctx,U.uAbsExp xs (rmtannot rhs),t))
rmtannot (U.ETyped e t) = e
rmtannot e = e
typeOf (U.ETyped e t) = Just t
typeOf _ = Nothing
postulate v (ctx,(xs, t)) = U.defA $ U.Axiom (v,(U.ctx ctx,U.uAbsExp xs t))
--typedef v ctx rhs = U.defA $ U.Type (v,(U.ctx ctx,rhs))
eTyped e@(U.ETyped _ _) t = e
eTyped e t = U.ETyped e t
instance (HasId NName e,Trans e U.Exp,Trans p U.Pat,DefinedNames NName p,
Trans ds [U.Def],EnvFrom ds DEnv')
=> Trans (HsMatchI NName e p ds) U.Rule where
trans (HsMatch s _ ps rhs ds) =
(,) # ltrans ps <# (scope ps ds $ transR ds rhs)
transR ds e = eLet # transD ds <# trans e
instance Trans t U.Exp => Trans (HsConDeclI NName t c) U.Constructor where
-- Existential quantification is ignored!!! (Impredicativity problem)
trans (HsConDecl s _ _ n as) = constr # transCon n <# mapM (trans.unbang) as
where
constr n as = U.Constr (nilHack n,(args as,[]))
unbang bt = accBangType const bt ()
args = U.ctx . xargs
nilHack (U.Con "List") = U.Con "Nil"
nilHack c = c
trans (HsRecDecl s _ _ n fs) = constr # transCon n <# concatMapM transFields fs
where
transFields (fs,bt) = fields # mapM trans fs <# trans (unbang bt)
where fields fs t = [(f,t)|f<-fs]
constr n as = U.Constr (n,(U.ctx as,[]))
xargs = zipWith arg [1..]
where arg i t = (U.Var ("x"++show i),t)
instance (HasId NName e,Trans e U.Exp) => Trans (HsRhs e) U.Exp where
transTyped t (HsBody e) = transTyped t e
transTyped t (HsGuard gs) = transGuards gs =<< trans t
where
-- this is a quick hack!!!
transGuards [] t =
do this <- getMEnv
return (eUndefined this `uApp` opt "result type in guarded rhs" t) -- a failed guard
transGuards ((_,g,e):gs) t =
if isTrue g
then trans e
else eIf t # trans g <# trans e <# transGuards gs t
isTrue = maybe False isTrueId . isId
isTrueId x = x `elem` [prelTrue,prelOtherwise]
instance Trans (Assump NName) U.SigPart where
trans (HsVar x:>:t) = U.SigField # transLbl x <# trans t
instance Trans (Scheme NName) U.Exp where
trans s =
do (vs,qt) <- kcScheme "?" s
U.piExp # ltrans vs <# extendTyvars vs (trans qt)
instance Trans t U.Exp => Trans (Qual NName t) U.Exp where
trans (ctx:=>t) = U.eFuns # ltrans ctx <# trans t
instance Trans (HsTypeI NName) U.Exp where trans (Typ t) = trans t
instance Trans NName U.Var where trans x = U.Var # (flip transId x # getMEnv)
transEVar x = inst x
{-
do b <- inEnv x
if b
then do Forall vs (ctx:=>_) <- sch x -- monomorphic recursive call
unless (null vs && null ctx) $
error $"missing type annotation for "++show x
x' <- inst x
vs' <- map U.EVar # ltrans vs
return $ U.app x' (vs'++replicate (length ctx) U.ePreMetaVar)
else inst x -- lambda bound variable
-}
-- Constructors don't need type arguments, but they need to be applied
-- to the right number of values.
transECon c sc ts =
con # inst c <# trans (specialize sc ts)
where
con c t =
eTyped (U.absExp (zipWith (U.:-) ps ts) (U.app c (map U.EVar ps))) t
where
(ts,tr) = U.flatFun t
ps = [U.Var ("conarg"++show n)|n<-[1..length ts]]
specialize (Forall _ gs qt) ts = apply (TI.S (zip (tdom gs) ts)) qt
instance (Printable t,KindCheck NName t Kind,Trans t U.Exp,Types NName t)
=> Trans (TI NName t) U.Exp where
trans t =
case t of
HsTyFun x y -> U.eFun # trans x <# trans y
-- HsTyTuple ts -> U.app . tupleT (length ts) # getMEnv <# ltrans ts
HsTyApp f x -> trans f `tapp` trans x
HsTyVar nm -> do b <- inTEnv (HsVar nm)
if b
then do (k,_) <- knd (HsVar nm)
if k==kprop
then U.EApp (un "predT") # inst (HsVar nm)
else inst (HsVar nm)
else return (missing "type variable not in scope")
HsTyCon nm -> instTcon nm
HsTyForall vs ps t1 ->
do vks <- runKc kstar (map HsVar vs) t1
let vks' = [(v,k)|(HsVar v,k)<-vks] -- grr
U.piExp # ltrans vks' <# extendTyvars' vks (trans t1) -- ps !!!
--ePis vs t = foldr ePi t vs
--ePi (v,k) = U.EPi (v U.:- k)
{-
tupleT n this = uqn (tupleName n)
where
prel = transM mod_Prelude
uqn = if this==prel then un else qn prel
-}
tupleName n = "Tuple"++show (n::Int)
instance Trans Kind U.Exp where
trans (K k) =
case k of
Kstar -> return eStar
Kfun k1 k2 -> U.eFun # trans k1 <# trans k2
Kpred -> return eClass
Kprop -> return ePropKind
consE = U.ECon cons
nilE = U.ECon nil
cons = U.Con "Cons"
nil = U.Con "Nil"
{-
type Pat0 = (U.Con,[U.Var])
instance Trans HsPat Pat0 where
trans (Pat p) =
case p of
HsPId (HsCon c) -> return (transCon c,[])
HsPApp c ps -> return (transCon c,transPVars ps)
HsPList [] -> return (nil,[])
-}
instance Trans (TiPat NName) U.Pat where
trans (Pat p) = trans p
trans (TiPSpec (HsVar v) _ []) = U.PVar # transUnqualVar v
trans (TiPSpec (HsCon c) _ _) = con0P c
trans (TiPTyped p t) = transTyped (Just t) p
trans (TiPApp p1 p2) = papp # trans p1 <# trans p2
where
papp (U.PCon c ps) p = U.PCon c (ps++[p])
papp _ _ = U.PVar noname -- !!!
trans p = --error $ "Not implemented yet: "++pp p
return $ U.PVar noname -- !!!
transTyped t (Pat e) = transTyped t e
transTyped _ e = trans e
-- ...
instance (Printable p,Trans p U.Pat) => Trans (PI NName p) U.Pat where
trans p =
case p of
HsPId (HsCon c) -> con0P c
HsPId (HsVar v) -> U.PVar # transUnqualVar v
HsPApp c ps -> U.PCon # transCon c <# ltrans ps
HsPList s ps -> foldr consP nilP # ltrans ps
HsPTuple s ps -> U.PCon (tupleCon (length ps)) # ltrans ps
HsPInfixApp p1 c p2 -> U.PCon # transCon c <# ltrans [p1,p2]
HsPParen p -> trans p
HsPAsPat v p -> U.PAs # trans v <# trans p
HsPWildCard -> return $ U.PVar noname
HsPIrrPat p -> trans p -- !!
_ -> --error $ "Not implemented yet: "++pp p
return $ U.PVar noname -- !!!
noname = U.Var "__" -- "_" is reserved in Agda nowadays
nilP = U.PCon nil []
consP p1 p2 = U.PCon cons [p1,p2]
con0P c = flip U.PCon [] # transCon c
tupleCon = U.Con . tupleName
--rmtrans e = rmtannot # trans e
rmltrans es = map rmtannot # ltrans es
ptrans (TiPTyped p t) = (,) # trans p <# trans t
lptrans = mapM ptrans
optTransTyped t e = maybe e (eTyped e) # trans t
{-
checkChar x c =
if c<toEnum 0 || c>toEnum 255
then error$ "Unsupported char"++show (fromEnum c)++" in "++show x
else c
-}
checkChar _ c = toEnum (fromEnum c `mod` 256) -- hmm
instance (HasId NName e,Trans e U.Exp,
--AccNames NName p,DefinedNames NName p,HasId NName p,Trans p U.Pat,
Trans ds [U.Def],EnvFrom ds DEnv')
=> Trans (EI NName e (TiPat NName) ds c t) U.Exp where
transTyped t e =
optTransTyped t =<<
case e of
HsId x -> transEVar x
HsLit _ (HsChar c) -> return (U.EChar (checkChar c c))
HsLit _ (HsString s) -> return (U.EString (map (checkChar s) s))
--HsLit _ (HsString s) -> return (U.EString "") -- for a performance test
HsLit _ (HsInt i) -> return (U.EInt i)
HsLit _ (HsFrac x) -> return (U.ERat x)
HsLit _ _ -> return (missing "unimplemented type of literal")
HsInfixApp x op z -> inst op `tapp` trans x `tapp` trans z
HsApp x y -> trans x `tapp` trans y
-- HsNegApp x -> inst prelNegate `tapp` tc x
HsLambda ps e -> do this <- getMEnv
eLambda this (patscons ps) # lptrans ps <# restrictFrom ps (trans e)
HsLet ds e -> eLet # transD ds <# extendFrom ds (trans e)
HsIf x y z -> eIf # trans t <# trans x <# trans y <# trans z
HsCase e alts -> do this <- getMEnv
eCase this (altcons alts) # trans t <# trans e <# ltrans alts
-- HsDo stmts -> tcStmts stmts
HsTuple es -> U.app (U.ECon (tupleCon (length es))) #rmltrans es
HsList es -> foldr (U.app2 consE) nilE # rmltrans es
HsParen e -> trans e
HsLeftSection x op -> inst op `tapp` trans x
HsRightSection op y -> inst pqFlip `tapp` inst op `tapp` trans y
-- HsRecConstr s n fields -> recConstr n fields
-- HsRecUpdate e upds ->
-- HsEnumFrom x -> inst prelEnumFrom `tapp` tc x
-- HsEnumFromTo x y -> inst prelEnumFromTo `tapp` tc x `tapp` tc y
-- HsEnumFromThen x y -> inst prelEnumFromThen `tapp` tc x `tapp` tc y
-- HsEnumFromThenTo x y z ->
-- inst prelEnumFromThenTo `tapp` tc x `tapp` tc y `tapp` tc z
-- HsListComp stmts -> emap hsListComp # tcLComp stmts
-- HsExpTypeSig s e c t -> tcExpTypeSig s e c t
-- Unimplemented things are turned into metavariables:
_ -> return $ missing "unimplemented form of expression"
where
{- recConstr c fs =
case fieldsOf c of
Nothing -> return $ missing bad
Just fns -> do c' <- inst (HsCon c)
let args = map (pick [(orig fn,e)|HsField fn e<-fs]) fns
args' <- mapM (mtrans bad) args
return (U.app c' args')
bad = "bad record construction?"
fieldsOf (PNT c (ConstrOf _ tinfo) _) =
fmap (map orig) . join . listToMaybe $
[conFields ci|ci<-constructors tinfo,orig (conName ci)==orig c]
fieldsOf (PNT c (TypedIds.Class ms) _) = Just (map orig ms)
fieldsOf _ = Nothing -- Not a constructor ?!
pick = flip lookup
-}
pqFlip = mapHsIdent oqual prelFlip
oqual (PNT (PN _ o@(G m n _)) t s) = PNT (PN (Qual m n) o) t s
oqual n = n
mtrans s Nothing = return $ missing s
mtrans s (Just e) = trans e
instance (Trans i1 i2,Trans e1 e2) => Trans (HsFieldI i1 e1) (i2,e2) where
trans (HsField i e) = (,) # trans i <# trans e
instance Trans [HsTypeI NName] [U.Exp] where trans = ltrans
instance (Trans a1 a2,Trans b1 b2) => Trans (a1,b1) (a2,b2) where
trans = trans >#< trans
instance (HasId NName e,Trans e U.Exp,Trans p U.Pat,DefinedNames NName p,
Trans ds [U.Def],EnvFrom ds DEnv')
=> Trans (HsAlt e p ds) U.Rule
where
trans (HsAlt s p rhs ds) =
do p' <- trans p
scope p ds $ do
rhs' <- transR ds rhs
return ([p'], rhs')
sets xs = [(x,eStar)|x<-xs]
--sets xs = [(x,U.ePreMetaVar)|x<-xs]
instTcon c = {-projSelf # -} inst (HsVar c)
inst x = flip inst' x # getMEnv
inst' this (HsCon x) = U.ECon (transCon' this x)
inst' this (HsVar n) = case getBaseName (n::NName) of
UnQual x -> un x
Qual mo x -> qn mo x
qn (PlainModule m) x = U.EProj (un m) (U.Label x)
un = U.EVar . U.Var
--evar = U.EVar . U.Var
{-
transPVar p = transVar (fromJust' . isVar $ p)
where fromJust' = fromMaybe (error "BaseStruct2Alfa.hs: patterns in lambdas are not supported")
transPVars ps = mapM transPVar ps
-}
-- This is used to translate identifiers appearing where only unqualified names
-- are legal, but the abstract syntax allows qualified names
transUnqualVar = transVar . unqual
transCon x = flip transCon' x # getMEnv
transVar x = flip transVar' x # getMEnv
var2lbl (U.Var x) = U.Label x
lbl2var (U.Label x) = U.Var x
transLbl x = var2lbl # transUnqualVar x
transVar' this = U.Var . transId this
transCon' this = U.Con . transId this
--lbl = U.Label # transId
transId this n = transId' this (getBaseName (n::NName))
transId' this (UnQual x) = x
transId' this (Qual mo@(PlainModule m) x) = -- !!!
if mo `elem` this
then x
else m{-++"_"-}++x
--Hmm. Qualified names in definitions won't work...
--Just output something rather than failing immediately.
eClass = un "Class" -- for readability
eStar = un "Star" -- for readability
--eStar = U.eSet -- avoids dependency on nonstd predefined things in Alfa
ePropKind = un "PropKind" -- for readability
eUndefined this =
if inPrelude this
then un "undefined"
else qn (transM mod_Prelude) "undefined"
eLet [] e = e
eLet (U.Decl _ []:ds) e = eLet ds e
eLet ds e = U.ELet ds e -- problem if e is case or sig or ...
eCase this css t e rules = optTyped t (U.subst e v ecase)
where ([v],ecase) = umatch this css rules
optTyped = maybe id (flip eTyped)
eLambda this css tps e0 =
if all uIsVar ps
then U.absExp [x U.:-t|(U.PVar x,t)<-tps] e0
else U.absExp [v U.:-t|(v,t)<-zip vs ts] (f ecase)
where
(ps,ts) = unzip tps
(vs,ecase) = umatch this css [(ps,e)]
(e,f) = case e0 of
U.ETyped e t -> (e,flip eTyped t)
_ -> (e0,id)
altcons alts = patscons [ p | HsAlt s p rhs ds<-alts]
matchcons ms = patscons [ p | HsMatch s _ ps rhs ds<-ms,p<-ps]
-- This can fail if a pattern contains constructors from different types
-- but with the same unqualified name...
patscons = transCons . accCons
where
transCons = (listcons:).map (mapFst con)
con (PN c o) = U.Con (transConName c)
listcons = [(U.Con "Nil",0),(U.Con "Cons",2)]
--tr x = ctrace "cons" x x
accCons ps = accNames con ps []
where
con (PNT c (ConstrOf _ tinfo) _) css =
if cs `elem` css
then css
else cs:css
where cs = tinfo2cs tinfo
con _ css = css
tinfo2cs tinfo = [(c,n)|ConInfo{conName=c,conArity=n}<-constructors tinfo]
eIf t cnd thn els = eIfTyped (opt "result type for if" t') cnd thn els
where t' = t `mplus` typeOf thn `mplus` typeOf els
eIfTyped t cnd thn els = U.app (un "if_then_else") [t,cnd,thn,els]
--eIf cnd thn els = U.ECase cnd [b "True" thn,b "False" els]
-- where b c e = U.Branch (U.Con c,([],e))
umatch this css rules =
case rules of
[(ps,e)] | all uIsVar ps -> ([x|U.PVar x<-ps],e) -- to preserve var names
_ -> U.exhaustiveMatch'' css [] rules undef
where
undef = eUndefined this `uApp` missing "potential pattern match failure"
uIsVar (U.PVar _) = True
uIsVar _ = False
m1 `tapp` m2 = uApp # m1 <# m2
e1 `uApp` e2 =
case e1 of
-- Agda doesn't like applied meta variables:
U.EMeta _ -> e1
U.EAnnot a (U.EMeta _) -> e1
-- Agda doesn't like beta redexes:
U.ETyped (U.EAbs (x U.:-_) e1') (U.EPi _ t) -> U.subst e2 x e1' `eTyped` t
U.EAbs x e1' -> uLet x e2 e1'
--U.ETyped e1' (U.EPi _ t) -> (e1' `uApp` e2) `eTyped` t
_ -> U.EApp e1 e2
where
-- Avoid code duplication, if possible without name capture
-- (there are no non-recursive declarations in Agda)
uLet (x U.:-t) e2 e1 =
if x `elem` U.free e2
then U.subst e2 x e1
else U.ELet [U.decl' [valdef x (([],([],t))) e2]] e1
getDEnv = snd # getEnv
getMEnv = fst # getEnv
{-+
Since the type checker doesn't provide kind information for type variables in
type schemes, we do a _local_ kind inference on the type scheme.
I am not quite sure this is enough to always get the right kinds...
-}
schk x = kcScheme x =<< sch x
schak x = akcScheme x =<< sch x
kcScheme _ (Forall _ vs qt) = return ([(v,k)|v:>:k<-vs],qt)
akcScheme _ (Forall as vs qt) = return ([(v,k)|v:>:k<-as++vs],qt)
{-
kcScheme x (Forall [] qt) = return ([],qt) -- shortcut
kcScheme x (Forall vs qt) =
do vks <- runKc' x kstar (map HsVar (tdom vs)) qt
return ([(v,k)|(HsVar v,k)<-vks],qt)
--}
--runKcStar = runKc kstar
runKc = runKc' ""
runKc' s k vs qt =
do kenv <- fst # getDEnv
vkts <- lift (errorContext (pp (s,vs,qt,k)) $
extendkts kenv $ kgeneraliseSloppy $
do bs <- kintro vs
bs' <- kintro (map HsVar (tv qt)\\vs) -- hmm
k' <- extendkts (bs++bs') $ kc qt
let _ = k' `asTypeOf` k
return bs)
return [(v,k)|v:>:(k,_)<-vkts]
sch x = lookupts x . snd # getDEnv
knd x = lookupts x . fst # getDEnv
inEnv x = (elem x . map tfst . snd) # getDEnv
inTEnv v = (elem v . map tfst . fst) # getDEnv
tfst (x:>:_) = x
lookupts x [] = error ("Not in scope:"++show x)
lookupts x ((y:>:t):ts) = if x==y then t else lookupts x ts
eCmnt = U.eComment . comment
comment s = "{- "++s++" -}"
annot s = "{-# Alfa "++s++" #-}"
missing s = eCmnt s U.ePreMetaVar
opt = fromMaybe . missing
hide v = hide' v . length
hide' (U.Var v) cnt =
if cnt>0
then [U.defA $ U.CommentDef $ annot s]
else []
where
s = --U.printIdOptions (U.name v,(U.defaultArgOptions v){U.hideCnt=cnt})
"var "++show v++" hide "++show cnt
---}
uapply e [] = e
uapply (U.EAbs (x U.:-_) e) (a:as) = uapply (U.subst a x e) as
uapply e as = U.app e as -- hmm
substds e [] = e
substds e@(U.EAbs p@(x U.:-t) b) ds =
case partition (sameT t) ds of
((d,_):ds1,ds2) -> substds (U.subst (U.EVar d) x b) (ds1++ds2)
([],ds2) -> U.EAbs p (substds b ds2) -- assume p is a type parameter
-- _ -> U.eComment (comment $ "Something went wrong here: dictionary argument type mismatch: "++show t) e -- Hmm
where
sameT t (_,t') = t==t'
substds e _ = U.eComment (comment "Something went wrong here: too many dictionary arguments?") e -- Hmm
| forste/haReFork | tools/hs2alfa/BaseStruct2Alfa.hs | bsd-3-clause | 32,831 | 295 | 22 | 9,179 | 10,716 | 5,867 | 4,849 | -1 | -1 |
module Aws.S3.Commands.DeleteObjects where
import Aws.Core
import Aws.S3.Core
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Network.HTTP.Conduit as HTTP
import qualified Network.HTTP.Types as HTTP
import qualified Text.XML as XML
import qualified Text.XML.Cursor as Cu
import Text.XML.Cursor (($/), (&|))
import Crypto.Hash
import qualified Data.ByteString.Char8 as B
import Data.ByteString.Char8 ({- IsString -})
import Control.Applicative ((<$>))
data DeleteObjects
= DeleteObjects {
dosBucket :: Bucket
, dosObjects :: [(Object, Maybe T.Text)] -- snd is an optional versionId
, dosQuiet :: Bool
, dosMultiFactorAuthentication :: Maybe T.Text
}
deriving (Show)
-- simple use case: neither mfa, nor version specified, quiet
deleteObjects :: Bucket -> [T.Text] -> DeleteObjects
deleteObjects bucket objs =
DeleteObjects {
dosBucket = bucket
, dosObjects = zip objs $ repeat Nothing
, dosQuiet = True
, dosMultiFactorAuthentication = Nothing
}
data DeleteObjectsResponse
= DeleteObjectsResponse {
dorDeleted :: [DORDeleted]
, dorErrors :: [DORErrors]
}
deriving (Show)
--omitting DeleteMarker because it appears superfluous
data DORDeleted
= DORDeleted {
ddKey :: T.Text
, ddVersionId :: Maybe T.Text
, ddDeleteMarkerVersionId :: Maybe T.Text
}
deriving (Show)
data DORErrors
= DORErrors {
deKey :: T.Text
, deCode :: T.Text
, deMessage :: T.Text
}
deriving (Show)
-- | ServiceConfiguration: 'S3Configuration'
instance SignQuery DeleteObjects where
type ServiceConfiguration DeleteObjects = S3Configuration
signQuery DeleteObjects {..} = s3SignQuery S3Query
{
s3QMethod = Post
, s3QBucket = Just $ T.encodeUtf8 dosBucket
, s3QSubresources = HTTP.toQuery [("delete" :: B.ByteString, Nothing :: Maybe B.ByteString)]
, s3QQuery = []
, s3QContentType = Nothing
, s3QContentMd5 = Just $ hashlazy dosBody
, s3QObject = Nothing
, s3QAmzHeaders = maybeToList $ (("x-amz-mfa", ) . T.encodeUtf8) <$> dosMultiFactorAuthentication
, s3QOtherHeaders = []
, s3QRequestBody = Just $ HTTP.RequestBodyLBS dosBody
}
where dosBody = XML.renderLBS XML.def XML.Document {
XML.documentPrologue = XML.Prologue [] Nothing []
, XML.documentRoot = root
, XML.documentEpilogue = []
}
root = XML.Element {
XML.elementName = "Delete"
, XML.elementAttributes = M.empty
, XML.elementNodes = quietNode dosQuiet : (objectNode <$> dosObjects)
}
objectNode (obj, mbVersion) = XML.NodeElement XML.Element {
XML.elementName = "Object"
, XML.elementAttributes = M.empty
, XML.elementNodes = keyNode obj : maybeToList (versionNode <$> mbVersion)
}
versionNode = toNode "VersionId"
keyNode = toNode "Key"
quietNode b = toNode "Quiet" $ if b then "true" else "false"
toNode name content = XML.NodeElement XML.Element {
XML.elementName = name
, XML.elementAttributes = M.empty
, XML.elementNodes = [XML.NodeContent content]
}
instance ResponseConsumer DeleteObjects DeleteObjectsResponse where
type ResponseMetadata DeleteObjectsResponse = S3Metadata
responseConsumer _ = s3XmlResponseConsumer parse
where parse cursor = do
dorDeleted <- sequence $ cursor $/ Cu.laxElement "Deleted" &| parseDeleted
dorErrors <- sequence $ cursor $/ Cu.laxElement "Error" &| parseErrors
return DeleteObjectsResponse {..}
parseDeleted c = do
ddKey <- force "Missing Key" $ c $/ elContent "Key"
let ddVersionId = listToMaybe $ c $/ elContent "VersionId"
ddDeleteMarkerVersionId = listToMaybe $ c $/ elContent "DeleteMarkerVersionId"
return DORDeleted {..}
parseErrors c = do
deKey <- force "Missing Key" $ c $/ elContent "Key"
deCode <- force "Missing Code" $ c $/ elContent "Code"
deMessage <- force "Missing Message" $ c $/ elContent "Message"
return DORErrors {..}
instance Transaction DeleteObjects DeleteObjectsResponse
instance AsMemoryResponse DeleteObjectsResponse where
type MemoryResponse DeleteObjectsResponse = DeleteObjectsResponse
loadToMemory = return
| Soostone/aws | Aws/S3/Commands/DeleteObjects.hs | bsd-3-clause | 5,036 | 0 | 14 | 1,658 | 1,112 | 623 | 489 | -1 | -1 |
module Distribution.Types.ComponentInclude (
ComponentInclude(..),
ci_id,
ci_pkgid,
ci_cname
) where
import Distribution.Types.PackageId
import Distribution.Types.ComponentName
import Distribution.Types.AnnotatedId
-- Once ci_id is refined to an 'OpenUnitId' or 'DefUnitId',
-- the 'includeRequiresRn' is not so useful (because it
-- includes the requirements renaming that is no longer
-- needed); use 'ci_prov_renaming' instead.
data ComponentInclude id rn = ComponentInclude {
ci_ann_id :: AnnotatedId id,
ci_renaming :: rn,
-- | Did this come from an entry in @mixins@, or
-- was implicitly generated by @build-depends@?
ci_implicit :: Bool
}
ci_id :: ComponentInclude id rn -> id
ci_id = ann_id . ci_ann_id
ci_pkgid :: ComponentInclude id rn -> PackageId
ci_pkgid = ann_pid . ci_ann_id
-- | This should always return 'CLibName' or 'CSubLibName'
ci_cname :: ComponentInclude id rn -> ComponentName
ci_cname = ann_cname . ci_ann_id
| mydaum/cabal | Cabal/Distribution/Types/ComponentInclude.hs | bsd-3-clause | 1,002 | 0 | 9 | 195 | 151 | 92 | 59 | 18 | 1 |
#!/usr/bin/env runhaskell
import Control.Concurrent (threadDelay)
main = do
threadDelay $ 5 * 60 * (round $ 1e6)
| tlevine/www.thomaslevine.com | content/!/sleep/sleep-hs.hs | mit | 115 | 0 | 9 | 19 | 39 | 21 | 18 | 3 | 1 |
-- |
-- Stability: stable
--
-- Hspec is a testing framework for Haskell.
--
-- This is the library reference for Hspec.
-- The <http://hspec.github.io/ User's Manual> contains more in-depth
-- documentation.
module Test.Hspec (
-- * Types
Spec
, SpecWith
, Arg
, Example
-- * Setting expectations
, module Test.Hspec.Expectations
-- * Defining a spec
, describe
, context
, it
, specify
, example
, pending
, pendingWith
, parallel
, runIO
-- * Hooks
, ActionWith
, before
, before_
, beforeWith
, beforeAll
, beforeAll_
, after
, after_
, afterAll
, afterAll_
, around
, around_
, aroundWith
-- * Running a spec
, hspec
) where
import Test.Hspec.Core.Spec
import Test.Hspec.Core.Hooks
import Test.Hspec.Runner
import Test.Hspec.Expectations
-- | @example@ is a type restricted version of `id`. It can be used to get better
-- error messages on type mismatches.
--
-- Compare e.g.
--
-- > it "exposes some behavior" $ example $ do
-- > putStrLn
--
-- with
--
-- > it "exposes some behavior" $ do
-- > putStrLn
example :: Expectation -> Expectation
example = id
-- | @context@ is an alias for `describe`.
context :: String -> SpecWith a -> SpecWith a
context = describe
-- | @specify@ is an alias for `it`.
specify :: Example a => String -> a -> SpecWith (Arg a)
specify = it
| beni55/hspec | src/Test/Hspec.hs | mit | 1,331 | 0 | 10 | 284 | 221 | 146 | 75 | 39 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import qualified Control.Concurrent as Conc
import Criterion (bench, bgroup)
import Criterion.Main (defaultMain, nfIO)
import Data.Default (def)
import qualified Frinfo.Structure as F
import qualified Frinfo.Free as FF
import qualified Frinfo.INotify as IN
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
main :: IO ()
main = do
songMVar <- Conc.newMVar "Test Song"
emailMVar <- Conc.newMVar 0
let staticS = def :: FF.StaticState
dynamicS = def :: FF.SystemState
stat = staticS { FF._dbusState = songMVar, FF._emailState = emailMVar}
defaultMain
[ bgroup "frinfo"
[ bench "PrintDzen" $ nfIO $ do
(t, _) <- FF.runFree stat dynamicS (FF.printDzen F.freeStruc)
return . TL.toStrict . TLB.toLazyText $ t
]
, bgroup "INotify"
[ bench "NewFolders" $ nfIO IN.allNewFolders
, bench "TotalFiles" $ nfIO $ IN.getTotalFiles "/home/arguggi/Downloads"
]
]
| Arguggi/Frinfo | benchmark/Main.hs | mit | 1,091 | 0 | 18 | 283 | 302 | 170 | 132 | 26 | 1 |
{-
TRANSFORMERZ - Monad Transformer in vanilla Haskell
Nothing imported - just code
Author: Marco Faustinelli ([email protected])
Web: http://faustinelli.net/
http://faustinelli.wordpress.com/
Version: 1.0
The MIT License - Copyright (c) 2015 Transformerz Project
-}
module TestNilsson_20 where
import Data.Maybe
import qualified Data.Map as Map
import Text.Show.Functions
import Test.HUnit
import Nilsson_01
ex2a :: ST Int (ET I) Int
ex2a = eHandle (sSet 3 >> eFail) sGet
testRunST :: Test
testRunST =
TestCase $ assertEqual "Nilsson's runST returns m a, not m (a, s)"
(0) (runI $ runST sGet 0)
testEx2a :: Test
testEx2a =
TestCase $ assertEqual "Nilsson's runST returns m a, not m (a, s)"
(0) (runI $ runET $ runST ex2a 0)
-------------------------------
ex2b :: ET (ST Int I) Int
ex2b = eHandle (sSet 3 >> eFail) sGet
testRunET :: Test
testRunET =
TestCase $ assertEqual "Nilsson's runET returns m a, not m (Maybe a)"
(10) (runI $ runST (runET sGet) 10)
testEx2b_run :: Test
testEx2b_run =
TestCase $ assertEqual "Nilsson's runET saves the day in case of eFail ?!?!?!?!?!?"
(3) (runI $ runST (runET ex2b) 0)
testEx2b_un :: Test
testEx2b_un =
TestCase $ assertEqual "Nilsson's unET returns (Maybe a, s)"
(Just 3, 3) (unI $ unST (unET ex2b) 0)
{--}
main :: IO Counts
main = runTestTT $ TestList [
testRunST,
testEx2a,
testRunET,
testEx2b_run,
testEx2b_un
]
| Muzietto/transformerz | haskell/nilsson/TestNilsson_20.hs | mit | 1,557 | 0 | 11 | 408 | 353 | 191 | 162 | 37 | 1 |
module Main (main) where
import Data.List (isSuffixOf)
import System.Environment (setEnv)
import XMonad.Actions.CycleWS
import XMonad.Actions.DwmPromote
import XMonad.Actions.FlexibleManipulate hiding (position)
import XMonad.Actions.WithAll
import XMonad.Config.Gnome (gnomeRegister)
import XMonad.Hooks.EwmhDesktops
import XMonad.Layout.TrackFloating
import XMonad.Util.Cursor
import XMonad.Util.EZConfig
import qualified Data.Map as M
import qualified XMonad.StackSet as W
import Audio
import Background
import Bluetooth
import Byzanz
import Focus
import Gist
import Imports
import Misc
import Prompt
import RedShift
import Roam
import ScreenLock
import Screens
import Scrot
import Spotify
import TallWheel
import Tmux
import Todoist
import Touchpad
import WeeklyReview
main :: IO ()
main = do
env <- initEnv
putStrLn $ "Unused M-alpha leaders: "
++ show (unusedAlphaLeaders (keymap env))
xmonad $ ewmh $ def
{ borderWidth = 0
, modMask = mod4Mask
, terminal = unwords (terminalCmd : terminalArgs)
, workspaces = workspaceNames
, startupHook = printErrors env "Startup hook" $ withEnv env startup
, layoutHook = trackFloating $ TallWheel 1 (phi / 8) phi ||| Full
, manageHook = printErrors env "Manage hook" (manageHooks env)
, keys = const M.empty
, mouseBindings = const M.empty
}
`additionalMouseBindings` mouse env
`additionalKeysP` keymap env
startup :: XX ()
startup = do
withScreenInitiallyLocked everyRunAction initialStartupAction
where
everyRunAction :: Bool -> XX ()
everyRunAction isStart = do
-- Registers xmonad with the session manager.
toXX gnomeRegister
-- Sets the mouse pointer.
toXX $ setDefaultCursor xC_left_ptr
-- Start redshift, to tint colors at night
when isStart redShiftStart
-- Periodically choose a new random background. Recompiles will
-- restart this, but I don't mind that.
forkXio $ forever $ do
liftIO $ threadDelay (60 * 60 * 1000 * 1000) -- One hour
randomBackground
initialStartupAction :: Xio ()
initialStartupAction = do
startupLogTerminals
startupWirelessTerminals
startupInitialApplications
startupMisc
-- Choose a random desktop background
randomBackground
-- | Starts terminals that show latest errors from this boot, and most
-- recent log output from processes started by xmonad.
startupLogTerminals :: Xio ()
startupLogTerminals = do
let baseCmd = "journalctl --output short-precise --follow"
spawnOrReplaceInteractiveTmuxShellOn "9" "syslog"
$ baseCmd ++ " | ccze -A"
spawnOrReplaceInteractiveTmuxShellOn "9" "errlog"
$ baseCmd ++ " --priority err --boot | errlog-filter | ccze -A"
-- | Starts terminals used for controlling wifi and bluetooth. In the
-- case of the bluetooth terminal,
startupWirelessTerminals :: Xio ()
startupWirelessTerminals = do
spawnOrReplaceInteractiveTmuxShellOn "0" "bt" "bluetoothctl"
spawnOrReplaceInteractiveTmuxShellOn "0" "wifi" "nmtui connect"
-- | Starts a tmux session running nvtop and htop.
topTerminals :: Xio ()
topTerminals = do
killTmuxSession "tops"
spawn "urxvt" $ terminalArgs ++
[ "new-session", "-s", "tops"
, "-n", "nvtop", interactiveShellCommand "nvtop"
, ";", "new-window", "-n", "htop", interactiveShellCommand "htop"
]
-- | Detect screen configuration, and launch default applications on
-- appropriate workspaces.
startupInitialApplications :: Xio ()
startupInitialApplications = do
-- This is done in another thread, because it initially blocks on
-- getting xrandr screen configuration output.
forkXio $ do
screenConfiguration <- detectScreens
let spawnEmacs ws = spawnOn ws "emacs" []
spawnChrome ws = spawnOn ws "google-chrome" []
case screenConfiguration of
BigScreen -> do
spawnEmacs "1"
spawnChrome "1"
_ -> do
spawnEmacs "1"
spawnChrome "2"
spawnOn "7" "spotify" []
configureScreens screenConfiguration
startupMisc :: Xio ()
startupMisc = do
-- Disable touchpad initially
setTouchpad initialValue
-- Start keynav, to drive mouse via keyboard
spawn "keynav" []
-- Start dunst, for notifications
spawn "dunst" []
-- Apply keyboard remappings
homeDir <- view envHomeDir
spawn (homeDir </> "env/scripts/xmodmap-on-input-change.sh") []
-- Create directories used for output
createDirectoryIfMissing True (homeDir </> "pics/screenshots")
createDirectoryIfMissing True (homeDir </> "pics/screenshots-large")
createDirectoryIfMissing True (homeDir </> "pics/screencaps")
manageHooks :: Env -> ManageHook
manageHooks env
= composeAll
$ [ manageSpawn env
-- , debugManageHook env
, title =? "Desktop" --> doShift "0"
]
mouse :: Env -> [((KeyMask, Button), Window -> X ())]
mouse env = [((mod4Mask, button1), mouseManipulate)]
where
mouseManipulate = printErrors env "mouse handler:" . mouseWindow discrete
keymap :: Env -> [(String, X ())]
keymap env =
map (printHandlerErrors env . second (withEnv env)) $
-- M-[1..] Switch to workspace N
-- M-S-[1..] Move client to workspace N
-- M-C-[1..] Switch to workspace N on other screen
[ (m ++ "M-" ++ i, warpMid $ f i)
| i <- workspaceNames
, (f, m) <- [ (focusWorkspace, "")
, (toXX . windows . W.shift, "S-")
, ((toXX nextScreen >>) . focusWorkspace, "C-")
]
] ++
[
-- Recompile and restart XMonad
("M-q", forkXio $ do
notify "Recompile + restart"
home <- view envHomeDir
syncSpawnStderrInfo (home </> "env/scripts/rebuild.sh") [] `onException` do
notify "Failed recompilation"
-- NOTE: it might be cleaner to invoke the 'restart' function
-- directly. However, it works within the X monad (which uses
-- StateT), and therefore cannot be used in a forked thread. So,
-- instead, use the X11 message queue to deliver the restart
-- message to the handler.
liftIO sendRestart)
-- Layout manipulation
, ("M-<Space>", warpMid $ toXX $ sendMessage NextLayout)
-- Focus / switch windows between screens
, ("M-u", focusScreen 2)
, ("M-i", focusScreen 1)
, ("M-o", focusScreen 0)
, ("M-S-u", moveToScreen 2)
, ("M-S-i", moveToScreen 1)
, ("M-S-o", moveToScreen 0)
-- Window navigation / manipulation
, ("M-k", warpMid $ toXX $ windows W.focusDown)
, ("M-j", warpMid $ toXX $ windows W.focusUp)
, ("M-S-k", warpMid $ toXX $ windows W.swapDown)
, ("M-S-j", warpMid $ toXX $ windows W.swapUp)
-- Window kill
, ("M-S-c", toXX kill)
-- Focus / switch master
, ("M-h", warpMid $ toXX $ windows W.focusMaster)
, ("M-S-h", warpMid $ toXX $ dwmpromote)
-- Sink floating windows
, ("M-t", toXX . withFocused $ windows . W.sink) -- from default
, ("M-S-t", toXX sinkAll)
-- Change number of windows in master region
, (("M-,"), warpMid . toXX . sendMessage $ IncMasterN 1)
, (("M-."), warpMid . toXX . sendMessage $ IncMasterN (-1))
-- Change size of master region
, ("M-l", toXX $ sendMessage Shrink)
, ("M-;", toXX $ sendMessage Expand)
-- Start programs or navigate to them
, ("M-p", shellPrompt)
-- Spawn terminal
, ("M-S-<Return>", spawn terminalCmd terminalArgs)
-- Start common programs with one key-press
, ("M-e", spawn "emacs" [])
, ("M-s", spawn "slock" [])
, ("M-g M-h", gistFromClipboard "paste.hs")
, ("M-g M-m", gistFromClipboard "paste.md")
, ("M-g M-p", gistFromClipboard "paste.txt")
-- Spotify control
, ("M-m M-l", spotifyLikeCurrentTrack)
, ("M-m M-m", spotifyTogglePlay)
, ("M-<Left>", spotifyPrevious)
, ("M-<Right>", spotifyNext)
, ("M-<Up>", spotifyAddToVolume 5)
, ("M-<Down>", spotifyAddToVolume (-5))
, ("M-S-<Up>", spotifySetVolume 100)
, ("M-S-<Down>", spotifySetVolume 0)
, ("M-m M-d", spotifyDebugPlayerInfo)
, ("M-S-/", forkXio spotifyNotifyTrack)
-- Brightness control
, ("M-S-=", spawn (_envHomeDir env </> "env/scripts/brightness-increase.sh") ["30"])
, ("M-S--", spawn (_envHomeDir env </> "env/scripts/brightness-decrease.sh") ["30"])
, ("M-=", spawn (_envHomeDir env </> "env/scripts/brightness-set.sh") ["100000000"])
, ("M--", spawn (_envHomeDir env </> "env/scripts/brightness-set.sh") ["40"])
-- Volume control
, ("M-S-f", forkXio $ unmuteAudio >> volumeUp)
, ("M-S-d", forkXio $ unmuteAudio >> volumeDown)
, ("M-f", forkXio $ unmuteAudio >> volumeMax)
, ("M-d", forkXio toggleAudio)
-- Media button versions of audio control
, ("<XF86AudioRaiseVolume>", forkXio $ unmuteAudio >> volumeUp)
, ("<XF86AudioLowerVolume>", forkXio $ unmuteAudio >> volumeDown)
, ("<XF86AudioMute>", forkXio toggleAudio)
, ("<XF86AudioMicMute>", forkXio toggleMicrophone)
-- Context dependent play / pause
, ("<XF86AudioPlay>", do
mt <- runQuery title
forkXio $ do
let mightBeVideo =
case debug "mightBeVideo title" mt of
Nothing -> False
Just t ->
"Netflix - Google Chrome" == t ||
" - YouTube - Google Chrome" `isSuffixOf` t ||
" | Prime Video - Google Chrome" `isSuffixOf` t ||
" | Coursera - Google Chrome" `isSuffixOf` t
if mightBeVideo
then do
-- For some reason, running xdotool directly doesn't work,
-- but running it in a temrinal does.
--
-- TODO: runQuery getWindowId as input to this
spawnOn "0" "urxvt" $ ["-e", "xdotool", "getwindowfocus", "key", "space"]
spotifyStop
else spotifyTogglePlay)
-- Screenshotting and gif recording
, ("M-r", forkXio scrot)
, ("M-S-r", byzanzPrompt)
-- Get logs for focused window
, ("M-y", do
mpid <- getPidOfFocus
case mpid of
Nothing -> return ()
Just pid -> forkXio $ do
allPids <- (pid :) <$> getParentPids pid
spawn "urxvt" $ terminalArgs ++ ["new-session", unwords $
["bash -c \"journalctl --boot --follow"]
++ map (\p -> "_PID=" ++ show p) allPids ++
["| ccze -A | less -R\""]])
-- Random background
, ("M-b M-g", forkXio randomBackground)
-- Add todoist task
, ("M-a", addTodoistTask)
-- TODO: fix - running nightwriter causes it to fail to grab keyboard
-- , ("M-z", forkXio $ spawn "nightwriter" [])
-- Actions which seem too specialized / one-off to have
-- keybindings. Nicer to just have a set of commands than filling up
-- the keyboard with random shortcuts.
, ("M-x", actionPrompt $ M.fromList $
[ ("weekly-review", forkXio weeklyReview)
-- Optional daily review if I feel like it.
, ("daily-review", forkXio dailyReview)
, ("update-backgrounds-list", forkXio $ void updateBackgrounds)
, ("touchpad-toggle", touchpadToggle)
, ( "connect-headphones"
, forkXio (bluetoothConnect "headphones" envHeadphonesUuid)
)
, ( "disconnect-headphones"
, forkXio (bluetoothDisconnect "headphones" envHeadphonesUuid)
)
, ( "connect-receiver"
, forkXio (bluetoothConnect "receiver" envReceiverUuid)
)
, ( "disconnect-receiver"
, forkXio (bluetoothDisconnect "receiver" envReceiverUuid)
)
, ("xrandrize", forkXio (detectScreens >>= configureScreens))
, ("dunst-toggle", forkXio dunstToggle)
, ("redshift-toggle", redShiftToggle)
-- Expose some parts of startup as commands so that they can be
-- iterated on without doing a restart.
, ("startup-log-terminals", forkXio startupLogTerminals)
, ("startup-wireless-terminals", forkXio startupWirelessTerminals)
, ("startup-initial-applications", forkXio startupInitialApplications)
, ("startup-misc", forkXio startupMisc)
, ("tops", forkXio topTerminals)
, ("invert-screen", forkXio $ spawn "xrandr" ["--output", "eDP-1", "--rotate", "inverted"])
, ("normal-screen", forkXio $ spawn "xrandr" ["--output", "eDP-1", "--rotate", "normal"])
, ("normal-dpi", liftIO $ do
setEnv "GDK_SCALE" "1"
setEnv "GDK_DPI_SCALE" "1")
, ("medium-dpi", liftIO $ do
setEnv "GDK_SCALE" "1.5"
setEnv "GDK_DPI_SCALE" "0.75")
, ("high-dpi", liftIO $ do
setEnv "GDK_SCALE" "2"
setEnv "GDK_DPI_SCALE" "0.75")
, ("lock", lockWorkspaceSwitching)
, ("unlock", unlockWorkspaceSwitching)
] ++ roamTemplates)
-- NOTE: Following keys taken by other things in this config:
--
-- * M-v taken by keynav, to simulate middle click paste.
--
-- * M-n and M-S-n taken by dunst, for clearing notifications.
--
-- * M-` taken by dunst, for viewing notification history.
]
| mgsloan/compconfig | env/src/xmonad.hs | mit | 12,775 | 0 | 25 | 2,905 | 2,827 | 1,566 | 1,261 | 250 | 4 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UnicodeSyntax #-}
module TT.Judgement.Bidirectional where
import Control.Applicative
import Control.Lens
import Control.Monad
import Control.Monad.Error.Class
import Prelude.Unicode
import Unbound.LocallyNameless hiding (Equal, Refl)
import TT.Eval
import TT.Judgement.Class
import TT.Judgement.Contains
import TT.Judgement.Hypothetical
import TT.Tele
import TT.Tm
data Chk
= Chk Tm Tm
data Inf
= Inf Tm
deriving Show
data Equal
= Equal Tm (Tm, Tm)
data EqualTypes
= EqualTypes Tm Tm
data IsType
= IsType Tm
infixl 9 :⇐
pattern m :⇐ α = Chk m α
derive [''Chk, ''Inf, ''Equal, ''IsType, ''EqualTypes]
instance Alpha Chk
instance Alpha Inf
instance Alpha Equal
instance Alpha IsType
instance Alpha EqualTypes
instance Judgement (Hypothetical IsType) Int where
judge j@(_ :⊢ IsType (Univ n))
| n ≥ 0 = return $ succ n
| otherwise = trace j $ throwError InvalidUniverse
judge (_ :⊢ IsType Unit) = return 0
judge (_ :⊢ IsType Void) = return 0
judge j@(γ :⊢ IsType (Plus α β)) =
trace j $ max
<$> judge (γ ⊢ IsType α)
<*> judge (γ ⊢ IsType β)
judge j@(γ :⊢ IsType (Pi α xβ)) =
trace j $ max
<$> judge (γ ⊢ IsType α)
<*> do
(x, β) ← unbind xβ
judge $ γ >: (x :∈ α) ⊢ IsType β
judge j@(γ :⊢ IsType (Id α (m, n))) =
trace j $ do
l ← judge $ γ ⊢ IsType α
judge $ γ ⊢ m :⇐ α
judge $ γ ⊢ n :⇐ α
return l
judge j@(γ :⊢ IsType (V x)) =
trace j $ do
τ ← judge $ γ :∋ x
τ ^? _Univ <?> ExpectedUniverse
judge j = trace j $ throwError ExpectedType
instance Judgement (Hypothetical Inf) Tm where
judge j@(γ :⊢ Inf (V x)) =
trace j ∘ judge $ γ :∋ x
judge j@(γ :⊢ Inf (Ann m α)) =
trace j $ do
judge $ γ ⊢ m :⇐ α
return α
judge (_ :⊢ Inf (Univ n)) = return $ Univ (succ n)
judge (_ :⊢ Inf Unit) = return $ Univ 0
judge (_ :⊢ Inf Void) = return $ Univ 0
judge (γ :⊢ Inf τ@Plus{}) =
Univ <$> judge (γ ⊢ IsType (eval τ))
judge (γ :⊢ Inf τ@Pi{}) =
Univ <$> judge (γ ⊢ IsType (eval τ))
judge (γ :⊢ Inf τ@Id{}) =
Univ <$> judge (γ ⊢ IsType (eval τ))
judge (_ :⊢ Inf Ax) = return Unit
judge j@(γ :⊢ Inf (Refl m)) =
trace j $ do
α ← judge $ γ ⊢ Inf m
let m' = eval m
return $ Id (eval α) (m', m')
judge j@(γ :⊢ Inf (App m n)) =
trace j $ do
τ ← judge $ γ ⊢ Inf m
(α, xβ) ← τ ^? _Pi <?> ExpectedPiType
judge $ γ ⊢ n :⇐ α
(x, β) ← unbind xβ
return ∘ eval $ subst x m β
judge j@(γ :⊢ Inf (Decide xc m ul vr)) =
trace j $ do
τ ← judge $ γ ⊢ Inf m
(α, β) ← τ ^? _Plus <?> ExpectedSumType
(x,c) ← unbind xc
(u,l) ← unbind ul
_ ← judge $ γ >: (x :∈ τ) ⊢ IsType (eval c)
judge $ γ >: (u :∈ α) ⊢ l :⇐ subst x (Inl (V u)) c
(v,r) ← unbind vr
judge $ γ >: (v :∈ β) ⊢ r :⇐ subst x (Inr (V v)) c
return $ subst x m c
judge j@(γ :⊢ Inf (IdPeel xypc idp ur)) =
trace j $ do
τ ← judge $ γ ⊢ Inf idp
(α, (m, n)) ← τ ^? _Id <?> ExpectedIdentityType
((x,y,p), c) ← unbind xypc
_ ← judge $
let δ = γ >: (x :∈ α) >: (y :∈ α) >: (p :∈ Id α (V x, V y))
in δ ⊢ IsType (eval c)
(u, r) ← unbind ur
judge $
let cuu = subst x (V u) $ subst y (V u) $ subst p (Refl (V u)) c
in γ >: (u :∈ α) ⊢ r :⇐ cuu
return ∘ eval ∘ subst x m ∘ subst y n $ subst p idp c
judge j = trace j $ throwError NotImplemented
instance Judgement (Hypothetical Chk) () where
judge j@(γ :⊢ τ :⇐ Univ n) =
trace j $ do
l ← judge $ γ ⊢ IsType (eval τ)
unless (l < succ n) $
throwError UniverseCycle
judge j@(γ :⊢ Inl m :⇐ Plus α β) =
trace j $ do
judge $ γ ⊢ m :⇐ α
_ ← wf ∘ judge $ γ ⊢ IsType (eval β)
return ()
judge j@(γ :⊢ Inr m :⇐ Plus α β) =
trace j $ do
judge $ γ ⊢ m :⇐ β
_ ← wf ∘ judge $ γ ⊢ IsType (eval α)
return ()
judge j@(γ :⊢ Lam xm :⇐ Pi α yβ) =
trace j $ do
(x, m) ← unbind xm
(y, β) ← unbind yβ
judge $ γ >: (x :∈ α) ⊢ m :⇐ subst y (V x) β
judge j@(γ :⊢ Refl m :⇐ Id α (n, n')) =
trace j $ do
judge $ γ ⊢ Equal α (m, n)
judge $ γ ⊢ Equal α (m, n')
judge j@(γ :⊢ m :⇐ α) =
trace j $ do
α' ← judge $ γ ⊢ Inf m
_ ← wf ∘ judge $ γ ⊢ EqualTypes α α'
return ()
judge _ = error "This is total"
instance Judgement (Hypothetical Equal) () where
judge j@(γ :⊢ Equal α (m,n)) =
trace j $ do
judge $ γ ⊢ m :⇐ α
judge $ γ ⊢ n :⇐ α
unless (eval m `aeq` eval n) ∘ throwError $
NotEqual m n
judge _ = error "This is total"
instance Judgement (Hypothetical EqualTypes) Int where
judge j@(γ :⊢ EqualTypes α β) =
trace j $ do
l ← judge $ γ ⊢ IsType (eval α)
l' ← judge $ γ ⊢ IsType (eval β)
let l'' = max l l'
judge $ γ ⊢ Equal (Univ l'') (α, β)
return l''
judge _ = error "This is total"
instance Show Chk where
showsPrec i (Chk m α) =
showParen (i > 10) $
shows m ∘ (" ⇐ " ++) ∘ shows α
instance Show Equal where
showsPrec i (Equal α (m,n)) =
showParen (i > 10) $
shows m ∘ (" = " ++) ∘ shows n ∘ (" : " ++) ∘ shows α
instance Show EqualTypes where
showsPrec i (EqualTypes α β) =
showParen (i > 10) $
shows α ∘ (" = " ++) ∘ shows β ∘ (" type" ++)
instance Show IsType where
showsPrec i (IsType α) =
showParen (i > 10) $
shows α ∘ (" type" ++)
| jonsterling/itt-bidirectional | src/TT/Judgement/Bidirectional.hs | mit | 6,051 | 1 | 20 | 1,801 | 2,997 | 1,477 | 1,520 | 183 | 0 |
{-|
Module : Control.Flower.Compose
Description : Directional composition combinators
-}
module Control.Flower.Compose ((<.), (.>)) where
{- $setup
>>> import Control.Flower.Apply.Lazy
>>> let x = 3
>>> let y = 4
>>> let f = (+2)
>>> let g = (*2)
>>> let h = (+)
-}
{-| Right-flowing, left-associative composition
Note that this is the opposite direction from typical composition
>>> (f .> g) x == (g . f) x
True
Can be combined with application combinators
>>> 5 |> (+1) .> (*10) :: Int
60
-}
infixl 9 .>
(.>) :: (a -> b) -> (b -> c) -> a -> c
a .> b = b . a
{-| Left-flowing, right-associative composition
>>> (g <. f) x == (g . f) x
True
Can be combined with application combinators
>>> (+1) <. (*10) <| 5 :: Int
51
-}
infixr 9 <.
(<.) :: (b -> c) -> (a -> b) -> a -> c
b <. a = b . a
| expede/flower | src/Control/Flower/Compose.hs | mit | 808 | 0 | 8 | 184 | 129 | 76 | 53 | 7 | 1 |
{-# LANGUAGE Rank2Types #-}
--
module Main where
import Data.List
import Data.Function
import Data.Monoid
import Options.Applicative
import Control.Applicative -- Compiler slow
{-
basic comments
-}
{- Basics
-- Type
True
sort [1, 2, 3, 4]
case Foo of True -> 1
False -> 2
-- let scope
let x = 3 * a
y = 4 * a
in sqrt (x^2 + y^2)
-- basic binding
addOne :: Int -> Int
addOne x = x + 1
welcomeMsg :: String
welcomeMsg = "Hello world"
-- lexical scope
let x = 1
in let y = x * 2
in x + y
-- prefix <-> infix
(+) 2 3 == 2 + 3
l = [1] ++ [] ++ [2, 3, 4]
elem 3 [1, 2, 3] == 3 `elem` [1, 2, 3]
-- Precedence
-- Simple Func > 0-9 infix
-- infix/infixl/infixr (default `f` == infixl 9)
-- 3 * -2 -- Error! - : simple func neg | infix 6 sub
-- :: the lowest precedence
-}
{- Ch2: Data and pattern-matching -}
-- data: declare T + declare T's constructor
-- ctor/record in T is global
data T = ConstructorT Int
-- ConstructorT 1 :: T
ti :: T
ti = ConstructorT 1
-- or
data U = U Int
-- U 1 :: U
u1 :: U
u1 = U 1
-- or
data V = Int :+ Int
-- 1 :+ 2 :: V
-- (:+) 1 2 :: V
v1 :: V
v1 = 1 :+ 2
v_norm2 :: V -> V -> Double
v_norm2 v1 v2 = case v1 of
x1 :+ y1 ->
case v2 of
x2 :+ y2 ->
sqrt (fromIntegral ((x1 - x2)^2 + (y1 - y2)^2))
v_norm2_alter :: V -> V -> Double
v_norm2_alter (x1 :+ y1) (x2 :+ y2) = sqrt (fromIntegral ((x1 - x2)^2 + (y1 - y2)^2))
v_norm2_alter2 :: V -> V -> Double
v_norm2_alter2 v1 v2 = let x1 :+ y1 = v1
x2 :+ y2 = v2
in sqrt (fromIntegral ((x1 - x2)^2 + (y1 - y2)^2))
-- as-mode
-- x@y (if matches x then binding y)
v_norm2_pattern :: V -> V -> Double
v_norm2_pattern v1@(x1 :+ y1) v2@(x2 :+ y2) = sqrt (fromIntegral ((x1 - x2)^2 + (y1 - y2)^2))
-- multiple ctor
data Pos = Cartesian Double Double | Polar Double Double
-- no parameter ctor
data SelfBool = STrue | SFalse
match_self_bool :: Bool -> Int
match_self_bool v = if v then 1
else 2
-- parametric polymorphism
data PosP a = PosP a a Double
posp1 :: PosP Int
posp1 = PosP 1 1 2.4
posp2 = PosP 2 2 3 :: PosP Double
-- maybe
int_div :: Int -> Int -> Double
int_div = (/) `on` fromIntegral
self_div :: Double -> Double -> Maybe Double
self_div a b = case b of
0 -> Nothing
_ -> Just (a / b)
-- record syntax
data PosR = MakePosR { getX :: Double, getY :: Double }
-- data Vec = MakeVec { getX :: Int, getY :: Int } Multiple defintion
posr1 = MakePosR 3 4
{- Ch3: List/Recursion -}
-- data [a] = a : [a] | []
-- List a = Nil | a : List a
-- [1, 2, 3] -> 1 : 2 : 3 : []
sample_l1 = [10, 9..0] -- 10, 9 ... (If use [2, 9..0] -> empty list)
sample_p4 = sample_l1 !! 4
-- (:) :: a -> [a] -> [a]
-- !! partial function (!! [] n will cause error)
-- !!! total function
totaln :: [a] -> Int -> Maybe a
totaln [] _ = Nothing
totaln (x : xs) 0 = Just x
totaln (x : xs) n = totaln xs (n-1)
infixl 9 !!!
(!!!) :: [a] -> Int -> Maybe a -- section infix -> simple
a !!! b = totaln a b
{- Ch4, Ch5: Tuple/Type Inference/High-order Function -}
-- data (,) a b = (,) a b Tuple, max 62
tp1 = (1, 2, 3) :: (Int, Float, Double)
tp2 = (,,) 1 2 3 :: (Int, Float, Double)
unit_t = () :: () -- von Neumann Peano
-- high order
-- (->) :: * -> * -> * (infixr 0) Parameters: Types, Return: Types -> Type Function
subscbfiveimpl :: [(Int, a)] -> [a]
subscbfiveimpl [] = []
subscbfiveimpl ((i, x) : xs) = case i `rem` 5 of
0 -> x : subscbfiveimpl xs
_ -> subscbfiveimpl xs
-- zip
zip_alt :: [a] -> [b] -> [(a, b)]
zip_alt [] _ = []
zip_alt _ [] = []
zip_alt (x:xs) (y:ys) = (x, y) : zip_alt xs ys
subscbfive :: [a] -> [a]
subscbfive [] = []
subscbfive xs = subscbfiveimpl (zip_alt [1..(length xs)] xs)
zip_with :: (a -> b -> c) -> [a] -> [b] -> [c]
zip_with _ _ [] = []
zip_with _ [] _ = []
zip_with f (x : xs) (y : ys) = f x y : zip_with f xs ys
-- curry
curry_alt :: ((a, b) -> c) -> a -> b -> c
curry_alt f x y = f (x, y)
uncurry_alt :: (a -> b -> c) -> (a, b) -> c
uncurry_alt f (x, y) = f x y
-- $ &
-- ($) :: (a -> b) -> a -> b (infixr 0)
-- f $ x = f x
-- replace f (x y z) -> f $ x $ y z
-- just pipeline
-- |> = &
-- <| = $
-- lambda function
sample_lambda1v = 3 & (\x -> x + 1) & (\x -> x + 2) -- 6
-- .
-- (.) :: (b -> c) -> (a -> b) -> a -> c -- Or BCKW B
-- f . g = \x -> f(g x) (infixr 9)
from_a_to_b = toEnum . (+1) . fromEnum $ 'a' :: Char -- 'b'
-- where
where_func :: [a] -> [a]
where_func xs = a_func $ zip [0..] xs
where
a_func [] = []
a_func ((i, x):xs) = if i `rem` 5 == 0 then x : a_func xs
else a_func xs
-- everywhere binding happen can use where
-- eg: case ... of ... where ... | let ... where ... in ...
-- Alt case conditition : ref: https://wiki.haskell.org/Case#Guards
-- guard
guard_func :: (Num a, Ord a, Eq a) => a -> String
guard_func x
| x' < 0 = "negative"
| x' == 0 = "zero"
| x' > 0 = "positive"
| otherwise = "hodouni"
where x' = x
multi_way_alt :: (Eq a) => a -> String
multi_way_alt x = case () of _
| x == x -> "Always True"
| otherwise -> "Always False"
-- point-free (eta-conversion in λ)
-- α-conversion : \x f x -> \y f y
-- β-reduction : \x f x z -> f z
-- η-conversion : \x f x == \x g x -> f == g
nextChar_less :: Char -> Char
nextChar_less = toEnum . (+1) . fromEnum
nextChar_full :: Char -> Char
nextChar_full = toEnum . (+1) . fromEnum
-- (.) . (.) :: (b -> c) -> (a1 -> a -> c) -> a1 -> a -> c
-- on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
-- (*) `on` f = \x y -> f x * f y
{- Ch6 List Operation -}
-- map
-- map :: (a -> b) -> [a] -> [b]
-- map _ [] = []
-- map f (x : xs) = f x : map f xs
-- filter
-- filter f (x : xs) = | f x = x : filter f xs
-- | = filter f xs
-- foldr --> primitive recursive
-- foldl (not work on infinite lists)
-- foldr (work on infinite lists)
foldr_alt :: (b -> a -> a) -> a -> [b] -> a
foldr_alt _ a [] = a
foldr_alt f a (x:xs) = f x $ foldr_alt f a xs
foldl_alt :: (a -> b -> a) -> a -> [b] -> a
foldl_alt _ a [] = a
foldl_alt f a (x:xs) = foldl_alt f (f a x) xs
foldl_reverse :: (a -> b -> a) -> a -> [b] -> a
foldl_reverse f a bs = foldr_alt (\b' a' -> f a' b') a (reverse bs)
-- save it on the closure, thus gf must match (b -> x -> x) -> x -> [b] -> x
-- x :: a -> a
-- gf :: b -> (a -> a) -> (a -> a)
foldl_foldr :: (a -> b -> a) -> a -> [b] -> a
foldl_foldr f a bs = foldr_alt (\b g x -> g $ f x b) id bs a
-- foldl f a bs = f (f z b0) b1
-- -> foldr gf id bs a
-- -> gf b0 (gf b1 id) a
-- -> gf b1 id (f a b0)
-- -> id $ f (f a b0) b1
-- for finite lists
foldr_foldl :: (b -> a -> a) -> a -> [b] -> a
foldr_foldl f a bs = foldl_alt (\g b x -> g $ f b x) id bs a
-- use foldl' instead, since foldl is lazy (evaluated at final saturation)
-- scanl
scanl_alt :: (b -> a -> b) -> b -> [a] -> [b]
scanl_alt f b ls = b : (
case ls of
[] -> []
x:xs -> scanl f (f b x) xs
)
scanr_alt :: (a -> b -> b) -> b -> [a] -> [b]
scanr_alt f b (x:xs) =
f x (head ys) : ys
where
ys = scanr_alt f b xs
{- Ch7 Typeclass -}
-- Constraints (=>) 也是 Mapping (->),但是其参数是一个包含了 Show instance 实现的 record
data PosTC = CartesianTC Double Double | PolarTC Double Double
-- deriving: auto-derive typeclass
data PosTCD = CartesianTCD Double Double | PolarTCD Double Double
deriving Eq
{-
-- declare typeclass Eq (interface[java] / traits[rust] / require[c++] / CRTP[no need of /=])
-- interface in typeclass is global (can be determined by following type deduction)
class Eq a where
(==), (/=) :: a -> a -> Bool
x /= y = not (x == y)
x == y = not (x /= y)
-- Interestingly, typeclass can auto-select interface...
class (Eq a) => Ord a where
compare :: a -> a -> Ordering -- data Ordering = LT | EQ | GT
(<), (<=), (>=), (>) :: a -> a -> Bool
max, min :: a -> a -> a
compare x y | x == y = EQ
| x <= y = LT
| otherwise = GT
max...
min...
<=...
<...
>=...
>...
-}
-- declare PosTC as instance of Eq (realize (==))
instance Eq PosTC where
CartesianTC x1 y1 == CartesianTC x2 y2 = (x1 == x2) && (y1 == y2)
PolarTC x1 y1 == PolarTC x2 y2 = (x1 == x2) && (y1 == y2)
CartesianTC x y == PolarTC a r = (x == r * cos a) && (y == r * sin a)
PolarTC a r == CartesianTC x y = (x == r * cos a) && (y == r * sin a)
{-# LANGUAGE InstanceSigs #-}
{-
instance Eq A where
(==) :: A -> A -> Bool
x == y = ...
-}
-- can-derived typeclass
-- Eq/Ord/Enum/Bounded/Show/Read
-- GHC: Functor/Foldable/Traversable/Typeable/Generics
-- Show -> how to print
-- Read -> how to parse
read_alt :: (Read a) => String -> a
read_alt s = case [x | (x, t) <- reads s, ("", "") <- lex t] of
[x] -> x
[] -> error "PreludeText.read: no parse"
_ -> error "PreludeText.read: ambiguous parse"
-- read (show (x :: a)) :: a = x (May not True)
{-
class (Monad m) => Streams s m t | s -> t where
uncons :: s -> m (Maybe (t, s))
-- Here s -> t represents
-- for any s, only one type of t is allowed in instance
-- So, if we have s, we can decide t
parse :: Stream s Identity t => Parse s () a -> SourceName -> s -> Either ParseError a
-- 比如,不能一个 instance 是 s 是 ByteString t 是 Char,另一个 s 是 ByteString t 是 Word8
-- 比如我们 s 那个参数传一个 String 进去
-- 那,s ~ String,我们发现有一个 instance Monad m => Stream [tok] m tok,那么我们就可以确定 t ~ Char 了(note that String ~ [Char]
-}
{- Ch8 Number Typeclass -}
-- Ord (default: lexicographical order)
-- compare/max/min/(<)/(<=)/(>=)/(>)
-- Never restrict data by typeclass
-- Enum
-- succ/pred/enumFrom/enumFromThen [x, y..]/enumFromTo [x..y]/enumFromThenTo [x, x'..y]
-- [m, n..l] is enum
data SPet = Dog | Cat | Bird | Turtle
deriving (Enum, Show)
-- enumFromTo Dog Bird == [Dog, Cat, Bird]
-- Bounded
-- maxBound/minBound
-- Num
-- (+)/(-)/(*)/negate/abs/signum/fromInteger
-- Real/Fractional/RealFrac/Floating/Integral
{- Ch9 type/newtype/lazy-evaluation -}
-- type : aliasing
type IntList = [Int]
type IdT a = a -> a
id_alt :: a -> IdT a
id_alt a = id
-- newtype : like data
-- only-one constructor and zero abstraction overhead
-- no unboxing ctor
-- must be lifted type
newtype Inch = Inch Double
deriving Eq
y = Inch 4
-- bottom(_|_) : cannot-be-calculated
undefined_alt = let x = x
in x
-- lifted type -> wrapper machine type (unlifted) so they can match _|_(⊥)
-- lazy thunk -> Tagless Graph
-- denotational semantics / referential transparency
-- every time eta-conversion a binding to expression -> value maintained
-- no side effect
-- compiler-friendly: inline/simplify/fusion easily
-- normal form/weak head normal form/thunk
-- eager evaluation -> weak head normal form
-- seq :: (a -> b -> b) seq = ... (Primitive)
-- ($!) :: (a -> b) -> a -> b
-- eager evaluation -> normal form
-- deepseq
-- force :: NFData a => a -> a
{- Ch10 Module -}
{-
module A.B.C (
binding,
module other,
DataType(Ctor1, Ctor2...), -- export one data DataTyoe
AnotherData(..),
ClassDef(class1, class2...) -- export one typeclass ClassDef
) where
import X.Y (Type, value...)
import qualified X.Y as Z -- import as Z (or just use Y.xxx)
import qualified X.Y as Z hiding(Type, value...)
-}
{- Ch11 Functor -}
-- match maybe box
add_one_maybe :: Maybe Int -> Maybe Int
add_one_maybe (Just a) = Just (a + 1)
add_one_maybe Nothing = Nothing
-- To abstract box
-- class Functor f where
-- fmap :: (a -> b) -> f a -> f b
-- (<$) :: a -> f b -> f a
-- (<$) :: fmap . const
-- instance Functor [] where
-- instance Functor Maybe where
-- instance Functor ((,), a) where -- The box of (a, b) is (,) a
-- fmap f (x, y) = (x, f y)
-- instance Functor ((->) a) where -- The box of a -> b is (->) a
-- fmap f fa = f . fa
-- fmap = (.) [:t (b -> c) -> (a -> b) -> (a -> c)]
-- Everything is a box (container)
-- container is a functor
-- Some category theory
-- category C
-- set class ob(C) : object
-- set class hom(C) : projection
-- binary operation o : combination of projection
-- forall a b c : hom(b, c) x hom(a, b) -> hom(a, c)
-- f : hom(a, b) o g : hom(b, c) = g o f
-- associativity h o (g o f) = h o g
-- identity forall x : object, exist idx : x -> x, forall f : a -> b, idb o f = f = f o ida
-- fmap: C -> D
-- ob(C) -> ob(D)
-- hom(C) - hom(D)
-- fmap id (C) = id (D)
-- fmap f o g = fmap(f) o fmap(g) (isomorphic)
-- This operation is called lifted (a -> b) -> (f a -> f b)
-- or from one category -> another category
-- Identity : Id here
newtype Identity_alt a = Identity_alt { runIdentity_alt :: a }
instance Functor Identity_alt where
fmap f idx = Identity_alt (f $ runIdentity_alt idx)
-- or fmap f = Identity_alt . f . runIdentity_alt -- point-free
-- Const : Nothing here
newtype Const_alt a b = Const_alt { getConst_alt :: a } -- phatom type b
instance Functor (Const_alt a) where
fmap f (Const_alt v) = Const_alt v -- Error: Book P116
-- IO: a container(functor)
{- Ch12 lenses -}
-- without lenses
pr1 = MakePosR 1 2
pr2 = pr1 {getY = 3}
-- pr2 = MakePosR {
-- getX = getX pr1
-- getY = 3
--}
getX_PosR :: PosR -> Double
getX_PosR (MakePosR x _) = x
setX_PosR :: Double -> PosR -> PosR
setX_PosR x' p = p{ getX = x' }
-- with Lens (unwrapper your functor to apply object and wrapper into container)
-- LANGUAGE Rank2Types
type Lens_alt b a = forall f. Functor f => (a -> f a) -> b -> f b -- b.a exists
-- Then
xLens_PosR :: Functor f => (Double -> f Double) -> PosR -> f PosR
-- Or xLens_PosR :: Lens PosR Double
xLens_PosR f p = fmap (\x' -> setX_PosR x' p) $ f (getX_PosR p)
-- Or xLens_PosR = fmap (\x' -> p{ getX = x' }) & f (getX p)
-- getter: getX/setter: \x' -> p{ getX = x' }
-- Then
-- xLen_PosR (\x -> [x+1, x+2, x+3]) (MakePosR 3 4) -> [PosR{...}, PosR{...}, ...]
-- If we have
-- view_PosR :: Lens_alt PosR Double -> Double -> Double -- getter
-- set_PosR :: Lens_alt PosR Double -> Double -> PosR -> PosR -- setter
-- over_PosR :: Lens_alt PosR Double -> (Double -> Double) -> PosR -> PosR -- transformer
-- over
-- over :: Functor f => ((a -> f a) -> b -> f b) -> (a -> a) -> b -> b
-- over :: ((a -> Identity a) -> b -> Identity b) -> (a -> a) -> b -> b
over_alt :: Lens_alt b a -> (a -> a) -> b -> b
over_alt lens f x = runIdentity_alt $ lifted x -- easy eta + beta => point-free
where
lifted = lens (Identity_alt . f) -- b -> Indentity b
infixr 4 %~
(%~) :: Lens_alt b a -> (a -> a) -> b -> b
(%~) = over_alt
-- set
-- over lens (\_ -> a) p == set lens a p
-- set :: ((a -> Identity a) -> b -> Identity b) -> a -> b -> b
set_alt :: Lens_alt b a -> a -> b -> b
set_alt lens a = over_alt lens (const a)
-- const :: a -> b -> a
-- const x _ = x
infixr 4 .~
(.~) :: Lens_alt b a -> a -> b -> b
(.~) = set_alt
-- view
-- view :: ((a -> Const a a) -> b -> Const a b) -> b -> a
view_alt :: Lens_alt b a -> b -> a
view_alt lens = getConst_alt . (lens Const_alt)
-- Then
-- yxLens = yLens . xLens
-- view yxLens y -> y.x.T
infixl 8 %^
(%^) :: b -> Lens_alt b a -> a
x %^ lens = view_alt lens x
-- (^.) = flip view_alt
-- flip :: (a -> b -> c) -> b -> a -> c
-- flip x y = f y x
{- pipeline
infixl 1
(&) :: a -> (a -> b) -> b
x & f = f x
-}
{-# LANGUAGE TemplateHaskell #-}
-- makeLenses
-- mkVars :: String -> Q (Pat Q, Exp Q)
-- mkVars name = do
-- x <- newName name
-- return (varP x, varE x)
-- makeLenses :: Name -> DecsQ
-- makeLenses typename = do
-- TyConI (DataD _ _ [] cons _) <- reify typeName
-- [RecC conName fields] <- return cons
-- fmap concat $
-- forM fields $ \(fieldName, _, fileType) ->
-- case nameBase fieldName of
-- -- only for _f
-- ('_':rest) -> makeLens typeName conName (mkName rest) fieldName fieldType
-- _ -> return []
-- makeLens
-- :: Name -- data type
-- -> Name -- ctor
-- -> Name -- lens name
-- -> Name -- data name
-- -> Type -- data type
-- -> DescQ
-- makeLens typeName conName lensName fieldName fieldType = do
-- let bT = conT typename
-- aT = return fieldType
-- lensT = [t|(Functor f) => ($aT -> f $aT) -> $bT -> f $bT|]
-- sig <- sigD lensName lensT
-- (fP, fE) <- makeVars "f"
-- (bP, bE) <- makeVars "b"
-- (xP, xE) <- makeVars "x"
-- xE' <- xE
-- let -- \x -> (\y b -> b {field = y}) x p
-- lam = [| \$xP -> $(recUpdE bE [return (fieldName, xE')]) |]
-- pats = [fP, bP]
-- rhs = [|fmap $lam ($fE ($(varE fieldName) $bE))|]
-- body = funD lensName [clause pats (normalB rhs) []]
-- return [sig, body]
{- Ch13 Applicative -}
-- concat :: [[a]] -> [a]
-- concat xss = foldl (++) [] xss
-- class Functor f => Applicative f where
-- pure :: a -> f a
-- (<*>) :: Functor f => f (a -> b) -> f a -> f b
-- (<*)
-- (*>)
-- identity: pure id <*> v === v
-- composition: pure (.) <*> u <*> v <*> w === u <*> (v <*> w)
-- homomorphism: pure f <*> pure x === pure (f x)
-- interchange: u <*> pure y === pure ($ y) <*> u
-- ($ a) :: (a -> b) -> b
-- instance Applicative [a] where
-- pure x = [x]
-- fs <*> xs = [f x | f <- fs, x <- xs ]
-- instance Applicative ((->) a) where -- (->): reader functor
-- pure :: x -> (a -> x)
-- pure x = \_ -> x -- just pure = const
-- (<*>) :: (a -> (x -> y)) -> (a -> x) -> (a -> y)
-- fxy <*> fx = \a -> fxy a $ fx a -- fxy(a, fx(a))
-- pure (\x y z -> x + y + z) <*> (^2) <*> (^2) <*> (^3)
-- \x -> (x^2) + (x^3) + (x^4)
-- \x y z -> x + y + z :: (Num a) => a -> a -> a -> a
-- pure f :: Num a => const (a -> a -> a -> a) === (->) a (a -> a -> a)
-- g :: a -> a === (->) a (a)
-- f <*> g :: (->) a (a -> a)
-- natural lift
-- infixl 4 <$>
-- (<$>) :: (a -> b) -> f a -> f b
-- f <$> x = fmap f x
-- infixl -> function -> Functor
-- (+) <$> Just 1 <*> Just 2 == pure (+) <*> Just 1 <*> Just 2
-- helper
-- infixl 4 <$, $>
-- (<$) :: Functor f => a -> f b -> f a
-- (<$) = fmap . const
-- ($>) :: Functor f => f a -> b -> f b
-- ($>) = flip (<$)
-- infixl 4 <*, *>
-- (*>) :: Applicative f => f a -> f b -> f b
-- a1 *> a2 = (id <$ a1) <*> a2
-- (<*) :: Applicative f => f a -> f b -> f a -- compare to const
-- (<*) = flip (*>)
-- Conclusion
-- <*> : horizonally concat function in category with its parameters in category
-- pure:
-- (global) lift function in any category defined by following parameters
-- pure :: Applicative f => a -> f a
-- (instance): wrap function in one category (add minimum context)
-- natural lift:
-- f <$> x <*> y <*> ...
-- fmap with many in-category parameters
{- Ch14 Monoid -}
-- Monoid: (+)
-- associativity
-- identity
-- class Monoid a where
-- mempty :: a
-- mappend :: a -> a -> a
-- mconcat :: [a] -> a
-- mconcat = foldr mappend mempty
-- infixr 6
-- (<>) :: Monoid a => a -> a -> a
-- (<>) = mappend
-- Common monoid: [a]/Ordering/()/(a, b)
newtype Product_alt a = Product_alt {getProduct_alt :: a}
deriving Show
newtype Sum_alt a = Sum_alt {getSum_alt :: a}
deriving Show
instance Num a => Monoid (Product_alt a) where
mempty = Product_alt 1
(Product_alt x) `mappend` (Product_alt y) = Product_alt (x * y)
instance Num a => Monoid (Sum_alt a) where
mempty = Sum_alt 1
(Sum_alt x) `mappend` (Sum_alt y) = Sum_alt (x + y)
newtype Any_alt = Any_alt {getAny_alt :: Bool}
deriving Show
newtype All_alt = All_alt {getAll_alt :: Bool}
deriving Show
instance Monoid Any_alt where
mempty = Any_alt False
Any_alt x `mappend` Any_alt y = Any_alt (x || y)
instance Monoid All_alt where
mempty = All_alt False
All_alt x `mappend` All_alt y = All_alt (x && y)
-- instance Monoid b => Monoid (a -> b) where
-- mempty _ = mempty
-- mappend f g x = f x `mappend` g x
-- Endomorphism
newtype Endo_alt a = Endo_alt {appEndo_alt :: a -> a}
instance Monoid (Endo_alt a) where
mempty = Endo_alt id
(Endo_alt f1) `mappend` (Endo_alt f2) = Endo_alt (f1 . f2)
-- Some Monoid -> Category
-- ob(C) = Monoid M
-- hom(C) = mappend ...
-- dual category
-- duality in Linear Algebra
newtype Dual_alt a = Dual_alt {getDual_alt :: a}
instance Monoid a => Monoid (Dual_alt a) where
mempty = Dual_alt mempty
(Dual_alt x) `mappend` (Dual_alt y) = Dual_alt (y `mappend` x)
-- Const a to be Applicative
-- Const cannot because (<*>) :: f (a -> b) -> f a -> f b cannot be satisfied
-- Here we just restrict a to be Monoid to have extra id/op
instance Monoid a => Applicative (Const_alt a) where
pure _ = Const_alt mempty
(Const_alt x) <*> (Const_alt y) = Const_alt (x `mappend` y)
-- Applicative happens to be a Monoid: []/Maybe
-- pure x === mempty of (<*>)
-- Alternative (<|>)
-- class Applicative f => Alternative f where
-- empty :: f a
-- (<|>) :: f a -> f a -> f a
-- instance Alternative [] where
-- empty = []
-- (<|>) = (++)
-- instance Alternative Maybe where
-- empty = Nothing
-- Nothing <|> r = r
-- l <|> _ = l
-- zip vs lift
-- simple lift -> n^k element
-- ziplist -> n element
newtype ZipList_alt a = ZipList_alt {getZipList_alt :: [a]}
instance Functor ZipList_alt where
fmap f (ZipList_alt xs) = ZipList_alt $ fmap f xs
instance Applicative ZipList_alt where
pure x = ZipList_alt (repeat x)
ZipList_alt fs <*> ZipList_alt xs = ZipList_alt (zipWith id fs xs)
-- Applicative -> Functor
-- fmap f x = pure f <*> x
{- Ch15 applicative parse/optparser -}
data Either_alt a b = Left_alt a | Right_alt b
deriving (Show, Eq)
-- Either a as container
-- Left: bottom
instance Functor (Either_alt a) where
fmap _ (Left_alt x) = Left_alt x
fmap f (Right_alt y) = Right_alt $ f y
instance Applicative (Either_alt e) where
pure = Right_alt
Left_alt e <*> _ = Left_alt e
Right_alt f <*> r = fmap f r
data Command = CmdBranch | CmdFile
deriving (Show, Eq)
cmdParser :: String -> Either_alt String Command
cmdParser str = case str of
"branch" -> Right_alt CmdBranch
"file" -> Right_alt CmdFile
str' -> Left_alt ("Unknown command: " ++ str)
data SubCommand = CmdList | CmdCreate | CmdRemove
deriving (Show, Eq)
subCmdParser :: String -> Either_alt String SubCommand
subCmdParser str = case str of
"list" -> Right_alt CmdList
"create" -> Right_alt CmdCreate
"remove" -> Right_alt CmdRemove
str' -> Left_alt ("Unknown sub-command: " ++ str)
mainCmdParser :: String -> Either_alt String (Command, SubCommand)
mainCmdParser str =
let [cmdStr, subCmdStr] = words str
in (,) <$> cmdParser cmdStr <*> subCmdParser subCmdStr
-- optparse-applicative
data GreetT = GreetT {hello :: String, quiet :: Bool}
greetParser :: Parser GreetT
greetParser = GreetT
<$> strOption
( long "Hello"
<> metavar "TARGET"
<> help "Target for the greeting" )
<*> switch
( long "quiet"
<> help "Whether to be quiet" )
greetMain :: IO()
greetMain = do
greet <- execParser $ info greetParser mempty
case greet of
GreetT h False -> putStrLn $ "Hello, " ++ h
_ -> return ()
-- long :: HasName f => String -> Mod f a
-- metavar :: HasMetavar f => String -> Mod f a
-- help :: String -> Mod f a
-- data Mod f a = Mod (f a -> f a) (DefaultProp a) (OptProperties -> OptProperties)
-- instance Monoid (Mod f a) where
-- mempty = Mod id mempty id
-- Mod f1 d1 g1 `mappend` Mod f2 d2 g2
-- = Mod (f2 . f1) (d2 `mappend` d1) (g2 . g1)
-- strOption :: Mod OptionFields String -> Parser String
-- strOption(...) :: Parser String
-- switch :: Mod FlagFields Bool -> Parser Bool
-- switch(...) :: Parser Bool
-- infixr 6 <>
-- (<>) :: a -> a -> a
-- associative operation
-- if Monoid => (<>) = mappend
-- since Parser is a alternative applicative
-- we have
-- data AB = A | B
-- ABParser :: Parser AB
-- ABParser = AParser <!> BParser
{- Ch16 Monad -}
-- Maybe (Maybe Int) == Maybe Int
-- join :: f (f a) -> f
-- join Maybe
-- join [[a]] = concat
-- class Applicative m => Monad m where -- book here mistakes the place of class P159
-- return :: a -> m a
-- return = pure
-- join :: m (m a) -> m a
-- fail :: String -> m a
-- left-id: return a >>= k === k a
-- right-id m >>= return === m
-- associativity: m >>= (x -> kx >>= h) === (m >>= k) >>= h
-- bind
-- infixl 1 >>=
-- (>>=) :: m a -> (a -> m b) -> m b
-- x >>= f = join $ fmap f x
-- f :: a -> m b => fmap f :: m a -> m (m b) => fmap f x :: m (m b) => x >>= f :: m b
-- bind isomorphic join
-- join :: Monad m => m (m a) -> m a
-- join mmx = mmx >>= id
-- realize <*>
-- <*> is just S-combinator
-- <*> :: Monad m => m (a -> b) -> m a -> m b
-- mf <*> mx = join $ fmap (\f -> fmap f mx) mf
-- ap :: Monad m => m (a -> b) -> m a -> m b
-- mf `ap` mx = mf >>= (\f -> mx >>= \x -> f x)
-- $ lift to Applicative = <*>
-- $ lift to Monad = ap
-- replicate <$> Just 3 <*> Just 'x'
-- == Just 3 >>= \n ->
-- Just 'x' >>= \x ->
-- Just (replicate n x)
-- compare to applicative
-- applicative cannot change context/functor/pure
-- monad can change properties of functor
-- m a -> (a -> m b) -> m b
-- do notation
-- simple act === act >>
-- y x <- t === >>= \x -> t === (\x -> t) y
-- let xxx = yyy === let xxx = yyy in
allArea :: [Int]
allArea = do
x <- [1..10]
y <- [x..10]
return (x * y)
allArea_raw :: [Int]
allArea_raw =
{-(-} [1..10] >>= \x ->
[x..10] {-(-} >>= \y ->
return (x * y)
count_anonoymous_do :: Int
count_anonoymous_do = sum $ do {- { -}
[1..10]
[1..10]
return 1 {- } -}
-- abandon information
-- (>>) :: Monad m => m a -> m b -> m b
-- mx >> my = mx >>= (\x -> my >>= \y -> return y)
-- IO
-- getLine :: IO String
-- purStrLn :: String -> IO ()
-- when :: Applicative f => Bool -> f () -> f ()
-- when p s = if p then s else pure ()
-- unless :: Applicative f => Bool -> f () -> f ()
-- unless p s = if p then pure () else s
-- return ()
-- void :: Function f => f a -> f ()
-- void x = () <$ x
{- Ch17 8-queen/List Monad -}
-- instance Monad [] where
-- return x = [x]
-- x >>= f = concat $ fmap f x
-- join = concat
-- do notation => list comprehension
-- <- === \... ->
-- MonadPlus
-- class (Alternative m, Monad m) => MonadPlus m where
-- mzero :: m a
-- mplus :: m a -> m a -> m a
-- identity: mzero `mplus` ma === ma `mplus` mzero === ma
-- associativity: ma `mplus` (mb `mplus` mc) === (ma `mplus` mb) `mplus` mc
-- mzero >>= f === mzero
-- v >> mzero === mzero
-- change shape of monad | if-statement
-- guard :: MonadPlus m => Bool -> m ()
-- guard True = return ()
-- guard False = mzero
-- sequence
-- Traversable : typeclass
-- sequence :: (Traversable t, Monad m) => t (m a) -> m (t a)
-- for list ([] = empty | (a:as) = concat | (:) = concat)
-- sequence [] = return []
-- sequence (a:as) = a >>= \x -> x : sequence as
-- sequence_ = a >> sequence_ as
-- mapM
-- mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b)
-- forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
-- forM = flip mapM
-- list
-- mapM = sequence .map
-- mapM_ = sequence_ . map
-- replicateM
-- replicateM :: (Traversable t, Monad m) => Int -> m a -> m (t a)
-- forever
-- forever :: Monad m => m a -> m b
-- filterM/foldM
{- Ch18 Reader Monad -}
-- a -> b === (->) a b Functor: (->) a Category: b
-- fmap :: (a -> b) -> (b -> c) -> (a -> c)
-- fmap = (.)
-- a -> b === (->) a b Applicative: (->) a
-- (<*>) :: (a -> b -> c) -> (a -> b) -> (a -> c)
-- fbc <*> fb = \a -> fbc a $ fb a
-- Reader:
-- given all (->) a wrapped (a -> *) type some parameter
-- combiner <$> f1 <*> f2 <*> ... $ global_const
-- (->) a as Monad
-- instance Monad (->) a where
-- return :: b -> a -> b
-- return = pure
-- (>>=) :: (a -> b) -> (b -> a -> c) -> (a -> c)
-- f >>= g = \x -> g (f x) x
-- how to modify global const
ask :: a -> a
ask = id
local :: (a -> a) -> (a -> r) -> a -> r
local f g = g . f
data Greet = Greet {
gHead :: String,
gBody :: String,
gFoot :: String
} deriving Show
gheadT :: String -> String
gheadT n = "Head" ++ n
gbodyT :: String -> String
gbodyT n = "Body" ++ n
gfootT :: String -> String
gfootT n = "Foot" ++ n
renderGreeting_applicative :: String -> Greet
renderGreeting_applicative = Greet <$> gheadT <*> gbodyT <*> gfootT
renderGreeting_monad :: String -> Greet
renderGreeting_monad =
gheadT >>= \h ->
gbodyT >>= \b ->
gfootT >>= \f ->
return $ Greet h b f
renderGreeting_do :: String -> Greet
renderGreeting_do = do
h <- gheadT
b <- gbodyT
f <- gfootT
return $ Greet h b f
renderGreeting_do_mod :: String -> Greet
renderGreeting_do_mod = do
h <- ask
(b, f) <- local ("Prefix" ++) $ do
b' <- gbodyT
f' <- gfootT
return (b', f')
return $ Greet h b f
renderGreeting_monad_mod :: String -> Greet
renderGreeting_monad_mod =
ask >>= \h ->
local ("Prefix" ++) ( -- (\env ... ) . ("Prefix" ++)
gbodyT >>= \b' -> -- \env -> ( \b' ->
gfootT >>= \f' -> -- ( \f' -> ( \_ ->
return (b', f') -- (b', f') ) $ env ) . gfootT $ env ) . gbodyT $ env
) >>= \(b, f) ->
return $ Greet h b f
renderGreeting_applicative_mod :: String -> Greet
renderGreeting_applicative_mod = Greet <$> id <*> gbodyT . ("Prefix" ++) <*> gfootT . ("Prefix" ++)
-- old-style Reader
newtype Reader r a = Reader { runReader :: r -> a }
instance Functor (Reader r) where
-- (->) r (a -> b) -> a -> (->) r b
fmap f m = Reader $ \r -> f (runReader m r)
instance Applicative (Reader r) where
-- a -> (->) r a
pure a = Reader $ \_ -> a
-- (->) r (a -> b) -> (->) r a -> (->) r b
a <*> b = Reader $ \r -> runReader a r $ runReader b r
instance Monad (Reader r) where
return = pure
-- (->) r a -> (a -> (->) r b) -> (->) r b
m >>= k = Reader $ \r -> runReader (k (runReader m r)) r
{- Ch19 State Monad -}
-- oldState -> (someValue, newState)
newtype State s a = State { runState :: s -> (a, s) }
instance Functor (State s) where
-- fmap :: (a -> b) -> State s a -> State s b
-- fmap :: (a -> b) -> (s -> (a, s)) -> (s -> (b, s))
fmap f fs = State $ \s ->
let (a, s') = runState fs s
in (f a, s')
instance Applicative (State s) where
pure a = State $ \s -> (a, s)
-- (<*>) :: State s (a -> b) -> State s a -> State s b
f <*> fa = State $ \s ->
let (fab, s0) = runState f s
(a, s1) = runState fa s0
in (fab a, s1)
instance Monad (State s) where
return = pure
-- (>>=) :: State s a -> (a -> State s b) -> State s b
fa >>= f = State $ \s ->
let (a, s') = runState fa s
in runState (f a) s'
get :: State s s
get = State $ \s -> (s, s)
gets :: (s -> a) -> State s a
gets f = State $ \s -> (f s, s)
put :: s -> State s ()
put s = State $ \_ -> ((), s)
modify :: (s -> s) -> State s ()
modify f = State $ \s -> ((), f s)
-- random number
{- Ch20 IO -}
-- newtype IO a = IO (State# RealWorld -> (# State# RealWorld, a #))
-- newtype IO a = IO (RealWorld -> (RealWorld, a))
-- instance Functor IO where
-- fmap f x = x >>= (return . f)
-- instance Applicative IO where
-- pure = return
-- (<*>) = ap
-- instance Monad IO where
-- m >> k = m >>= \_ -> k
-- return = returnIO
-- (>>=) = bindIO
-- returnIO :: a -> IO a
-- returnIO x = IO $ \s -> (# s, x #)
-- bindIO : IO a -> (a -> IO b) -> IO b
-- bindIO (IO m) k = IO $ \s -> case m s of (# new_s, a #) -> unIO (k a) new_s
-- putChar/putStr/putStrLn/print
-- getChar/getLine/getContents/interact
-- readIO/readLn/readT
-- readFile/writeFile/appendFile
-- IO : non-blocking (managed by IO manager)
-- IORef: compiler-magic
-- forkIO :: IO () -> IO ThreadId
-- ST Monad / Thread Monad
-- create a pure world
-- newtype ST s a = ST (STRep s a)
-- type STRep s a = State# s -> (# State#, a #)
-- newtype ST s a = ST (s -> (s, a))
-- newSTRef :: a -> ST s (STRef s a)
-- readSTRef :: STRef s a -> ST s a
-- writeSTRef :: STRef s a -> a -> ST s ()
-- modifySTRef :: STRef s a -> (a -> a) -> ST s ()
-- modifySTRef' :: STRef s a -> (a -> a) -> ST s ()
-- runST :: (forall s. ST s a) -> a
-- forall a. ((forall s. ST s a) -> a)
-- stToIO :: ST RealWorld a -> IO a
-- unsafe
-- unsafePerformIO :: IO a -> a
{- Ch21 Language Extension/Pragma -}
-- TupleSections --> (1,,3,) --> \x y -> (1, x, 3, y)
-- LambdCase --> \x -> case x of --> \case
-- MultiWayIf --> if else if else if --> if | | | (guard-with-no-binding)
-- BinaryLiterals --> 0x/0X --> 0b/0B
-- BangPattern --> fun(!x, !y) --> weak normal formal
-- Record puns/NameFieldPuns --> getX { X {x = x}} --> get { X {x} }
-- RecordWildCards --> getX { X {..} } -- default name
-- RankNTypes
-- DeriveFunctor/DeriveFoldable/DeriveTraversable
-- lazy mode --> f ~(a, b) = 1
-- \{-# UNPACK #-\}
-- \{-# INLINE func_name #-\}
-- \{-# INLINABLE/NONINLINE func_name #-\}
{- Ch22 Foldable/Traversable -}
-- data structure -> value
-- class Foldable t where
-- fold :: Monoid m => t m -> m
-- foldMap :: Monoid m => (a -> m) -> t a -> m
-- foldr/foldr'/foldl/foldl'
-- foldr1/foldl1
-- toList
-- null/length/elem/maximum/minimum/sum/product
data BinaryTree_alt a = Nil | Node a (BinaryTree_alt a) (BinaryTree_alt a)
deriving Show
exampleTree_alt =
Node 2
( Node 3
( Node 4 Nil Nil )
( Node 5 Nil
( Node 9 Nil Nil )
)
)
instance Functor BinaryTree_alt where
fmap f Nil = Nil
fmap f (Node x left right) = Node (f x) (fmap f left) (fmap f right)
instance Foldable BinaryTree_alt where
-- foldr :: (a -> b -> b) -> b -> BinaryTree a -> b
foldr f acc Nil = acc
foldr f acc (Node x left right) = (foldr f (f x (foldr f acc right)) left)
-- foldMap f = foldr (mappend . f) mempty
-- Key of Foldable
foldMap f Nil = mempty
foldMap f (Node x left right) = foldMap f left `mappend` f x `mappend` foldMap f right
-- foldr f z t = appEndo (foldMap (Endo #. f) t) z
-- foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
-- Traversable
-- methods to traverse
-- class (Functor t, Foldable t) => Traversable t where
-- traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
-- traverse = sequenceA . fmap -- default
-- sequenceA :: Applicative f => t (f a) -> f (t a)
-- sequenceA = traverse id -- default
-- mapM :: Monad m => (a -> m b) -> t a -> m (t b)
-- mapM = traverse -- default
-- sequence :: Monad m => t (m a) -> m (t a)
-- sequence = sequenceA -- default
instance Traversable BinaryTree_alt where
traverse f Nil = pure Nil
traverse f (Node x left right) =
Node <$> f x <*> traverse f left <*> traverse f right
-- Coerce
-- (#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c)
-- (#.) f = coerce
-- nomial / representational / phantom types
-- Coercible
-- A -> A
-- A -> newtype A
-- A -> newtype A B(phantom)
-- A T -> A NT
-- nomial :: equal
-- repreesntational :: must be Coercible =>
-- phantom :: any
{- Ch23 List/Array/Hash -}
-- List
-- O(1) --> :
-- O(1) --> tail
-- O(m) --> splitAt
-- share object (lazy)
-- O(n) -- length
-- O(m) -- ++
-- O(m) -- !!
-- O(m) -- update
-- intersperse/intercalate/subsequences/permutations/transpose/concatMap/mapAccumL/mapAccumR
-- iterate/cycle/takeWhile/dropWhile/dropWhileEnd/span/break/stripPrefix/group/inits/tails/lookup/partition
-- Array
-- Ix
-- class (Ord a) => Ix a where
-- minimum defintion: rnage, (index | unsafeIndex), inRange
-- range :: (a, a) -> [a]
-- index :: (a, a) -> a -> Int (indexError Exception)
-- unsafeIndex :: (a, a) -> a -> Int
-- inRange :: (a, a) -> a -> Bool
-- rangeSize :: (a, a) -> Int
-- unsafeRangeSize :: (a, a) -> Int
-- array :: Ix i => (i, i) -> [(i, e)] -> Array i e
-- listArray :: Ix i => (i, i) -> [e] -> Array i e
-- accumArray :: Ix i => (e -> a -> e) -> e -> (i, i) -> [(i, a)] -> Array i e
-- IArray (immutable)
-- (!) :: (IArray a e, Ix i) => a i e -> i -> e
-- indices/elems/assocs/accum/amap/ixmap
-- (//) :: (IArray a e, Ix i) => a i e -> [(i, e)] -> a i e
-- MArray (mutable, must in RealWorld/ST/IO)
-- freeze/thaw :: IArray <-> MArray
-- HashMap
-- hash-trie
-- empty/singleton/insert/adjust/insertWith/delete/lookup/lookupDefault/null/size/member
{- Ch24 Monad Transform -}
-- Kleisli Category
-- hom :: a -> [b]
-- (>=>) :: (a -> [b]) -> (b -> [c]) -> a -> [c]
-- f >=> g = \x -> concatMap g (f x)
-- every Monad has corresponding Kleisli Category
-- return :: a -> m a
-- return = pure
-- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)
-- f >=> g = \x -> f x >>= g
-- (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
-- (<=<) = flip (>>=)
-- ReaderT
-- encap r -> m a Monad function instead of r -> a in Reader
newtype ReaderT r m a = ReaderT { runReaderT :: r -> m a }
instance (Functor m) => Functor (ReaderT r m) where
-- fmap :: (a -> b) -> ReaderT r m a -> ReaderT r m b
fmap f m = ReaderT $ \r -> fmap f (runReaderT m r)
instance (Applicative m) => Applicative (ReaderT r m) where
-- pure :: a -> ReaderT r m a
pure r = ReaderT $ \_ -> pure r
-- (<*>) :: ReaderT r m (a -> b) -> ReaderT r m a -> ReaderT r m b (error on P246)
f <*> v = ReaderT $ \r -> runReaderT f r <*> runReaderT v r
instance (Monad m) => Monad (ReaderT r m) where
-- return :: a -> ReaderT r m a
return = pure
-- (>>=) :: ReaderT r m a -> (a -> ReaderT r m b) -> ReaderT r m b
m >>= k = ReaderT $ \r -> do
a <- runReaderT m r
runReaderT (k a) r
-- connect different Kleisli Category
liftReaderT :: m a -> ReaderT r m a
liftReaderT m = ReaderT $ \r -> m
-- or LiftReader m = ReaderT (const m)
askT :: Monad m => ReaderT r m r
askT = ReaderT return
localT :: (r -> r) -> ReaderT r m a -> ReaderT r m a
localT f m = ReaderT $ \r -> runReaderT m (f r)
-- in Hask Category, id is identity hom
-- in Kleisli Category, return is identity hom
-- StateT
-- newtype StateT s m a = StateT { runStateT :: s -> m (a, s) }
-- evalStateT/execStateT
{- Ch25 Lift Monad Transform -}
-- MonadIO
-- MonadState/MonadReader
-- type family
-- TypeFamilies
-- Lazy StateT/Strict StateT
-- Writer Monad
-- newtype Writter w a = Writer { runWriter :: (a, w) }
-- instance (Monoid w) => Monad (Writer w) where
-- return x = Writer (x, mempty)
-- (Writer (x, w)) >>= f =
-- let (Writer (y, w')) = fx
-- in Writer (y, w 'mappend' w')
-- WriterT
{- Ch29 Template Haskell -}
-- program to generate AST
-- mkName :: String -> Name
-- ' :: 'fmap --> fmap :: Name (binding)
-- '' :: ''Position --> Position :: Name (data/typeclass)
-- Type/Pat/Dec
-- Clause [Pat] Body [Dec]
-- Body = GuardedB [(Guard, Exp)] | NormalB Exp
-- Name :: [a] -> Int
-- Name = mkName "Name"
-- typeSig = SigD Name
-- (Forall T [PlainT (mkName "a")] [] (ArrowT 'AppT' (AppT ListT (VarT $ mkName "a")) 'AppT' (Cont ''Int)))
-- eq1 = Clause
-- Oxford bracket
-- [|...|] : AST
-- [|...|]/[e|...|] Q Exp
-- [t|...|] Q Type
-- [p|...|] Q Pat
-- [d|...|] Q Dec
-- Q Monad
-- Compile-time
-- Quasi/Quote
-- newName/reify/location/reportError/runIO
-- $.../$(...) concat
-- varP/LitE/integerL
{-# LANGUAGE TemplateHaskell #-}
-- makeLenses
-- mkVars :: String -> Q (Pat Q, Exp Q)
-- mkVars name = do
-- x <- newName name
-- return (varP x, varE x)
-- makeLenses :: Name -> DecsQ
-- makeLenses typename = do
-- TyConI (DataD _ _ [] cons _) <- reify typeName
-- [RecC conName fields] <- return cons
-- fmap concat $
-- forM fields $ \(fieldName, _, fileType) ->
-- case nameBase fieldName of
-- -- only for _f
-- ('_':rest) -> makeLens typeName conName (mkName rest) fieldName fieldType
-- _ -> return []
-- makeLens
-- :: Name -- data type
-- -> Name -- ctor
-- -> Name -- lens name
-- -> Name -- data name
-- -> Type -- data type
-- -> DescQ
-- makeLens typeName conName lensName fieldName fieldType = do
-- let bT = conT typename
-- aT = return fieldType
-- lensT = [t|(Functor f) => ($aT -> f $aT) -> $bT -> f $bT|]
-- sig <- sigD lensName lensT
-- (fP, fE) <- makeVars "f"
-- (bP, bE) <- makeVars "b"
-- (xP, xE) <- makeVars "x"
-- xE' <- xE
-- let -- \x -> (\y b -> b {field = y}) x p
-- lam = [| \$xP -> $(recUpdE bE [return (fieldName, xE')]) |]
-- pats = [fP, bP]
-- rhs = [|fmap $lam ($fE ($(varE fieldName) $bE))|]
-- body = funD lensName [clause pats (normalB rhs) []]
-- return [sig, body]
{- Ch31 GADT -}
-- Typeable : compile-time type determination
-- deriving (Typeable) --> typeOf (T)
-- tyConPackage/tyConModule/tyConName/typeRepTyCon/typeRepFingerprint
-- Dynamic : runtime type conversion
-- toDyn/fromDynamic/fromDyn/dynTypeRep
-- existential type
-- Extension : ExistentialQuantification
-- data Dyn = forall a. Show a => Dyn a (existential type)
-- heteroList = [Dyn 3, Dyn "abc", Dyn 'x']
-- TypeFamily/DataFamily/GADT
-- type family Item a :: * (* -> *)
-- Open: type instance Item String = Char (Char :: Item String)
-- Close: type family Item a where ...
-- data family T a
-- data instance T Int = T1 Int | T2 Bool (T2 Bool :: T Int)
-- 对类型特化构造器
-- type family S a
-- type family S Int = Bool
-- type family S Char = Char
-- type function as synonym
-- data T ... where
-- C1 ... :: T ...
-- C2 ... :: T ...
-- DataKinds
-- Extension : GADTs/DataKinds/KindSignatures
-- Extension : OverlappingInstances {-# OVERLAPPING #-}
-- main :: IO()
main = do
x <- readLn
putStrLn x -- Prelude.base.print
| Airtnp/Freshman_Simple_Haskell_Lib | Intro/hello-world.hs | mit | 42,745 | 0 | 19 | 11,908 | 7,102 | 4,084 | 3,018 | -1 | -1 |
-- Taken from blog post http://blog.tmorris.net/20-intermediate-haskell-exercises/
class Fluffy f where
furry :: (a -> b) -> f a -> f b
-- Exercise 1
-- Relative Difficulty: 1
instance Fluffy [] where
-- furry :: (a -> b) -> [a] -> [b]
furry = map
-- Exercise 2
-- Relative Difficulty: 1
instance Fluffy Maybe where
-- furry :: (a -> b) -> Maybe a -> Maybe b
furry f (Just x) = Just $ f x
furry _ Nothing = Nothing
-- Exercise 3
-- Relative Difficulty: 5
instance Fluffy ((->) t) where
-- furry :: (a -> b) -> (t -> a) -> t -> b
furry f g = f . g
newtype EitherLeft b a = EitherLeft (Either a b)
newtype EitherRight a b = EitherRight (Either a b)
-- Exercise 4
-- Relative Difficulty: 5
instance Fluffy (EitherLeft t) where
-- furry :: (a -> b) -> EitherLeft t a -> EitherLeft t b
furry _ (EitherLeft (Right x)) = EitherLeft $ Right x
furry f (EitherLeft (Left x)) = EitherLeft $ Left $ f x
-- Exercise 5
-- Relative Difficulty: 5
instance Fluffy (EitherRight t) where
-- furry :: (a -> b) -> EitherRight t a -> EitherRight t b
furry f (EitherRight (Right x)) = EitherRight $ Right $ f x
furry _ (EitherRight (Left x)) = EitherRight $ Left x
class Misty m where
banana :: (a -> m b) -> m a -> m b
unicorn :: a -> m a
-- Exercise 6
-- Relative Difficulty: 3
-- (use banana and/or unicorn)
furry' :: (a -> b) -> m a -> m b
furry' f = banana $ \x ->
unicorn $ f x
-- Exercise 7
-- Relative Difficulty: 2
instance Misty [] where
-- banana :: (a -> [b]) -> [a] -> [b]
banana f = concat . (map f)
-- unicorn :: a -> [a]
unicorn = (:[])
-- Exercise 8
-- Relative Difficulty: 2
instance Misty Maybe where
-- banana :: (a -> Maybe b) -> Maybe a -> Maybe b
banana f (Just x) = f x
banana _ Nothing = Nothing
-- unicorn :: a -> Maybe a
unicorn = Just
-- Exercise 9
-- Relative Difficulty: 6
instance Misty ((->) t) where
-- banana :: (a -> t -> b) -> (t -> a) -> t -> b
banana f g x = f (g x) x
-- unicorn :: a -> t -> a
unicorn = \x _ -> x
-- Exercise 10
-- Relative Difficulty: 6
instance Misty (EitherLeft t) where
-- (a -> EitherLeft t b) -> EitherLeft t a -> EitherLeft t b
banana f (EitherLeft (Left x)) = f x
banana _ (EitherLeft (Right x)) = EitherLeft $ Right x
-- a -> EitherLeft t a
unicorn = EitherLeft . Left
-- Exercise 11
-- Relative Difficulty: 6
instance Misty (EitherRight t) where
-- (a -> EitherRight t b) -> EitherRight t a -> EitherRight t b
banana _ (EitherRight (Left x)) = EitherRight $ Left x
banana f (EitherRight (Right x)) = f x
-- a -> EitherRight t a
unicorn = EitherRight . Right
-- Exercise 12
-- Relative Difficulty: 3
jellybean :: (Misty m) => m (m a) -> m a
jellybean = banana id
-- Exercise 13
-- Relative Difficulty: 6
apple :: (Misty m) => m a -> m (a -> b) -> m b
apple x mf = banana (\f -> furry' f x) mf
-- Exercise 14
-- Relative Difficulty: 6
moppy :: (Misty m) => [a] -> (a -> m b) -> m [b]
moppy xs f = foldr (\x acc -> banana (\x' -> furry' (x':) acc) x) (unicorn []) (map f xs)
-- Exercise 15
-- Relative Difficulty: 6
-- (bonus: use moppy)
sausage :: (Misty m) => [m a] -> m [a]
sausage xs = moppy xs id
-- Exercise 16
-- Relative Difficulty: 6
-- (bonus: use apple + furry')
banana2 :: (Misty m) => (a -> b -> c) -> m a -> m b -> m c
banana2 f x y = apple y $ furry' f x
-- Exercise 17
-- Relative Difficulty: 6
-- (bonus: use apple + banana2)
banana3 :: (Misty m) => (a -> b -> c -> d) -> m a -> m b -> m c -> m d
banana3 f x y w = apple w $ banana2 f x y
-- Exercise 18
-- Relative Difficulty: 6
-- (bonus: use apple + banana3)
banana4 :: (Misty m) => (a -> b -> c -> d -> e) -> m a -> m b -> m c -> m d -> m e
banana4 f x y w z = apple z $ banana3 f x y w
newtype State s a = State {
state :: (s -> (s, a))
}
-- Exercise 19
-- Relative Difficulty: 9
instance Fluffy (State s) where
-- furry :: (a -> b) -> State s a -> State s b
furry f = \(State sf) ->
State $ \s ->
let
(s', x) = sf s
in
(s', f x)
-- Exercise 20
-- Relative Difficulty: 10
instance Misty (State s) where
-- banana :: (a -> State s b) -> State s a -> State s b
banana f = \(State sf) ->
State $ \s ->
let
(s', x) = sf s
(State sf') = f x
in
sf' s'
-- unicorn :: a -> State s a
unicorn x = State $ \s -> (s, x)
| maurotrb/hs-exercises | 20IntermediateHaskellExercises.hs | mit | 4,481 | 0 | 14 | 1,292 | 1,474 | 777 | 697 | 71 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
-- Refactoring
-- TODO: перейти на lens
module Compiler.Rum.Internal.AST where
import Control.Applicative (Alternative)
import Control.Monad.State (MonadIO, MonadState, StateT)
import Control.Monad.Trans.Maybe (MaybeT)
import qualified Data.HashMap.Strict as HM (HashMap)
import Data.Hashable (Hashable)
import Data.IORef
import Data.String (IsString, fromString)
import Data.Text (Text)
import qualified Data.Text as T (pack)
import GHC.Generics (Generic)
data Type = Number Int | Ch Char | Str Text | Arr [Type] | Unit deriving (Show, Eq, Ord)
data BinOp = Add | Sub | Mul | Div | Mod | Pow deriving (Show, Eq, Ord)
data CompOp = Eq | NotEq | Lt | Gt | NotGt | NotLt deriving (Show, Eq, Ord)
data LogicOp = And | Or | Xor deriving (Show, Eq, Ord)
newtype Variable = Variable {varName :: Text} deriving (Show, Eq, Ord, Hashable)
instance IsString Variable where
fromString = Variable . T.pack
data ArrCell = ArrCell {arr :: Variable, index :: [Expression]} deriving (Show)
data FunCall = FunCall {fName :: Variable, args :: [Expression]} deriving (Show)
data Expression = Const Type
| Var Variable
| ArrC ArrCell
| ArrLit [Expression] -- for [ a, b, c ]
| Neg Expression
| BinOper {bop :: BinOp, l, r :: Expression}
| CompOper {cop :: CompOp, l, r :: Expression}
| LogicOper {lop :: LogicOp, l, r :: Expression}
| FunCallExp FunCall
deriving (Show)
data Statement = AssignmentVar {var :: Variable, value :: Expression}
| AssignmentArr {arrC :: ArrCell, value :: Expression}
| FunCallStmt FunCall
| Skip
| IfElse {ifCond :: Expression, trueAct, falseAct :: Program}
| RepeatUntil {repCond :: Expression, act :: Program}
| WhileDo {whileCond :: Expression, act :: Program}
| For {start :: Program, expr :: Expression, update, body :: Program}
| Fun {funName :: Variable, params :: [Variable], funBody :: Program}
| Return {retExp :: Expression}
deriving (Show)
type Program = [Statement]
data RumludeFunName = Read | Write
| Strlen | Strget | Strsub | Strdup | Strset | Strcat | Strcmp | Strmake
| Arrlen | Arrmake
deriving (Show, Eq, Ord, Generic)
instance Hashable RumludeFunName
-------------------------
--- Environment Stuff ---
-------------------------
newtype Interpret a = Interpret
{ runInterpret :: StateT Environment (MaybeT IO) a
} deriving (Functor, Applicative, Monad, MonadIO, MonadState Environment, Alternative)
type InterpretT = Interpret Type
type VarEnv = HM.HashMap Variable Type
type RefVarEnv = HM.HashMap Variable (IORef RefType)
data RefType = Val Type | ArrayRef [IORef RefType]
type FunEnv = HM.HashMap Variable ([Variable], [Type] -> InterpretT)
data Environment = Env {varEnv :: VarEnv, refVarEnv :: RefVarEnv, funEnv :: FunEnv, isReturn :: Bool} | vrom911/Compiler | src/Compiler/Rum/Internal/AST.hs | mit | 3,369 | 0 | 9 | 1,030 | 913 | 561 | 352 | 58 | 0 |
module Person
( Address (..)
, Born (..)
, Name (..)
, Person (..)
, bornStreet
, renameStreets
, setBirthMonth
, setCurrentStreet
) where
import Data.Time.Calendar (Day)
data Person = Person { _name :: Name
, _born :: Born
, _address :: Address
}
data Name = Name { _foreNames :: String
, _surName :: String
}
data Born = Born { _bornAt :: Address
, _bornOn :: Day
}
data Address = Address { _street :: String
, _houseNumber :: Int
, _place :: String
, _country :: String
}
bornStreet :: Born -> String
bornStreet born = error "You need to implement this function."
setCurrentStreet :: String -> Person -> Person
setCurrentStreet street person = error "You need to implement this function."
setBirthMonth :: Int -> Person -> Person
setBirthMonth month person = error "You need to implement this function."
renameStreets :: (String -> String) -> Person -> Person
renameStreets f person = error "You need to implement this function."
| exercism/xhaskell | exercises/practice/lens-person/src/Person.hs | mit | 1,213 | 0 | 8 | 442 | 264 | 156 | 108 | 29 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
module Init (
(@/=), (@==), (==@)
, assertNotEqual
, assertNotEmpty
, assertEmpty
, isTravis
, BackendMonad
, runConn
, MonadIO
, persistSettings
, MkPersistSettings (..)
#ifdef WITH_NOSQL
, dbName
, db'
, setup
, mkPersistSettings
, Action
, Context
#else
, db
, sqlite_database
#endif
, BackendKey(..)
, generateKey
-- re-exports
, (<$>), (<*>)
, module Database.Persist
, module Test.Hspec
, module Test.HUnit
, liftIO
, mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase
, Int32, Int64
, Text
, module Control.Monad.Trans.Reader
, module Control.Monad
#ifndef WITH_NOSQL
, module Database.Persist.Sql
#else
, PersistFieldSql(..)
#endif
, ByteString
) where
-- re-exports
import Control.Applicative ((<$>), (<*>))
import Control.Monad (void, replicateM, liftM, when, forM_)
import Control.Monad.Trans.Reader
import Test.Hspec
import Database.Persist.TH (mkPersist, mkMigrate, share, sqlSettings, persistLowerCase, persistUpperCase, MkPersistSettings(..))
-- testing
import Test.HUnit ((@?=),(@=?), Assertion, assertFailure, assertBool)
import Test.QuickCheck
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Database.Persist
import Database.Persist.TH ()
import Data.Text (Text, unpack)
import System.Environment (getEnvironment)
#ifdef WITH_NOSQL
import Language.Haskell.TH.Syntax (Type(..))
import Database.Persist.TH (mkPersistSettings)
import Database.Persist.Sql (PersistFieldSql(..))
# ifdef WITH_MONGODB
import qualified Database.MongoDB as MongoDB
import Database.Persist.MongoDB (Action, withMongoPool, runMongoDBPool, defaultMongoConf, applyDockerEnv, BackendKey(..))
# endif
# ifdef WITH_ZOOKEEPER
import qualified Database.Zookeeper as Z
import Database.Persist.Zookeeper (Action, withZookeeperPool, runZookeeperPool, ZookeeperConf(..), defaultZookeeperConf, BackendKey(..), deleteRecursive)
import Data.IORef (newIORef, IORef, writeIORef, readIORef)
import System.IO.Unsafe (unsafePerformIO)
import qualified Data.Text as T
# endif
#else
import Database.Persist.Sql
import Control.Monad.Trans.Resource (ResourceT, runResourceT)
import Control.Monad.Logger
import System.Log.FastLogger (fromLogStr)
# ifdef WITH_POSTGRESQL
import Database.Persist.Postgresql
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
# endif
# ifdef WITH_SQLITE
import Database.Persist.Sqlite
# endif
# ifdef WITH_MYSQL
import Database.Persist.MySQL
# endif
import Data.IORef (newIORef, IORef, writeIORef, readIORef)
import System.IO.Unsafe (unsafePerformIO)
#endif
import Control.Monad (unless, (>=>))
import Control.Monad.Trans.Control (MonadBaseControl)
-- Data types
import Data.Int (Int32, Int64)
import Control.Monad.IO.Class
#ifdef WITH_MONGODB
setup :: Action IO ()
setup = setupMongo
type Context = MongoDB.MongoContext
#endif
#ifdef WITH_ZOOKEEPER
setup :: Action IO ()
setup = setupZookeeper
type Context = Z.Zookeeper
#endif
(@/=), (@==), (==@) :: (Eq a, Show a, MonadIO m) => a -> a -> m ()
infix 1 @/= --, /=@
actual @/= expected = liftIO $ assertNotEqual "" expected actual
infix 1 @==, ==@
expected @== actual = liftIO $ expected @?= actual
expected ==@ actual = liftIO $ expected @=? actual
{-
expected /=@ actual = liftIO $ assertNotEqual "" expected actual
-}
assertNotEqual :: (Eq a, Show a) => String -> a -> a -> Assertion
assertNotEqual preface expected actual =
unless (actual /= expected) (assertFailure msg)
where msg = (if null preface then "" else preface ++ "\n") ++
"expected: " ++ show expected ++ "\n to not equal: " ++ show actual
assertEmpty :: (Monad m, MonadIO m) => [a] -> m ()
assertEmpty xs = liftIO $ assertBool "" (null xs)
assertNotEmpty :: (Monad m, MonadIO m) => [a] -> m ()
assertNotEmpty xs = liftIO $ assertBool "" (not (null xs))
isTravis :: IO Bool
isTravis = do
env <- liftIO getEnvironment
return $ case lookup "TRAVIS" env of
Just "true" -> True
_ -> False
debugOn :: Bool
#ifdef DEBUG
debugOn = True
#else
debugOn = False
#endif
#ifdef WITH_POSTGRESQL
dockerPg :: IO (Maybe BS.ByteString)
dockerPg = do
env <- liftIO getEnvironment
return $ case lookup "POSTGRES_NAME" env of
Just _name -> Just "postgres" -- /persistent/postgres
_ -> Nothing
#endif
#ifdef WITH_NOSQL
persistSettings :: MkPersistSettings
persistSettings = (mkPersistSettings $ ConT ''Context) { mpsGeneric = True }
dbName :: Text
dbName = "persistent"
type BackendMonad = Context
#ifdef WITH_MONGODB
runConn :: (MonadIO m, MonadBaseControl IO m) => Action m backend -> m ()
runConn f = do
conf <- liftIO $ applyDockerEnv $ defaultMongoConf dbName -- { mgRsPrimary = Just "replicaset" }
void $ withMongoPool conf $ runMongoDBPool MongoDB.master f
setupMongo :: Action IO ()
setupMongo = void $ MongoDB.dropDatabase dbName
#endif
#ifdef WITH_ZOOKEEPER
runConn :: (MonadIO m, MonadBaseControl IO m) => Action m backend -> m ()
runConn f = do
let conf = defaultZookeeperConf {zCoord = "localhost:2181/" ++ T.unpack dbName}
void $ withZookeeperPool conf $ runZookeeperPool f
setupZookeeper :: Action IO ()
setupZookeeper = do
liftIO $ Z.setDebugLevel Z.ZLogError
deleteRecursive "/"
#endif
db' :: Action IO () -> Action IO () -> Assertion
db' actions cleanDB = do
r <- runConn (actions >> cleanDB)
return r
instance Arbitrary PersistValue where
arbitrary = PersistObjectId `fmap` BS.pack `fmap` replicateM 12 arbitrary
#else
persistSettings :: MkPersistSettings
persistSettings = sqlSettings { mpsGeneric = True }
type BackendMonad = SqlBackend
sqlite_database :: Text
sqlite_database = "test/testdb.sqlite3"
-- sqlite_database = ":memory:"
runConn :: (MonadIO m, MonadBaseControl IO m) => SqlPersistT (LoggingT m) t -> m ()
runConn f = do
travis <- liftIO isTravis
let debugPrint = not travis && debugOn
let printDebug = if debugPrint then print . fromLogStr else void . return
flip runLoggingT (\_ _ _ s -> printDebug s) $ do
# ifdef WITH_POSTGRESQL
_ <- if travis
then withPostgresqlPool "host=localhost port=5432 user=postgres dbname=persistent" 1 $ runSqlPool f
else do
host <- fromMaybe "localhost" <$> liftIO dockerPg
withPostgresqlPool ("host=" <> host <> " port=5432 user=postgres dbname=test") 1 $ runSqlPool f
# else
# ifdef WITH_MYSQL
_ <- if not travis
then withMySQLPool defaultConnectInfo
{ connectHost = "localhost"
, connectUser = "test"
, connectPassword = "test"
, connectDatabase = "test"
} 1 $ runSqlPool f
else withMySQLPool defaultConnectInfo
{ connectHost = "localhost"
, connectUser = "travis"
, connectPassword = ""
, connectDatabase = "persistent"
} 1 $ runSqlPool f
# else
_<-withSqlitePool sqlite_database 1 $ runSqlPool f
# endif
# endif
return ()
db :: SqlPersistT (LoggingT (ResourceT IO)) () -> Assertion
db actions = do
runResourceT $ runConn $ actions >> transactionUndo
#if !MIN_VERSION_random(1,0,1)
instance Random Int32 where
random g =
let ((i::Int), g') = random g in
(fromInteger $ toInteger i, g')
randomR (lo, hi) g =
let ((i::Int), g') = randomR (fromInteger $ toInteger lo, fromInteger $ toInteger hi) g in
(fromInteger $ toInteger i, g')
instance Random Int64 where
random g =
let ((i0::Int32), g0) = random g
((i1::Int32), g1) = random g0 in
(fromInteger (toInteger i0) + fromInteger (toInteger i1) * 2 ^ (32::Int), g1)
randomR (lo, hi) g = -- TODO : generate on the whole range, and not only on a part of it
let ((i::Int), g') = randomR (fromInteger $ toInteger lo, fromInteger $ toInteger hi) g in
(fromInteger $ toInteger i, g')
#endif
instance Arbitrary PersistValue where
arbitrary = PersistInt64 `fmap` choose (0, maxBound)
#endif
instance PersistStore backend => Arbitrary (BackendKey backend) where
arbitrary = (errorLeft . fromPersistValue) `fmap` arbitrary
where
errorLeft x = case x of
Left e -> error $ unpack e
Right r -> r
#ifdef WITH_NOSQL
#ifdef WITH_MONGODB
generateKey :: IO (BackendKey Context)
generateKey = MongoKey `liftM` MongoDB.genObjectId
#endif
#ifdef WITH_ZOOKEEPER
keyCounter :: IORef Int64
keyCounter = unsafePerformIO $ newIORef 1
{-# NOINLINE keyCounter #-}
generateKey :: IO (BackendKey Context)
generateKey = do
i <- readIORef keyCounter
writeIORef keyCounter (i + 1)
return $ ZooKey $ T.pack $ show i
#endif
#else
keyCounter :: IORef Int64
keyCounter = unsafePerformIO $ newIORef 1
{-# NOINLINE keyCounter #-}
generateKey :: IO (BackendKey SqlBackend)
generateKey = do
i <- readIORef keyCounter
writeIORef keyCounter (i + 1)
return $ SqlBackendKey $ i
#endif
| pseudonom/persistent | persistent-test/src/Init.hs | mit | 9,187 | 0 | 14 | 1,880 | 1,708 | 982 | 726 | 125 | 2 |
-- Exercise 0
--
_foldl1 f a bs = foldr (\b -> \g -> (\a -> g (f a b))) id bs a
_foldl2 f a bs = foldr (\a b -> f b a) a bs
_foldl3 f = flip $ foldr (\a b g -> b (f g a)) id
_foldl4 = foldr . flip | anwb/fp-one-on-one | lecture-13-hw.hs | mit | 208 | 0 | 13 | 68 | 139 | 72 | 67 | 4 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.NavigatorUserMediaErrorCallback (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.NavigatorUserMediaErrorCallback
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.NavigatorUserMediaErrorCallback
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/NavigatorUserMediaErrorCallback.hs | mit | 406 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
module Tach.Migration.RoutesSpec (main, spec) where
import Test.Hspec
import Data.ByteString.Lazy.Char8
import Yesod.Test
import Yesod
import Tach.Migration.Routes
import Yesod.Default.Config
import Tach.Impulse.Types.TimeValue
import Data.Aeson
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
yesodSpecWithSiteGenerator (return MigrationRoutes) test
-- test :: YesodSpec Application
test = ydescribe "Main api" $ do
yit "Should return 4" $ do
postBody ReceiveTimeSeriesR body
bodyEquals $ unpack body
where body :: ByteString
body = encode [(TVSimple 100 10.6 300),(TVSimple 100 10.6 300),(TVSimple 100 10.6 300),(TVSimple 100 10.6 300),(TVSimple 100 10.6 300),(TVSimple 100 10.6 300),(TVSimple 100 10.6 300),(TVSimple 100 10.6 300),(TVSimple 100 10.6 300)]
| smurphy8/tach | core-types/tach-migration-routes/test/Tach/Migration/RoutesSpec.hs | mit | 798 | 0 | 12 | 131 | 274 | 149 | 125 | 20 | 1 |
module Tests where
import Prelude hiding (lex, catch)
import Syntax.Lexer
import Syntax.Parser
import Syntax.Term
import Interpreter
import Typechecker
import Control.Exception
import System.Console.ANSI
greenColor = setSGR [SetColor Foreground Vivid Green]
yellowColor = setSGR [SetColor Foreground Vivid Yellow]
redColor = setSGR [SetColor Foreground Vivid Red]
cyanColor = setSGR [SetColor Foreground Vivid Cyan]
resetColor = setSGR [Reset]
data TestType = In | Tc
data Test = Passable String | Unpassable String
getString :: Test -> String
getString (Passable s) = s
getString (Unpassable s) = s
isPassable :: Test -> Bool
isPassable (Passable _) = True
isPassable (Unpassable _) = False
runTcTests :: IO ()
runTests fun tp nm rng = mapM_ (\ x -> do
cyanColor
putStrLn (nm ++ " Test #" ++ show x)
resetColor
catch (do
fun (getString $ test tp x)
if isPassable (test tp x)
then greenColor >> putStrLn "Pass"
else redColor >> putStrLn "Fail - should have failed, but passed"
resetColor) ((\ ex -> do
if isPassable (test tp x)
then do
redColor
putStrLn "\nFail"
yellowColor
putStrLn $ "Exception caught: " ++ (show ex)
else do
greenColor
putStrLn "\nPass - Controlled failure"
yellowColor
putStrLn $ "Exception caught: " ++ (show ex)
resetColor) :: SomeException -> IO ())) rng
runInTests = runTests rep In "Interpreter" [0 .. 12]
runTcTests = runTests retp Tc "Typechecker" [0 .. 14]
test Tc 0 = Passable "start: code{r0: uptr(), r2: uptr(int,int,int,int,int)} \n\
\r1 = mem[r2 + 5] \n\
\mem[r2 + 5] = r1 \n\
\r3 = malloc 3 \n\
\commit r3 \n\
\salloc 6 \n\
\sfree 2 \n\
\jump exit"
-- load i save na int, a nie pointer
test Tc 1 = Unpassable "start: code{r0: uptr(int), r2: int} \n\
\r1 = mem[r2 + 5] \n\
\mem[r2 + 5] = r1 \n\
\r3 = malloc 3 \n\
\commit r3 \n\
\salloc 6 \n\
\sfree 2 \n\
\jump exit"
test Tc 2 = Passable "troll: code{r0: uptr()}\n\
\salloc 2\n\
\r1 = 5\n\
\r2 = 7\n\
\mem[sp+1] = r1\n\
\mem[sp+2] = r2\n\
\sfree 1\n\
\jump exit"
-- commitowany stack pointer
test Tc 3 = Unpassable "troll: code{r0: ptr()}\n\
\salloc 2\n\
\r1 = 5\n\
\r2 = 7\n\
\mem[r0+1] = r1\n\
\mem[r0+2] = r2\n\
\sfree 1\n\
\jump exit"
test Tc 4 = Passable "copy: code{r1:ptr(int,int), r2:int,r3:int}\n\
\r2 = malloc 2;\n\
\r3 = mem[r1+1];\n\
\mem[r2+1] = r3;\n\
\r3 = mem[r1+2];\n\
\mem[r2+1] = r3;\n\
\commit r2;\n\
\jump exit"
test Tc 5 = Unpassable "copy: code{r1:ptr(int), r2:int,r3:int}\n\
\r2 = malloc 2;\n\
\r3 = mem[r1+1];\n\
\mem[r2+1] = r3;\n\
\r3 = mem[r1+2];\n\
\mem[r2+1] = r3;\n\
\commit r2;\n\
\jump exit"
test Tc 6 = Unpassable "copy: code{r1:ptr(int), r2:int}\n\
\r2 = malloc 2;\n\
\r3 = mem[r1+1];\n\
\mem[r2+1] = r3;\n\
\r3 = mem[r1+2];\n\
\mem[r2+1] = r3;\n\
\commit r2;\n\
\jump exit"
test Tc 7 = Passable "copy: code{}\n\
\r1 = malloc 2;\n\
\jump exit;"
test Tc 8 = Passable "start: code{r1:int}\n\
\r1 = 4 \n\
\jump exit\n"
test Tc 9 = Passable "start: code{r0: int, r1:int, r12:int, r33:int}\n\
\r1 = 4\n\n\
\r0 = 1\n\
\jump s2\n\
\trololol: code{r0:int, r1:int, r12:int, r33:int}\n\
\r33 = r1 + 1\n\
\ jump exit\n\
\s2: code{r0:int, r1:int, r12:int, r33:int}\n\
\if r0 jump trololol\n\
\r12 = 4\n\
\jump exit;comment trololol\n"
test Tc 10 = Unpassable "start: code{r0: int, r1:int, r12:int, r33:int}\n\
\r1 = 4\n\n\
\r0 = 1\n\
\jump s2\n\
\trololol: code{r0:int, r1:code{}, r12:int, r33:int}\n\
\r33 = r1 + 1\n\
\ jump exit\n\
\s2: code{r0:int, r1:int, r12:int, r33:int}\n\
\if r0 jump trololol\n\
\r12 = 4\n\
\jump exit;comment trololol\n"
test Tc 11 = Passable "prod: code{r1:int, r2:int, r3:int} \n\
\r3 = 0; res = 0\n\
\r1 = 5\n\
\r2 = 7\n\
\jump loop\n\n\
\loop: code{r1:int, r2:int, r3:int}\n\
\if r1 jump done; if a == 0 goto done\n\
\r3 = r2 + r3; res = res + b\n\
\r1 = r1 + -1; a = a - 1\n\
\jump loop\n\n\
\done: code{r1:int, r2:int, r3:int}\n\
\jump exit\n\n"
test Tc 12 = Passable "copy: code{}\n\
\r1 = malloc 2;\n\
\r2 = 5;\n\
\r3 = 3;\n\
\mem[r1+1] = r2;\n\
\mem[r1+2] = r3;\n\
\r4 = mem[r1+1]\n\
\r5 = mem[r1+2]\n\
\commit r1;\n\
\jump exit;"
test Tc 13 = Passable "loop: code{r1: int, r2: int, r3: int}\n\
\r3 = r2 + r3\n\
\r1 = r1 + -1\n\
\jump loop\n"
test Tc 14 = Unpassable "loop: code{r1: code{}, r2: int, r3: int}\n\
\r3 = r2 + r3\n\
\r1 = r1 + -1\n\
\jump loop\n"
test In 0 = Unpassable "start: code{r0: uptr(), r2: uptr(int,int,int,int,int)} \n\
\r1 = mem[r2 + 5] \n\
\mem[r2 + 5] = r1 \n\
\r3 = malloc 3 \n\
\commit r3 \n\
\salloc 6 \n\
\sfree 2 \n\
\jump exit"
test In 1 = Unpassable "start: code{r0: uptr(int), r2: int} \n\
\r1 = mem[r2 + 5] \n\
\mem[r2 + 5] = r1 \n\
\r3 = malloc 3 \n\
\commit r3 \n\
\salloc 6 \n\
\sfree 2 \n\
\jump exit"
test In 2 = Passable "troll: code{r0: uptr()}\n\
\salloc 2\n\
\r1 = 5\n\
\r2 = 7\n\
\mem[r0+1] = r1\n\
\mem[r0+2] = r2\n\
\sfree 1\n\
\jump exit"
test In 3 = Passable "troll: code{r0: ptr()}\n\
\salloc 2\n\
\r1 = 5\n\
\r2 = 7\n\
\mem[r0+1] = r1\n\
\mem[r0+2] = r2\n\
\sfree 1\n\
\jump exit"
test In 4 = Unpassable "copy: code{r1:ptr(int,int), r2:int,r3:int}\n\
\r2 = malloc 2;\n\
\r3 = mem[r1+1];\n\
\mem[r2+1] = r3;\n\
\r3 = mem[r1+2];\n\
\mem[r2+1] = r3;\n\
\commit r2;\n\
\jump exit"
test In 5 = Unpassable "copy: code{r1:ptr(int), r2:int,r3:int}\n\
\r2 = malloc 2;\n\
\r3 = mem[r1+1];\n\
\mem[r2+1] = r3;\n\
\r3 = mem[r1+2];\n\
\mem[r2+1] = r3;\n\
\commit r2;\n\
\jump exit"
test In 6 = Unpassable "copy: code{r1:ptr(int), r2:int}\n\
\r2 = malloc 2;\n\
\r3 = mem[r1+1];\n\
\mem[r2+1] = r3;\n\
\r3 = mem[r1+2];\n\
\mem[r2+1] = r3;\n\
\commit r2;\n\
\jump exit"
test In 7 = Passable "copy: code{}\n\
\r1 = malloc 2;\n\
\jump exit;"
test In 8 = Passable "start: code{r1:int}\n\
\r1 = 4 \n\
\jump exit\n"
test In 9 = Passable "start: code{r0: int, r1:int, r12:int, r33:int}\n\
\r1 = 4\n\n\
\r0 = 1\n\
\jump s2\n\
\trololol: code{r0:int, r1:int, r12:int, r33:int}\n\
\r33 = r1 + 1\n\
\ jump exit\n\
\s2: code{r0:int, r1:int, r12:int, r33:int}\n\
\if r0 jump trololol\n\
\r12 = 4\n\
\jump exit;comment trololol\n"
test In 10 = Passable "start: code{r0: int, r1:int, r12:int, r33:int}\n\
\r1 = 4\n\n\
\r0 = 1\n\
\jump s2\n\
\trololol: code{r0:int, r1:code{}, r12:int, r33:int}\n\
\r33 = r1 + 1\n\
\ jump exit\n\
\s2: code{r0:int, r1:int, r12:int, r33:int}\n\
\if r0 jump trololol\n\
\r12 = 4\n\
\jump exit;comment trololol\n"
test In 11 = Passable "prod: code{r1:int, r2:int, r3:int} \n\
\r3 = 0; res = 0\n\
\r1 = 5\n\
\r2 = 7\n\
\jump loop\n\n\
\loop: code{r1:int, r2:int, r3:int}\n\
\if r1 jump done; if a == 0 goto done\n\
\r3 = r2 + r3; res = res + b\n\
\r1 = r1 + -1; a = a - 1\n\
\jump loop\n\n\
\done: code{r1:int, r2:int, r3:int}\n\
\jump exit\n\n"
test In 12 = Passable "copy: code{}\n\
\r1 = malloc 2;\n\
\r2 = 5;\n\
\r3 = 3;\n\
\mem[r1+1] = r2;\n\
\mem[r1+2] = r3;\n\
\r4 = mem[r1+1]\n\
\r5 = mem[r1+2]\n\
\commit r1;\n\
\jump exit;"
| drx/petal | Tests.hs | mit | 9,425 | 0 | 21 | 3,844 | 872 | 427 | 445 | 75 | 3 |
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-unused-binds -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
-- | A test specification for Web.TSBot.ClientQuery.Parse
module Web.TSBot.ClientQuery.ParseSpec (spec) where
import Control.Applicative ((<*))
import Control.Arrow (first)
import Data.Attoparsec.Text
import Data.Char (isAlpha, isControl,
isSpace)
import Data.Functor ((<$>))
import Data.Text (Text, pack, unpack)
import Web.TSBot ()
import Web.TSBot.ClientQuery.Parse
import Web.TSBot.ClientQuery.PrettyPrint
import Web.TSBot.ClientQuery.Response
import Web.TSBot.ClientQuery.ResponseSpec (CQRL (..))
import Test.Hspec
import Test.QuickCheck
testParse :: Text -> Either String CQResponse
testParse = parseOnly (responseP <* endOfInput)
parseInv :: CQRL -> Property
parseInv (CQRL c) = testParse (resPrint c) === Right c
parseIs :: (Eq c, Show c) =>
(a -> b)
-> (b -> Text)
-> (CQResponse -> c)
-> (b -> c)
-> a -> Property
parseIs f tf tg cf i = case testParse $ tf $ f i of
Left _ -> property False
Right p -> tg p === cf (f i)
spec :: Spec
spec =
describe "responseP" $ do
context "when given an empty string" $ do
it "returns [fromListCQR []]" $ do
testParse "" `shouldBe` Right [fromListCQR []]
context "when given a string of n pipes ('|')" $ do
it "gives a list with a length n + 1" $ do
property $ parseIs getPositive (pack . flip replicate '|') length (+1)
context "when given ugly-printed [CQR]" $ do
it "is an involution" $ do
property parseInv
| taktoa/TSBot | test-suite/Web/TSBot/ClientQuery/ParseSpec.hs | mit | 2,021 | 0 | 18 | 706 | 487 | 261 | 226 | 44 | 2 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLTitleElement
(js_setText, setText, js_getText, getText, HTMLTitleElement,
castToHTMLTitleElement, gTypeHTMLTitleElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"text\"] = $2;" js_setText ::
JSRef HTMLTitleElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTitleElement.text Mozilla HTMLTitleElement.text documentation>
setText ::
(MonadIO m, ToJSString val) =>
HTMLTitleElement -> Maybe val -> m ()
setText self val
= liftIO
(js_setText (unHTMLTitleElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"text\"]" js_getText ::
JSRef HTMLTitleElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLTitleElement.text Mozilla HTMLTitleElement.text documentation>
getText ::
(MonadIO m, FromJSString result) =>
HTMLTitleElement -> m (Maybe result)
getText self
= liftIO
(fromMaybeJSString <$> (js_getText (unHTMLTitleElement self))) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/HTMLTitleElement.hs | mit | 1,898 | 14 | 11 | 271 | 502 | 302 | 200 | 34 | 1 |
{-# LANGUAGE ExistentialQuantification #-}
module Dumblisp.Eval (eval) where
import Dumblisp.Types
import Dumblisp.Env
import Dumblisp.Primitives
import Control.Monad.Error
import Data.Maybe (isNothing)
makeFunc varargs env params body = return $ Func (map showVal params) varargs body env
makeNormalFunc = makeFunc Nothing
makeVarArgs = makeFunc . Just . showVal
apply :: LispVal -> [LispVal] -> IOThrowsError LispVal
apply (PrimitiveFunc func) args = liftThrows $ func args
apply (Func params varargs body closure) args =
if num params /= num args && isNothing varargs
then throwError $ NumArgs (num params) args
else (liftIO $ bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalBody
where remainingArgs = drop (length params) args
num = toInteger . length
evalBody env = liftM last $ mapM (eval env) body
bindVarArgs arg env = case arg of
Just argName -> liftIO $ bindVars env [(argName, List remainingArgs)]
Nothing -> return env
apply (IOFunc func) args = func args
eval :: Env -> LispVal -> IOThrowsError LispVal
eval env val@(String _) = return val
eval env val@(Number _) = return val
eval env val@(Bool _) = return val
eval env (Atom id) = getVar env id
eval env (List [Atom "quote", val]) = return val
eval env (List [Atom "if", pred, conseq, alt]) =
do result <- eval env pred
case result of
Bool False -> eval env alt
_ -> eval env conseq
eval env (List [Atom "set!", Atom var, form]) =
eval env form >>= setVar env var
eval env (List [Atom "define", Atom var, form]) =
eval env form >>= defineVar env var
eval env (List (Atom "define" : List (Atom var : params) : body)) =
makeNormalFunc env params body >>= defineVar env var
eval env (List (Atom "define" : DottedList (Atom var : params) varargs : body)) =
makeVarArgs varargs env params body >>= defineVar env var
eval env (List (Atom "lambda" : List params : body)) =
makeNormalFunc env params body
eval env (List (Atom "lambda" : DottedList params varargs : body)) =
makeVarArgs varargs env params body
eval env (List (Atom "lambda" : varargs@(Atom _) : body)) =
makeVarArgs varargs env [] body
eval env (List [Atom "apply" , func ,List args]) =
apply func args
eval env (List (Atom "apply" : func : args)) =
apply func args
eval env (List [Atom "load", String filename]) =
load filename >>= liftM last . mapM (eval env)
eval env (List (function : args)) = do
func <- eval env function
argVals <- mapM (eval env) args
apply func argVals
eval env badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm
| mmailhot/Dumblisp | Dumblisp/Eval.hs | mit | 2,617 | 0 | 14 | 540 | 1,112 | 545 | 567 | 59 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
module RWPAS.Role.Psychic
( AuraType(..)
, activate )
where
import Control.Lens
import Control.Monad.State.Strict
import Data.Data
import Data.Foldable
import Data.Maybe
import Data.Monoid
import qualified Data.IntSet as IS
import Data.Set ( Set )
import Data.Text ( Text )
import Linear.Metric
import Linear.V2
import GHC.Generics
import RWPAS.Actor
import RWPAS.BresenhamLine
import RWPAS.Control.ControlMonad
import RWPAS.Direction
import RWPAS.Level.Type
import RWPAS.World.Type
data Psychic = Psychic
{ _learnedAuras :: Set AuraType }
deriving ( Eq, Ord, Show, Read, Typeable, Data, Generic )
data AuraType
= RepulsionForce
deriving ( Eq, Ord, Show, Read, Typeable, Data, Generic, Enum )
makeLenses ''Psychic
auraName :: AuraType -> Text
auraName RepulsionForce = "repulsion force"
auraHelp :: AuraType -> Text
auraHelp RepulsionForce
= "Emits a field of force that pushes back foes, sometimes violently."
activate :: ControlActorMonad s m
=> AuraType
-> WorldCoordinates
-> m ()
activate RepulsionForce coords = repulsionActivate coords
repulsionActivate :: ControlActorMonad s m
=> WorldCoordinates
-> m ()
repulsionActivate coords = do
immune_aid <- myActorID
-- keep a state of actors that have already been repulsed/are immune
void $ flip evalStateT (IS.singleton immune_aid) $ do
-- shoot bresenham to the edge of the repulsion field
-- top and bottom
for_ [-10..10] $ \x -> do
shootRepulsionLine (V2 x (-10))
shootRepulsionLine (V2 x 10)
-- left and right (-9 to 9 because corners were already taken above)
for_ [-9..9] $ \y -> do
shootRepulsionLine (V2 (-10) y)
shootRepulsionLine (V2 10 y)
r <- rollUniformR (0, 4 :: Int)
emitMessage $ case r of
0 -> "KABOOOM!!"
1 -> "BATAANNNGG!!!"
2 -> "DONNNGG!"
3 -> "KATANNGGGG!!"
_ -> "BAZANGGGG!"
where
shootRepulsionLine target_coords =
void $ flip execStateT coords $
bresenhamLineDirectionP target_coords $ \dir relative_coords -> do
my_pos <- get
new_pos <- lift $ lift $ moveCoords dir my_pos
put new_pos
f <- lift $ lift $ use (world.terrainAt new_pos)
case f of
Just t | impassable t -> return False
_ -> do excluded <- lift get
(lift $ lift $ use $ world.actorAt new_pos) >>= \case
Just (victim_id, victim) | IS.notMember victim_id excluded -> do
let power = 20.0 / (norm $ fmap fromIntegral relative_coords)
lift $ modify $ IS.insert victim_id
lift $ lift $ hurlVictim new_pos momentum power
return True
_ -> return True
where
momentum :: V2 Double
momentum = signorm $ fmap fromIntegral target_coords
hurlVictim :: ControlMonad s m
=> WorldCoordinates
-> V2 Double
-> Double
-> m ()
hurlVictim coords direction@(V2 dx'' dy'') original_power =
use (world.actorAt coords) >>= \case
Nothing -> return ()
Just ac -> loop ac coords coords original_power
where
dx' = abs dx''
dy' = abs dy''
dx = dx' / (dx' + dy')
dy = dy' / (dx' + dy')
move_x_dir = if dx'' >= 0 then D8Right else D8Left
move_y_dir = if dy'' >= 0 then D8Down else D8Up
loop ac@(_, actor) last_coords current_coords power | power > 0 = do
f <- use (world.terrainAt current_coords)
a <- use (world.actorAt current_coords)
if (impassable <$> f) /= Just False || (isJust a && last_coords /= current_coords)
then do case a^?_Just._2.actorName of
Just name ->
emitMessage $ actor^.actorName <> " collides with " <> name <> "!"
_ -> emitMessage $ actor^.actorName <> " smashes into an obstacle!"
hurlTarget ac last_coords True
else do rx <- rollUniformR (0, 1 :: Double)
ry <- rollUniformR (0, 1 :: Double)
coords1 <- if rx < dx then moveOnXAxis else return current_coords
coords2 <- if ry < dy then moveOnYAxis else return coords1
loop ac current_coords coords2 (power-1)
where
moveOnXAxis = moveCoords move_x_dir current_coords
moveOnYAxis = moveCoords move_y_dir current_coords
loop ac final_coords _ _ = hurlTarget ac final_coords False
hurlTarget ac@(actor_id, actor) final_coords hurt_it = do
world.actorAt coords .= Nothing
world.actorAt final_coords .= Just (if hurt_it
then (actor_id, hurt (ceiling original_power) actor)
else ac)
| Noeda/rwpas | src/RWPAS/Role/Psychic.hs | mit | 4,882 | 0 | 29 | 1,367 | 1,428 | 720 | 708 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import RIO
import qualified RIO.Text as Text
import qualified System.Etc as Etc
import Paths_etc_plain_example (getDataFileName)
--------------------------------------------------------------------------------
-- We specify the support commands for our program
main :: IO ()
main = do
specPath <- getDataFileName "spec.yaml"
configSpec <- Etc.readConfigSpec (Text.pack specPath)
Etc.reportEnvMisspellingWarnings configSpec
(configFiles, _fileWarnings) <- Etc.resolveFiles configSpec
configEnv <- Etc.resolveEnv configSpec
configOptParser <- Etc.resolvePlainCli configSpec
let configDefault = Etc.resolveDefault configSpec
config =
configFiles `mappend` configDefault `mappend` configEnv `mappend` configOptParser
Etc.printPrettyConfig config
| roman/Haskell-etc | examples/etc-plain-example/src/Main.hs | mit | 955 | 0 | 12 | 175 | 176 | 94 | 82 | 20 | 1 |
module Logic.PropositionalLogic.Terms where
import Notes
makeDefs [
"Propositional logic"
, "boolean value"
, "implication"
, "equivalence"
, "valid"
, "satisfiable"
, "unsatisfiable"
, "logically equivalent"
, "conjunctive normal form"
]
| NorfairKing/the-notes | src/Logic/PropositionalLogic/Terms.hs | gpl-2.0 | 293 | 0 | 6 | 84 | 43 | 27 | 16 | -1 | -1 |
module Git.Commit where
import Foreign.ForeignPtr hiding (newForeignPtr)
import Foreign.Concurrent
import Foreign.Ptr
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Marshal.Utils
import Foreign.Storable
import Foreign.C.String
import Git.Result
import Git.Repository
import Git.Oid
import Git.Tree
import Git.Object
import Bindings.Libgit2
data Commit = Commit { commit_ptr::ForeignPtr C'git_commit
, commit_repo_ptr::ForeignPtr C'git_repository
}
lookup::Repository -> Oid -> Result Commit
lookup repo oid = lookup_wrapped_object repo oid wrap c'GIT_OBJ_COMMIT
where
wrap fptr = Commit { commit_ptr = fptr, commit_repo_ptr = repository_ptr repo}
type Ref = String
type Message = String
type OidT a = Oid
type Author = Signature
type Committer = Signature
data Time = Time { time_epoch::Integer, time_offset::Int }
data Signature = Signature { signature_author::String, signature_email::String, signature_time::Time }
with_signature::Signature -> (C'git_signature -> Result a) -> Result a
with_signature sig action = do
withCString (signature_author sig) $ \c'author -> do
withCString (signature_email sig) $ \c'email -> do
let c'time = C'git_time (fromIntegral $ time_epoch $ signature_time sig) (fromIntegral $ time_offset $ signature_time sig)
c'sig = C'git_signature c'author c'email c'time
action c'sig
with_signature_ptr::Signature -> (Ptr C'git_signature -> Result a) -> Result a
with_signature_ptr sig action = with_signature sig $ \c'sig -> with c'sig action
withMaybeCString::Maybe String -> (CString -> IO a) -> IO a
withMaybeCString string action = maybe (action nullPtr) (flip withCString action) string
withForeignPtrs::[ForeignPtr a] -> ([Ptr a] -> IO b) -> IO b
withForeignPtrs fptrs action = go fptrs []
where
go [] fptrs = action $ reverse fptrs
go (a:as) fptrs = withForeignPtr a $ \fptr -> go as (fptr:fptrs)
create::Repository -> Maybe Ref -> Author -> Committer -> Message -> OidT Tree -> [OidT Commit] -> Result (OidT Commit)
create repo ref author committer message tree parents = do
oid_fptr <- mallocForeignPtr
withForeignPtr oid_fptr $ \result_oid_ptr -> do
withForeignPtr (repository_ptr repo) $ \repo_ptr -> do
withMaybeCString ref $ \ref_ptr -> do
with_signature_ptr author $ \c'author_ptr -> do
with_signature_ptr committer $ \ c'committer_ptr -> do
withCString message $ \message_ptr -> do
withForeignPtr (oid_ptr tree) $ \tree_ptr -> do
withForeignPtrs (map oid_ptr parents) $ \parent_oid_ptrs -> do
parent_oids <- mapM peek parent_oid_ptrs
withArray parent_oids $ \parent_oid_array -> do
c'git_commit_create result_oid_ptr repo_ptr ref_ptr c'author_ptr c'committer_ptr message_ptr tree_ptr (fromIntegral $ length parents) parent_oid_array `handle_git_return` (return $ Oid oid_fptr) | sakari/hgit | src/Git/Commit.hs | gpl-2.0 | 2,990 | 0 | 48 | 606 | 922 | 473 | 449 | 56 | 2 |
{- | Module : $Header$
- Description : Implementation of logic instance Coalition Logic
- Copyright : (c) Daniel Hausmann & Georgel Calin & Lutz Schroeder, DFKI Lab Bremen,
- Rob Myers & Dirk Pattinson, Department of Computing, ICL
- License : GPLv2 or higher, see LICENSE.txt
- Maintainer : [email protected]
- Stability : provisional
- Portability : portable
-
- Provides the implementation of the matching functions of coalition logic.
-}
module GMP.Logics.C where
import List
import Ratio
import Maybe
import Debug.Trace
import Text.ParserCombinators.Parsec
import GMP.Logics.Generic
import GMP.Parser
--------------------------------------------------------------------------------
-- instance of feature for coalition logic
--------------------------------------------------------------------------------
data C a = C [Int] [Formula a] deriving (Eq,Show)
agents :: Int; agents = 10
-- For each positive modal literal, there are possibly serveral premises,
-- containing only one sequent each. This sequent contains the stripped positive
-- literal and additional stripped literals which are computed by
-- 'c_build_matches'. Also there is one additional premise, containing the sequent
-- of all negated stripped negative literals.
-- e.g. seq = [ (M (C [0,3]) p), !(M (C [0]) q), (M (C [0,2,3]) !p), !(M (C [1]) !r)]
-- match seq = [ [[ p, !p, !q ]], [[ p, !p, !q]], [[!q, r]] ]
instance (SigFeature b c d, Eq (b (c d)), Eq (c d)) => NonEmptyFeature C b c d where
nefMatch flags seq = let neglits = [ (Neg phi) | (Neg (Mod (C s [phi]))) <- seq ]
poslits = [ phi | (Mod (C s [phi])) <- seq ]
in if (flags!!1)
then
[ [[Sequent (c_match++poslits)]] | c_match <- c_build_matches (keep_poslits seq) (keep_neglits seq)]
++ [[[Sequent neglits]]]
else
[ [[Sequent (c_match++poslits)]] | c_match <- c_build_matches (keep_poslits seq) (keep_neglits seq)]
++ [[[Sequent neglits]]]
nefPretty d = case d of
C l [] -> "[C]" ++ show l ++ "nothing contained"
C l e -> "[C]" ++ show l ++ (pretty (head e))
nefFeatureFromSignature sig = C [1]
nefFeatureFromFormula phi = C [1]
nefStripFeature (C i phis) = phis
nefDisj2Conj (Mod (C l phi)) = Mod (C l ([disj2conj (head phi)]))
nefNegNorm (Mod (C l phi)) = Mod (C l ([negNorm (head phi)]))
nefParser sig = do -- checks whether there are more numbers to be parsed
let stopParser = do char ','
return False
<|> do char '}'
return True
<?> "Parser.parseCindex.stop"
-- checks whether the index is of the form x1,..,x&
let normalParser l = do x <- natural
let n = fromInteger x
spaces
q <- stopParser
spaces
case q of
False -> normalParser (n:l)
_ -> return (n:l)
<?> "Parser.parseCindex.normal"
char '{'
res <- try(normalParser [])
return $ C res
<|> do -- checks whether the index is of the form "n..m"
let shortParser = do x <- natural
let n = fromInteger x
spaces
string ".."
spaces
y <- natural
let m = fromInteger y
return $ [n..m]
<?> "Parser.parseCindex.short"
res <- try(shortParser)
return $ C res
<?> "Parser.parseCindex"
--------------------------------------------------------------------------------
-- additional functions for the matching function of this logic
--------------------------------------------------------------------------------
-- Form negative literal parts of matching premise for positive literals
c_build_matches :: (Eq b) => [Formula (C b)] -> [Formula (C b)] -> [[Formula b]]
c_build_matches [] _ = []
c_build_matches ( (Mod (C pset pphi)):pls) nls =
let relevant_neglits = filter (\(Neg(Mod (C s _))) -> ((s `intersect` pset)==s)) nls
relevant_ncoalitions = nub $ map (\(Neg(Mod (C s _))) -> s) relevant_neglits
maximal_pw_dis_lists = rm_sublists $ sortBy compare_length
(filter (pairwise_disjunct)
(powerList relevant_ncoalitions))
negmats = [ [Neg phi] | [(Neg (Mod (C s [phi])))] <- (concatMap (build_lit_lists relevant_neglits) maximal_pw_dis_lists)]
in (map ([head pphi]++) negmats) ++ (c_build_matches pls nls)
-- Given a list of negative literals and a list of pairwise disjunctive lists, form pairwise
-- disjunctive lists of the according literals
build_lit_lists :: (Eq b) => [Formula (C b)] -> [[Int]] -> [[Formula (C b)]]
build_lit_lists _ [] = [[]]
build_lit_lists lits (set:sets) = let relevant_neglits = filter (\(Neg(Mod (C t _))) -> set==t) lits
in if null(relevant_neglits) then [] else
(map ([head relevant_neglits]++) (build_lit_lists lits sets))
++ (build_lit_lists (lits\\[head relevant_neglits]) (set:sets))
-- Does the list contain only pairwise disjunct lists?
pairwise_disjunct :: (Eq a) => [[a]] -> Bool
pairwise_disjunct [] = True
pairwise_disjunct (x:xs) = if (all (\y -> null(x `intersect` y)) xs) then (pairwise_disjunct xs) else False
-- Remove sublists (i.e. keep only maximal lists). Requires input to be sorted
rm_sublists :: (Eq a) => [[a]] -> [[a]]
rm_sublists [] = []
rm_sublists (x:xs) | (any (\y -> (x `intersect` y == x)) xs) = rm_sublists(xs)
| otherwise = x:rm_sublists(xs)
-- Compare lists by size.
compare_length :: [a] -> [a] -> Ordering
compare_length s t = if(length(s) < length(t)) then LT else GT
--------------------------------------------------------------------------------
-- instance of sigFeature for coalition logic
--------------------------------------------------------------------------------
instance (SigFeature b c d, Eq (c d), Eq (b (c d))) => NonEmptySigFeature C b c d where
neGoOn sig flag = genericPGoOn sig flag
| nevrenato/Hets_Fork | GMP/GMP-CoLoSS/GMP/Logics/C.hs | gpl-2.0 | 7,147 | 7 | 21 | 2,602 | 1,758 | 916 | 842 | -1 | -1 |
module Graphics.Implicit.Export.Symbolic.Rebound2 (rebound2) where
import Data.VectorSpace
import Graphics.Implicit.Definitions
rebound2 :: BoxedObj2 -> BoxedObj2
rebound2 (obj, (a,b)) =
let
d :: ℝ2
d = (b ^-^ a) ^/ 10
in
(obj, ((a ^-^ d), (b ^+^ d)))
| silky/ImplicitCAD | Graphics/Implicit/Export/Symbolic/Rebound2.hs | gpl-2.0 | 290 | 0 | 11 | 72 | 107 | 64 | 43 | 9 | 1 |
module Network.Gitit.Plugins.PlantUML (plugin) where
{-
This plugin allows you to include a plantuml diagram
in a page like this:
~~~ {.plantuml name="plantuml_diagram1"}
@startuml
Bob -> Alice : hello
@enduml
~~~
Must be installed and in the path:
- Java virtual machine (java)
- Copy "plantuml.jar" at a known location.
See: http://plantuml.sourceforge.net/download.html
- add planuml.jar to the CLASSPATH environment variable.
- e.g. (Windows): set CLASSPATH=C:\My\AbsPath\To\Jar\Files\plantuml.jar;%CLASSPATH%
- e.g. (Unix): export CLASSPATH=/My/AbsPath/To/Jar/Files/plantuml.jar:%CLASSPATH%
- The "dot" executable must be in the path.
See: http://www.graphviz.org/Download.php
- We also assume an executable wrapper that will properly handle
calls in the form `plantuml myArguments`.
The generated png file will be saved in the static img directory.
If no name is specified, a unique name will be generated from a hash
of the file contents.
Any classes not handled by the plug-in are simply handled to the
Span wrapper put around the image container.
The first id attribute found is handled to the previously mentioned
Span wrapper.
The preceding two points allow a user to add some classes and an id
to a diagram in order to control its layout using a custom css.
~~~ {#my-class-diagram .plantuml .auto-expand }
..
~~~
with a `custom.css` of:
..
span.auto-expand img {
width: 100%;
}
span#my-class-diagram img {
border: 2px solid grey;
}
Will give a diagram that auto-expand to its container and
that has a 2px grey border.
-}
import Network.Gitit.Interface
import System.Exit (ExitCode(ExitSuccess))
-- from the utf8-string package on HackageDB:
import Data.ByteString.Lazy.UTF8 (fromString)
-- from the SHA package on HackageDB:
import Data.Digest.Pure.SHA (sha1, showDigest)
import System.FilePath ((</>), takeDirectory, normalise)
import System.Directory(createDirectoryIfMissing)
import Control.Monad.Trans (liftIO)
import Control.Concurrent
import Data.List (intersperse)
-- Needed only for runProcessWithStrInToOutFile. TODO: Think about moving the funtion to its own module.
import System.Process (createProcess, proc, CreateProcess(..), CmdSpec(..), StdStream(..), ProcessHandle, waitForProcess)
import System.IO (withBinaryFile, hGetContents, hPutStr, hClose, hFlush, IOMode(..))
import qualified Control.Exception as C
import Control.Monad (when)
plugin :: Plugin
plugin = mkPageTransformM transformBlock
transformBlock :: Block -> PluginM Block
transformBlock (CodeBlock (id, classes, namevals) contents) | "plantuml" `elem` classes = do
cfg <- askConfig
rq <- askRequest
--meta <- askMeta
--ctx <- getContext
let
handledClasses = ["plantuml"]
unhandledClasses = filter (\e -> not (elem e handledClasses)) classes
relUrlToCurrentDir = drop 1 . rqUri $ rq
isRelUri :: String -> Bool
isRelUri uri = take 1 uri /= "/"
uriFromImg oriUri | isRelUri oriUri = relUrlToCurrentDir ++ "/" ++ oriUri
| otherwise = drop 1 oriUri
(outExt, ftParams) = case lookup "type" namevals of
Just ft -> ('.':ft, ["-t" ++ ft])
Nothing -> (".png", [])
(name, outfile) = case lookup "name" namevals of
Just fn -> ([Str fn], uriFromImg fn ++ outExt)
Nothing -> ([], "unnamed/" ++
uniqueName contents ++ outExt)
exeName = "plantuml"
args = ["-pipe"] ++ ftParams
handledAttrs = ["type", "name"]
unhandledAttrs = filter (\e -> not (elem (fst e) handledAttrs)) namevals
localOutFn = normalise (staticDir cfg) </> "img" </> (normalise outfile)
localOutDir = takeDirectory localOutFn
liftIO $ do
createDirectoryIfMissing True localOutDir
(ec, stderr) <- runProcessWithStrInToOutFile exeName args contents localOutFn
if ec == ExitSuccess && "" == stderr
then
let
imgInline = Image nullAttr name ("/img/" ++ outfile, "")
imgBlock = Para [Span (id, unhandledClasses, unhandledAttrs) [imgInline]]
in
return $ imgBlock
else
let
errorBlock = CodeBlock (id, classes, namevals) errorMsg
errorMsg =
"[content] | " ++ exeName ++ " " ++ (concat . intersperse " " $ args) ++ "\n\n" ++
prettyPrintErrorCode ec ++
prettyPrintStdStream "stderr" stderr
in
return $ errorBlock
transformBlock x = return x
prettyPrintErrorCode ExitSuccess = ""
prettyPrintErrorCode ec =
"error code\n" ++
"==========\n\n" ++ show ec ++ "\n\n";
prettyPrintStdStream _ "" = ""
prettyPrintStdStream streamName content =
streamName ++ "\n" ++
"======\n\n" ++ content ++ "\n\n";
runProcessWithStrInToOutFile :: FilePath -> [String] -> String -> FilePath -> IO (ExitCode, String)
runProcessWithStrInToOutFile cmd args input outfp =
withBinaryFile outfp WriteMode $ \outHdl -> do
outMVar <- newEmptyMVar
(Just inh, _, Just errh, pid) <-
createProcess (proc cmd args){ std_out = (UseHandle outHdl), std_in = CreatePipe, std_err = CreatePipe }
err <- hGetContents errh
_ <- forkIO $ C.evaluate (length err) >> putMVar outMVar ()
-- hSetBinaryMode inp False
-- now write and flush any input
when (not (null input)) $ do hPutStr inh input; hFlush inh
hClose inh -- done with stdin
-- wait on the output
takeMVar outMVar
hClose errh
-- wait on the process
ex <- waitForProcess pid
return (ex, err)
-- | Generate a unique filename given the file's contents.
uniqueName :: String -> String
uniqueName = showDigest . sha1 . fromString
| jraygauthier/jrg-gitit-plugins | src/Network/Gitit/Plugins/PlantUML.hs | gpl-2.0 | 6,232 | 0 | 23 | 1,804 | 1,197 | 639 | 558 | 81 | 4 |
module Antimony.Resource.Primitives where
import H.Generic
import Antimony.Resource.Core
import Antimony.Types
data Role = RoleOwner | RoleGroup | RoleOther
deriving (Eq, Ord, Enum, Bounded, Show, Typeable)
data Permissions =
Permissions
{ canRead :: Bool
, canWrite :: Bool
, canExecute :: Bool
} deriving (Eq, Ord, Bounded, Show, Typeable)
data FileState =
FileState
{ fileOwner :: Text
, fileMode :: [(Role, Permissions)]
} deriving (Eq, Ord, Show, Typeable)
data Directory =
RootDirectory
| Directory Text FileState
deriving (Eq, Ord, Show, Typeable)
data File = File Directory Text FileState Text
deriving (Eq, Ord, Show, Typeable)
data Package = Package Text (Maybe VersionConstraint)
deriving (Eq, Ord, Show, Typeable)
data Service = Service Text Bool
deriving (Eq, Ord, Show, Typeable)
data Group = Group Text [Resource]
deriving (Eq, Ord, Show, Typeable)
| ktvoelker/Antimony | src/Antimony/Resource/Primitives.hs | gpl-3.0 | 920 | 0 | 10 | 182 | 328 | 184 | 144 | 29 | 0 |
{-# LANGUAGE ExistentialQuantification, Rank2Types #-}
{-# LANGUAGE LambdaCase #-}
module Craeft.TypedAST.Pass where
import Control.Lens
import Control.Monad
import Debug.Trace (trace)
import Craeft.TypedAST.Impl
import Craeft.TypedAST.Lens
import qualified Craeft.Types as Types
import Craeft.Types (Type)
import Craeft.Utility
-- | A traversal into all leaf expressions.
eachLeafExpression :: Traversal' ExpressionContents ExpressionContents
eachLeafExpression f expr = case expr of
Reference _ ->
(referencedVal.eachLValueExpr.exprContents.eachLeafExpression) f expr
Binop lhs op rhs -> flip Binop op <$> subExprs f lhs <*> subExprs f rhs
FunctionCall func args targs -> FunctionCall
<$> subExprs f func
<*> (each.subExprs) f args
<*> pure targs
Cast _ -> (castedExpr.subExprs $ f) expr
LValueExpr _ ->
(lvalueExpr.eachLValueExpr.exprContents.eachLeafExpression) f expr
other -> f other
where subExprs = contents.exprContents.eachLeafExpression
eachExprFunctionCall :: Traversal' ExpressionContents (Annotated Expression,
[Annotated Expression],
[Types.Type] )
eachExprFunctionCall f expr = case expr of
Reference _ ->
(referencedVal.eachLValueExpr.exprContents.eachExprFunctionCall) f expr
Binop lhs op rhs -> flip Binop op <$> subExprs f lhs <*> subExprs f rhs
FunctionCall func args targs -> uncurry3 FunctionCall
<$> f (func, args, targs)
Cast _ -> (castedExpr.subExprs $ f) expr
LValueExpr _ ->
(lvalueExpr.eachLValueExpr.exprContents.eachExprFunctionCall) f expr
other -> pure other
where subExprs = contents.exprContents.eachExprFunctionCall
uncurry3 f (x, y, z) = f x y z
eachLValueExpr :: Traversal' LValue Expression
eachLValueExpr f d@(Dereference _) = (derefPointer.contents) f d
eachLValueExpr f (FieldAccess e i) =
FieldAccess <$> f e <*> pure i
eachLValueExpr f other = pure other
-- | Does *not* include sub-statements.
--
-- To do that, just do `eachSubStmt.eachExpressionInStmt`.
eachExpressionInStmt :: Traversal' Statement Expression
eachExpressionInStmt f stmt = case stmt of
ExpressionStmt e -> stmtExpr f stmt
Return ret -> (retExpr.contents) f stmt
Assignment l r -> Assignment <$> (contents.eachLValueExpr) f l
<*> contents f r
CompoundDeclaration n t e -> CompoundDeclaration n t
<$> contents f e
IfStatement c ifB elseB -> IfStatement
<$> contents f c
<*> (each.contents.eachExpressionInStmt) f ifB
<*> (each.contents.eachExpressionInStmt) f elseB
other -> pure other
eachSubStmt :: Traversal' Statement Statement
eachSubStmt f stmt = case stmt of
IfStatement c ifB elseB -> IfStatement c
<$> (each.contents.eachSubStmt) f ifB
<*> (each.contents.eachSubStmt) f elseB
other -> f other
eachStatementInBlock :: Traversal' Block Statement
eachStatementInBlock = each.contents.eachSubStmt
| ikuehne/craeft-hs | lib/Craeft/TypedAST/Pass.hs | gpl-3.0 | 3,326 | 0 | 13 | 963 | 851 | 424 | 427 | 66 | 6 |
module Jason
(
JValue (..),
stringify,
parse,
) where
import Jason.Core
import Jason.Parse
import Jason.Stringify
| TOSPIO/jason | src/Jason.hs | gpl-3.0 | 156 | 0 | 5 | 57 | 35 | 23 | 12 | 8 | 0 |
module DataHand.USB.Descriptors where
import System.USB.Descriptors
import Data.EnumSet hiding (empty)
import Data.ByteString (empty)
deviceDescriptor = DeviceDesc {
deviceUSBSpecReleaseNumber = (0, 0, 0, 2)
, deviceReleaseNumber = (0, 0, 0, 1)
, deviceClass = 0
, deviceSubClass = 0
, deviceProtocol = 0
, deviceMaxPacketSize0 = 32
, deviceVendorId = 0x16C0 -- XXX endswap?
, deviceProductId = 0x047D
, deviceNumConfigs = 1 -- XXX should be calculated based on length of [Config]
, deviceSerialNumberStrIx = Just 0
, deviceManufacturerStrIx = Just 1
, deviceProductStrIx = Just 2
-- FIXME unaccounted for:
-- 18, // bLength
-- 1, // bDescriptorType
}
configDescriptor = ConfigDesc
{
configValue = 1 -- TODO i shouldnt have to manually enum these. constructors should resolve these for me. or atleast not by index?
, configStrIx = Just 0
, configAttribs = fromEnums [SelfPowered, USB1BusPowered] -- XXX check this matches 0xC0 XXX i dont like that i have to remember to put USB1BusPowered everywhere. As I understand it, in usb2.0, this legacy 1.0 flag must always beset.
, configMaxPower = 50 -- TODO is this mA? will giving more power help longer cable + uncooperative port combinations i was encountering with the teensy? stm32 prly takes a good deal more power to begin with...
, configInterfaces = []
, configExtra = empty
}
-- TODO make this all compilable by ghc as a cabal library, using ifdefs to differentiate ghc/jhc if necessary, then build a test harness around it, first as basic exe, then quickcheck etc.
--const uint8_t PROGMEM config1_descriptor[CONFIG1_DESC_SIZE] = {
-- // configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10
-- 9, // bLength;
-- 2, // bDescriptorType;
-- LSB(CONFIG1_DESC_SIZE), // wTotalLength
-- MSB(CONFIG1_DESC_SIZE),
--
-- 2, // bNumInterfaces
-- 1, // bConfigurationValue
-- 0, // iConfiguration
-- 0xC0, // bmAttributes
-- 50, // bMaxPower
--
--
--
-- // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
-- 9, // bLength
-- 4, // bDescriptorType
-- KEYBOARD_INTERFACE, // bInterfaceNumber
-- 0, // bAlternateSetting
-- 1, // bNumEndpoints
-- 0x03, // bInterfaceClass (0x03 = HID)
-- 0x01, // bInterfaceSubClass (0x01 = Boot)
-- 0x01, // bInterfaceProtocol (0x01 = Keyboard)
-- 0, // iInterface
--
--
--
--
-- // HID interface descriptor, HID 1.11 spec, section 6.2.1
-- 9, // bLength
-- 0x21, // bDescriptorType
-- 0x11, 0x01, // bcdHID
-- 0, // bCountryCode
-- 1, // bNumDescriptors
-- 0x22, // bDescriptorType
-- sizeof(keyboard_hid_report_desc), // wDescriptorLength
-- 0,
--
--
--
-- // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
-- 7, // bLength
-- 5, // bDescriptorType
-- KEYBOARD_ENDPOINT | 0x80, // bEndpointAddress
-- 0x03, // bmAttributes (0x03=intr)
-- KEYBOARD_SIZE, 0, // wMaxPacketSize
-- 1, // bInterval
--
--
--
-- // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
-- 9, // bLength
-- 4, // bDescriptorType
-- DEBUG_INTERFACE, // bInterfaceNumber
-- 0, // bAlternateSetting
-- 1, // bNumEndpoints
-- 0x03, // bInterfaceClass (0x03 = HID)
-- 0x00, // bInterfaceSubClass
-- 0x00, // bInterfaceProtocol
-- 0, // iInterface
--
--
--
--
-- // HID interface descriptor, HID 1.11 spec, section 6.2.1
-- 9, // bLength
-- 0x21, // bDescriptorType
-- 0x11, 0x01, // bcdHID
-- 0, // bCountryCode
-- 1, // bNumDescriptors
-- 0x22, // bDescriptorType
-- sizeof(debug_hid_report_desc), // wDescriptorLength
-- 0,
--
--
--
--
-- // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
-- 7, // bLength
-- 5, // bDescriptorType
-- DEBUG_TX_ENDPOINT | 0x80, // bEndpointAddress
-- 0x03, // bmAttributes (0x03=intr)
-- DEBUG_TX_SIZE, 0, // wMaxPacketSize
-- 1 // bInterval
--};
| elitak/hs-datahand | src/DataHand/USB/Descriptors.hs | gpl-3.0 | 5,972 | 0 | 8 | 2,866 | 298 | 223 | 75 | 24 | 1 |
{-# LANGUAGE NoImplicitPrelude, DeriveGeneric, OverloadedStrings, PatternGuards, RecordWildCards #-}
module Lamdu.Expr.Scheme
( Scheme(..), schemeForAll, schemeConstraints, schemeType
, make, mono, any
, alphaEq
) where
import Prelude.Compat hiding (any)
import Control.DeepSeq (NFData(..))
import Control.DeepSeq.Generics (genericRnf)
import Control.Lens (Lens')
import Control.Lens.Operators
import Control.Lens.Tuple
import Control.Monad (guard)
import Data.Binary (Binary)
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Tuple as Tuple
import GHC.Generics (Generic)
import Lamdu.Expr.Constraints (Constraints(..), getTypeVarConstraints, getSumVarConstraints, getProductVarConstraints)
import qualified Lamdu.Expr.Constraints as Constraints
import Lamdu.Expr.Type (Type)
import qualified Lamdu.Expr.Type as T
import qualified Lamdu.Expr.Type.Match as TypeMatch
import Lamdu.Expr.TypeVars (TypeVars(..))
import qualified Lamdu.Expr.TypeVars as TV
import Text.PrettyPrint ((<+>), (<>))
import qualified Text.PrettyPrint as PP
import Text.PrettyPrint.HughesPJClass.Compat (Pretty(..), maybeParens)
data Scheme = Scheme
{ _schemeForAll :: TypeVars
, _schemeConstraints :: Constraints
, _schemeType :: Type
} deriving (Generic, Show)
schemeForAll :: Lens' Scheme TypeVars
schemeForAll f Scheme{..} = f _schemeForAll <&> \_schemeForAll -> Scheme{..}
schemeConstraints :: Lens' Scheme Constraints
schemeConstraints f Scheme{..} = f _schemeConstraints <&> \_schemeConstraints -> Scheme{..}
schemeType :: Lens' Scheme Type
schemeType f Scheme{..} = f _schemeType <&> \_schemeType -> Scheme{..}
-- a Consistent List is an assoc list where each key is never
-- associated to non-eq values
fromConsistentList :: (Ord a, Eq b) => [(a, b)] -> Maybe (Map a b)
fromConsistentList pairs =
pairs
<&> _2 %~ Just
& Map.fromListWith checkConsistency
& sequenceA
where
checkConsistency x y = guard (x == y) >> x
fromDoublyConsistentList :: (Ord a, Ord b) => [(a, b)] -> Maybe (Map a b)
fromDoublyConsistentList pairs =
do
m <- fromConsistentList pairs
_ <- fromConsistentList $ map Tuple.swap $ Map.toList m
return m
alphaEq :: Scheme -> Scheme -> Bool
alphaEq
(Scheme aForall aConstraints aType)
(Scheme bForall bConstraints bType) =
case TypeMatch.matchVars aType bType of
Just (tvPairs, ctvPairs, stvPairs)
| Just tvMap <- fromDoublyConsistentList tvPairs
, Just ctvMap <- fromDoublyConsistentList ctvPairs
, Just stvMap <- fromDoublyConsistentList stvPairs
-> all (checkVarsMatch getSumVarConstraints) (Map.toList stvMap) &&
all (checkVarsMatch getProductVarConstraints) (Map.toList ctvMap) &&
all (checkVarsMatch getTypeVarConstraints) (Map.toList tvMap)
_ -> False
where
checkVarsMatch getTVConstraints (a, b) =
( a `TV.member` aForall ==
b `TV.member` bForall
) &&
( getTVConstraints a aConstraints ==
getTVConstraints b bConstraints
)
make :: Constraints -> Type -> Scheme
make c t =
Scheme freeVars (freeVars `Constraints.intersect` c) t
where
freeVars = TV.free t
mono :: Type -> Scheme
mono x =
Scheme
{ _schemeForAll = mempty
, _schemeConstraints = mempty
, _schemeType = x
}
any :: Scheme
any =
Scheme (TV.singleton a) mempty (T.TVar a)
where
a :: T.TypeVar
a = "a"
instance NFData Scheme where
rnf = genericRnf
instance Pretty Scheme where
pPrintPrec lvl prec (Scheme vars@(TypeVars tv rv sv) constraints t) =
maybeParens (0 < prec) $
forallStr <+> constraintsStr <+> pPrintPrec lvl 0 t
where
forallStr
| mempty == vars = mempty
| otherwise =
PP.text "forall" <+>
PP.hsep (map pPrint (Set.toList tv) ++ map pPrint (Set.toList rv) ++ map pPrint (Set.toList sv)) <>
PP.text "."
constraintsStr
| mempty == constraints = mempty
| otherwise = pPrint constraints <+> PP.text "=>"
instance Binary Scheme
instance TV.Free Scheme where
-- constraints apply to the forAll'd variables so free variables
-- there are irrelevant:
free (Scheme forAll _constraints typ) =
TV.free typ `TV.difference` forAll
| da-x/Algorithm-W-Step-By-Step | Lamdu/Expr/Scheme.hs | gpl-3.0 | 4,664 | 0 | 18 | 1,246 | 1,308 | 714 | 594 | 105 | 2 |
{-
- Lowlevel IRC client library for HircBot.
- Copyright (C) 2008-2019 Madis Janson
-
- This file is part of HircBot.
-
- HircBot is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- HircBot is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with HircBot. If not, see <http://www.gnu.org/licenses/>.
-}
module Hirc (
Irc, showMsg, ircSend, ircCmd, say, say', quitIrc, connectIrc,
escape, ircCatch, liftIO, ircConfig, ircModifyConfig, myIrcNick, splitN,
initEnv
) where
import Control.Arrow
import Control.Concurrent
import Control.Exception as E
import Control.Monad.Reader
import qualified Data.ByteString.Char8 as C
import Data.IORef
import Data.List
import Network.Socket
import System.IO
import System.IO.Error (ioeGetErrorString, ioeGetErrorType, isUserErrorType)
import System.Environment
import System.Mem
import System.Random
data IrcCtx c = IrcCtx { conn :: !Handle, lastPong :: MVar Int,
sync :: MVar (), buffer :: Chan [C.ByteString],
config :: MVar c,
currentNick :: IORef C.ByteString,
isQuit :: IORef Bool }
type Irc c a = ReaderT (IrcCtx c) IO a
type Message = (C.ByteString, String, [C.ByteString])
foreign import ccall "hirc_init_env" initEnv :: IO ()
space = C.singleton ' '
colon = C.singleton ':'
spaceColon = C.pack " :"
showMsg :: Message -> C.ByteString
showMsg (prefix, cmd, arg) =
if C.null prefix then
C.pack cmd `C.append` showArg arg
else
C.concat [colon, prefix, C.pack (' ':cmd), showArg arg]
showArg :: [C.ByteString] -> C.ByteString
showArg args = C.concat (format args)
where format [] = []
format [arg] = [spaceColon, arg]
format (arg : rest) = space : arg : format rest
stripCR :: C.ByteString -> C.ByteString
stripCR str =
if not (C.null str) && C.last str == '\r' then
C.take (C.length str - 1) str
else
str
readMsg :: (MonadFail m) => C.ByteString -> m Message
readMsg message =
if args == [] then fail ("Invalid irc message: " ++ show message)
else return $! (prefix, C.unpack (head args),
tail args ++ [stripCR $ C.drop 1 final])
where (args, final) = first C.words (C.span (/= ':') msg)
(prefix, msg) =
if not (C.null message) && C.head message == ':' then
C.span (/= ' ') (C.tail message)
else
(C.empty, message)
ircSend :: C.ByteString -> String -> [C.ByteString] -> Irc c ()
ircSend prefix cmd arg =
do h <- fmap conn ask
m <- fmap sync ask
liftIO $ withMVar m $ \_ ->
do C.hPutStr h $ showMsg (prefix, cmd, arg)
hPutStr h "\r\n"
hFlush h
ircCmd :: String -> C.ByteString -> Irc c ()
ircCmd cmd what = ircSend C.empty cmd [what]
smartSplit :: Int -> C.ByteString -> (C.ByteString, C.ByteString)
smartSplit at s =
if C.null c || C.null rb' then (a, c)
else (C.reverse rb', C.append (C.reverse ra) c)
where (a, c) = C.splitAt at s
(ra, rb) = C.span (/= ' ') (C.reverse a)
rb' = C.dropWhile (== ' ') rb
splitN :: Int -> C.ByteString -> [C.ByteString]
splitN n = takeWhile (not . C.null) . unfoldr (Just . smartSplit n)
say' :: ([C.ByteString] -> Irc c [C.ByteString])
-> C.ByteString -> C.ByteString -> Irc c ()
say' limit !to text =
do lines <- limit (splitN 400 text)
ctx <- ask
let msg :: C.ByteString -> Irc c ()
msg !line = liftIO $ writeChan (buffer ctx) [to, line]
mapM_ msg lines
say :: C.ByteString -> C.ByteString -> Irc c ()
say to text = say' return to text
quitIrc :: C.ByteString -> Irc c ()
quitIrc quitMsg =
do ask >>= liftIO . (`writeIORef` True) . isQuit
ircCmd "QUIT" quitMsg
fail "QUIT"
alive = C.pack "alive"
pinger :: IrcCtx c -> IO ()
pinger ctx = run
where run = do threadDelay (1000 * 1000 * 120)
runReaderT (ircCmd "PING" alive) ctx
performGC -- just force GC on every 2 minutes
run
pingChecker :: IrcCtx c -> ThreadId -> IO ()
pingChecker ctx th = run
where run = do threadDelay 10000000
n <- modifyMVar (lastPong ctx) update
if n >= 300 then throwTo th (ErrorCall "ping timeout") else run
update x = let y = x + 10 in return $! (y, y)
processIrc :: (Message -> Irc c ()) -> Irc c ()
processIrc handler = do
ctx <- ask
let run p = do line <- liftIO $ C.hGetLine (conn ctx)
msg <- readMsg line
p msg
process _ (_, "PING", param) = ircSend C.empty "PONG" param
process _ (_, "PONG", _) = do liftIO $ swapMVar (lastPong ctx) 0
return ()
process h msg@(_, cmd, !nick:_) | cmd == "NICK" || cmd == "001" =
do liftIO $ writeIORef (currentNick ctx) nick
h msg
process h msg = h msg
wait (_, "376", _) = handler (C.empty, "CONNECTED", []) >> run ready
wait (_, "432", _) = liftIO $ fail "Invalid nick"
wait (_, "433", _) =
do n <- liftIO $ randomRIO (10 :: Int, 9999)
oldnick <- myIrcNick
ircSend C.empty "NICK"
[C.take 8 oldnick `C.append` C.pack (show n)]
run wait
wait msg = process (const (return ())) msg >> run wait
ready msg = process handler msg >> run ready
result = run wait
result
connectIrc :: String -> Int -> String -> (Message -> Irc c ())
-> MVar c -> IO ()
connectIrc host port nick handler cfgRef =
withSocketsDo $ withConnection $ \h -> do
hSetEncoding h latin1
hSetBuffering h (BlockBuffering (Just 4096))
lastPong <- newMVar 0
sync <- newMVar ()
buf <- newChan
nick' <- newIORef cnick
quit <- newIORef False
let ctx = IrcCtx h lastPong sync buf cfgRef nick' quit
writer t = do threadDelay t
msg <- readChan buf
runReaderT (ircSend C.empty "PRIVMSG" msg) ctx
writer (sum (120 : map C.length msg) * 9000)
ex (ErrorCall e) = do putStrLn ("ex: " ++ show e)
fail e
ioEx e | ioeGetErrorString e == "QUIT" = putStrLn "ioEx QUIT"
ioEx e = do q <- readIORef quit
if q then putStrLn "ioEx with quit"
else putStrLn ("ioEx: " ++ show e) >> ioError e
mainThread <- myThreadId
threads <- sequence $ map forkIO [
pinger ctx, pingChecker ctx mainThread, writer 1]
finally (E.catch (E.catch (runReaderT run ctx) ioEx) ex)
(finally (runReaderT (handler (C.empty, "TERMINATE", [])) ctx)
(mapM_ killThread threads))
putStrLn "Normal shutdown."
where withConnection client = do
let hints = defaultHints { addrSocketType = Stream }
addrInfo <- getAddrInfo (Just hints) (Just host) (Just (show port))
let addr = head addrInfo
sock <- E.bracketOnError (socket (addrFamily addr) (addrSocketType addr)
(addrProtocol addr)) close $ \sock -> do
connect sock $ addrAddress addr
return sock
E.bracket (socketToHandle sock ReadWriteMode) hClose client
run = do user <- liftIO $ getEnv "USER"
ircCmd "NICK" cnick
ircSend C.empty "USER"
(map C.pack [user, "localhost", "unknown"] ++ [cnick])
processIrc handler
cnick = C.pack nick
escape :: Irc c (Irc c a -> IO a)
escape =
do ctx <- ask
return $! \action -> runReaderT action ctx
ircCatch :: Irc c a -> (String -> Irc c a) -> Irc c a
ircCatch action handler =
do liftIrc <- escape
let ex (ErrorCall e) = fail e
ioEx e | isUserErrorType (ioeGetErrorType e) =
liftIrc $ handler (ioeGetErrorString e)
ioEx e = ioError e
liftIO $ E.catch (E.catch (liftIrc action) ex) ioEx
ircConfig :: Irc c c
ircConfig = ask >>= liftIO . readMVar . config
ircModifyConfig :: (c -> IO c) -> Irc c ()
ircModifyConfig f = ask >>= liftIO . (`modifyMVar_` f) . config
myIrcNick :: Irc c C.ByteString
myIrcNick = ask >>= liftIO . readIORef . currentNick
| mth/hirc | Hirc.hs | gpl-3.0 | 8,947 | 0 | 21 | 2,880 | 3,130 | 1,566 | 1,564 | -1 | -1 |
module Engine where
import Grid
import Language
import Control.Monad.Reader
--type RoboM a = ReaderT Prog (State [Instr]) a
--runRobo :: RoboM a -> Prog -> a
--runRobo m prog = evalState (runReaderT m prog) $ head prog
step :: Game -> [Instr] -> Reader Prog (Game, [Instr])
step game instrs = do
let (Instr cond act : instrs') = instrs
let color = case getCurrentCell game of
Simple c -> c
_ -> error "error"
case cond of
Always -> doAction game instrs' act
If col -> if color == col then doAction game instrs' act else return (game, instrs')
where doAction g i act =
case act of
TurnLeft -> return (g { gameDir = turnLeft (gameDir g) }, i)
TurnRight -> return (g { gameDir = turnRight (gameDir g) }, i)
GoForward -> return (goForward g, i)
CallF n -> do
prog <- ask
return (g, (prog !! (n-1)) ++ i)
turnLeft :: Direction -> Direction
turnLeft DirUp = DirLeft
turnLeft DirDown = DirRight
turnLeft DirLeft = DirDown
turnLeft DirRight = DirUp
turnRight :: Direction -> Direction
turnRight DirUp = DirRight
turnRight DirDown = DirLeft
turnRight DirLeft = DirUp
turnRight DirRight = DirDown
goForward :: Game -> Game
goForward game = let pos = newPosition (gamePos game) (gameDir game) in
let (game', b) = checkCell game pos in
if b
then game' { gamePos = pos
, gameNbStars = gameNbStars game - 1
}
else game' { gamePos = pos }
where checkCell g p = case getCell g p of
None -> error "fell off the puzzle"
StarOn _ -> (removeStar g p, True)
_ -> (g, False)
newPosition :: Position -> Direction -> Position
newPosition (Pos x y) DirUp = Pos x (y-1)
newPosition (Pos x y) DirDown = Pos x (y+1)
newPosition (Pos x y) DirLeft = Pos (x-1) y
newPosition (Pos x y) DirRight = Pos (x+1) y
| ad0/robozzle-hs | src/Engine.hs | gpl-3.0 | 2,102 | 0 | 18 | 739 | 700 | 359 | 341 | 47 | 7 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.GroupsSettings.Groups.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets one resource by id.
--
-- /See:/ <https://developers.google.com/google-apps/groups-settings/get_started Groups Settings API Reference> for @groupsSettings.groups.get@.
module Network.Google.Resource.GroupsSettings.Groups.Get
(
-- * REST Resource
GroupsGetResource
-- * Creating a Request
, groupsGet
, GroupsGet
-- * Request Lenses
, ggGroupUniqueId
) where
import Network.Google.GroupsSettings.Types
import Network.Google.Prelude
-- | A resource alias for @groupsSettings.groups.get@ method which the
-- 'GroupsGet' request conforms to.
type GroupsGetResource =
"groups" :>
"v1" :>
"groups" :>
Capture "groupUniqueId" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Groups
-- | Gets one resource by id.
--
-- /See:/ 'groupsGet' smart constructor.
newtype GroupsGet = GroupsGet'
{ _ggGroupUniqueId :: Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'GroupsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ggGroupUniqueId'
groupsGet
:: Text -- ^ 'ggGroupUniqueId'
-> GroupsGet
groupsGet pGgGroupUniqueId_ =
GroupsGet'
{ _ggGroupUniqueId = pGgGroupUniqueId_
}
-- | The resource ID
ggGroupUniqueId :: Lens' GroupsGet Text
ggGroupUniqueId
= lens _ggGroupUniqueId
(\ s a -> s{_ggGroupUniqueId = a})
instance GoogleRequest GroupsGet where
type Rs GroupsGet = Groups
type Scopes GroupsGet =
'["https://www.googleapis.com/auth/apps.groups.settings"]
requestClient GroupsGet'{..}
= go _ggGroupUniqueId (Just AltJSON)
groupsSettingsService
where go
= buildClient (Proxy :: Proxy GroupsGetResource)
mempty
| rueshyna/gogol | gogol-groups-settings/gen/Network/Google/Resource/GroupsSettings/Groups/Get.hs | mpl-2.0 | 2,646 | 0 | 12 | 606 | 299 | 184 | 115 | 49 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidPublisher.Systemapks.Variants.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the list of previously created system APK variants.
--
-- /See:/ <https://developers.google.com/android-publisher Google Play Android Developer API Reference> for @androidpublisher.systemapks.variants.list@.
module Network.Google.Resource.AndroidPublisher.Systemapks.Variants.List
(
-- * REST Resource
SystemapksVariantsListResource
-- * Creating a Request
, systemapksVariantsList
, SystemapksVariantsList
-- * Request Lenses
, svlXgafv
, svlVersionCode
, svlUploadProtocol
, svlPackageName
, svlAccessToken
, svlUploadType
, svlCallback
) where
import Network.Google.AndroidPublisher.Types
import Network.Google.Prelude
-- | A resource alias for @androidpublisher.systemapks.variants.list@ method which the
-- 'SystemapksVariantsList' request conforms to.
type SystemapksVariantsListResource =
"androidpublisher" :>
"v3" :>
"applications" :>
Capture "packageName" Text :>
"systemApks" :>
Capture "versionCode" (Textual Int64) :>
"variants" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] SystemAPKsListResponse
-- | Returns the list of previously created system APK variants.
--
-- /See:/ 'systemapksVariantsList' smart constructor.
data SystemapksVariantsList =
SystemapksVariantsList'
{ _svlXgafv :: !(Maybe Xgafv)
, _svlVersionCode :: !(Textual Int64)
, _svlUploadProtocol :: !(Maybe Text)
, _svlPackageName :: !Text
, _svlAccessToken :: !(Maybe Text)
, _svlUploadType :: !(Maybe Text)
, _svlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SystemapksVariantsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'svlXgafv'
--
-- * 'svlVersionCode'
--
-- * 'svlUploadProtocol'
--
-- * 'svlPackageName'
--
-- * 'svlAccessToken'
--
-- * 'svlUploadType'
--
-- * 'svlCallback'
systemapksVariantsList
:: Int64 -- ^ 'svlVersionCode'
-> Text -- ^ 'svlPackageName'
-> SystemapksVariantsList
systemapksVariantsList pSvlVersionCode_ pSvlPackageName_ =
SystemapksVariantsList'
{ _svlXgafv = Nothing
, _svlVersionCode = _Coerce # pSvlVersionCode_
, _svlUploadProtocol = Nothing
, _svlPackageName = pSvlPackageName_
, _svlAccessToken = Nothing
, _svlUploadType = Nothing
, _svlCallback = Nothing
}
-- | V1 error format.
svlXgafv :: Lens' SystemapksVariantsList (Maybe Xgafv)
svlXgafv = lens _svlXgafv (\ s a -> s{_svlXgafv = a})
-- | The version code of the App Bundle.
svlVersionCode :: Lens' SystemapksVariantsList Int64
svlVersionCode
= lens _svlVersionCode
(\ s a -> s{_svlVersionCode = a})
. _Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
svlUploadProtocol :: Lens' SystemapksVariantsList (Maybe Text)
svlUploadProtocol
= lens _svlUploadProtocol
(\ s a -> s{_svlUploadProtocol = a})
-- | Package name of the app.
svlPackageName :: Lens' SystemapksVariantsList Text
svlPackageName
= lens _svlPackageName
(\ s a -> s{_svlPackageName = a})
-- | OAuth access token.
svlAccessToken :: Lens' SystemapksVariantsList (Maybe Text)
svlAccessToken
= lens _svlAccessToken
(\ s a -> s{_svlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
svlUploadType :: Lens' SystemapksVariantsList (Maybe Text)
svlUploadType
= lens _svlUploadType
(\ s a -> s{_svlUploadType = a})
-- | JSONP
svlCallback :: Lens' SystemapksVariantsList (Maybe Text)
svlCallback
= lens _svlCallback (\ s a -> s{_svlCallback = a})
instance GoogleRequest SystemapksVariantsList where
type Rs SystemapksVariantsList =
SystemAPKsListResponse
type Scopes SystemapksVariantsList =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient SystemapksVariantsList'{..}
= go _svlPackageName _svlVersionCode _svlXgafv
_svlUploadProtocol
_svlAccessToken
_svlUploadType
_svlCallback
(Just AltJSON)
androidPublisherService
where go
= buildClient
(Proxy :: Proxy SystemapksVariantsListResource)
mempty
| brendanhay/gogol | gogol-android-publisher/gen/Network/Google/Resource/AndroidPublisher/Systemapks/Variants/List.hs | mpl-2.0 | 5,478 | 0 | 20 | 1,317 | 806 | 467 | 339 | 121 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.S3.CopyObject
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Creates a copy of an object that is already stored in Amazon S3.
--
-- <http://docs.aws.amazon.com/AmazonS3/latest/API/CopyObject.html>
module Network.AWS.S3.CopyObject
(
-- * Request
CopyObject
-- ** Request constructor
, copyObject
-- ** Request lenses
, coACL
, coBucket
, coCacheControl
, coContentDisposition
, coContentEncoding
, coContentLanguage
, coContentType
, coCopySource
, coCopySourceIfMatch
, coCopySourceIfModifiedSince
, coCopySourceIfNoneMatch
, coCopySourceIfUnmodifiedSince
, coCopySourceSSECustomerAlgorithm
, coCopySourceSSECustomerKey
, coCopySourceSSECustomerKeyMD5
, coExpires
, coGrantFullControl
, coGrantRead
, coGrantReadACP
, coGrantWriteACP
, coKey
, coMetadata
, coMetadataDirective
, coSSECustomerAlgorithm
, coSSECustomerKey
, coSSECustomerKeyMD5
, coSSEKMSKeyId
, coServerSideEncryption
, coStorageClass
, coWebsiteRedirectLocation
-- * Response
, CopyObjectResponse
-- ** Response constructor
, copyObjectResponse
-- ** Response lenses
, corCopyObjectResult
, corCopySourceVersionId
, corExpiration
, corSSECustomerAlgorithm
, corSSECustomerKeyMD5
, corSSEKMSKeyId
, corServerSideEncryption
) where
import Network.AWS.Prelude
import Network.AWS.Request.S3
import Network.AWS.S3.Types
import qualified GHC.Exts
data CopyObject = CopyObject
{ _coACL :: Maybe ObjectCannedACL
, _coBucket :: Text
, _coCacheControl :: Maybe Text
, _coContentDisposition :: Maybe Text
, _coContentEncoding :: Maybe Text
, _coContentLanguage :: Maybe Text
, _coContentType :: Maybe Text
, _coCopySource :: Text
, _coCopySourceIfMatch :: Maybe Text
, _coCopySourceIfModifiedSince :: Maybe RFC822
, _coCopySourceIfNoneMatch :: Maybe Text
, _coCopySourceIfUnmodifiedSince :: Maybe RFC822
, _coCopySourceSSECustomerAlgorithm :: Maybe Text
, _coCopySourceSSECustomerKey :: Maybe (Sensitive Text)
, _coCopySourceSSECustomerKeyMD5 :: Maybe Text
, _coExpires :: Maybe RFC822
, _coGrantFullControl :: Maybe Text
, _coGrantRead :: Maybe Text
, _coGrantReadACP :: Maybe Text
, _coGrantWriteACP :: Maybe Text
, _coKey :: Text
, _coMetadata :: Map (CI Text) Text
, _coMetadataDirective :: Maybe MetadataDirective
, _coSSECustomerAlgorithm :: Maybe Text
, _coSSECustomerKey :: Maybe (Sensitive Text)
, _coSSECustomerKeyMD5 :: Maybe Text
, _coSSEKMSKeyId :: Maybe (Sensitive Text)
, _coServerSideEncryption :: Maybe ServerSideEncryption
, _coStorageClass :: Maybe StorageClass
, _coWebsiteRedirectLocation :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'CopyObject' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'coACL' @::@ 'Maybe' 'ObjectCannedACL'
--
-- * 'coBucket' @::@ 'Text'
--
-- * 'coCacheControl' @::@ 'Maybe' 'Text'
--
-- * 'coContentDisposition' @::@ 'Maybe' 'Text'
--
-- * 'coContentEncoding' @::@ 'Maybe' 'Text'
--
-- * 'coContentLanguage' @::@ 'Maybe' 'Text'
--
-- * 'coContentType' @::@ 'Maybe' 'Text'
--
-- * 'coCopySource' @::@ 'Text'
--
-- * 'coCopySourceIfMatch' @::@ 'Maybe' 'Text'
--
-- * 'coCopySourceIfModifiedSince' @::@ 'Maybe' 'UTCTime'
--
-- * 'coCopySourceIfNoneMatch' @::@ 'Maybe' 'Text'
--
-- * 'coCopySourceIfUnmodifiedSince' @::@ 'Maybe' 'UTCTime'
--
-- * 'coCopySourceSSECustomerAlgorithm' @::@ 'Maybe' 'Text'
--
-- * 'coCopySourceSSECustomerKey' @::@ 'Maybe' 'Text'
--
-- * 'coCopySourceSSECustomerKeyMD5' @::@ 'Maybe' 'Text'
--
-- * 'coExpires' @::@ 'Maybe' 'UTCTime'
--
-- * 'coGrantFullControl' @::@ 'Maybe' 'Text'
--
-- * 'coGrantRead' @::@ 'Maybe' 'Text'
--
-- * 'coGrantReadACP' @::@ 'Maybe' 'Text'
--
-- * 'coGrantWriteACP' @::@ 'Maybe' 'Text'
--
-- * 'coKey' @::@ 'Text'
--
-- * 'coMetadata' @::@ 'HashMap' ('CI' 'Text') 'Text'
--
-- * 'coMetadataDirective' @::@ 'Maybe' 'MetadataDirective'
--
-- * 'coSSECustomerAlgorithm' @::@ 'Maybe' 'Text'
--
-- * 'coSSECustomerKey' @::@ 'Maybe' 'Text'
--
-- * 'coSSECustomerKeyMD5' @::@ 'Maybe' 'Text'
--
-- * 'coSSEKMSKeyId' @::@ 'Maybe' 'Text'
--
-- * 'coServerSideEncryption' @::@ 'Maybe' 'ServerSideEncryption'
--
-- * 'coStorageClass' @::@ 'Maybe' 'StorageClass'
--
-- * 'coWebsiteRedirectLocation' @::@ 'Maybe' 'Text'
--
copyObject :: Text -- ^ 'coBucket'
-> Text -- ^ 'coCopySource'
-> Text -- ^ 'coKey'
-> CopyObject
copyObject p1 p2 p3 = CopyObject
{ _coBucket = p1
, _coCopySource = p2
, _coKey = p3
, _coACL = Nothing
, _coCacheControl = Nothing
, _coContentDisposition = Nothing
, _coContentEncoding = Nothing
, _coContentLanguage = Nothing
, _coContentType = Nothing
, _coCopySourceIfMatch = Nothing
, _coCopySourceIfModifiedSince = Nothing
, _coCopySourceIfNoneMatch = Nothing
, _coCopySourceIfUnmodifiedSince = Nothing
, _coExpires = Nothing
, _coGrantFullControl = Nothing
, _coGrantRead = Nothing
, _coGrantReadACP = Nothing
, _coGrantWriteACP = Nothing
, _coMetadata = mempty
, _coMetadataDirective = Nothing
, _coServerSideEncryption = Nothing
, _coStorageClass = Nothing
, _coWebsiteRedirectLocation = Nothing
, _coSSECustomerAlgorithm = Nothing
, _coSSECustomerKey = Nothing
, _coSSECustomerKeyMD5 = Nothing
, _coSSEKMSKeyId = Nothing
, _coCopySourceSSECustomerAlgorithm = Nothing
, _coCopySourceSSECustomerKey = Nothing
, _coCopySourceSSECustomerKeyMD5 = Nothing
}
-- | The canned ACL to apply to the object.
coACL :: Lens' CopyObject (Maybe ObjectCannedACL)
coACL = lens _coACL (\s a -> s { _coACL = a })
coBucket :: Lens' CopyObject Text
coBucket = lens _coBucket (\s a -> s { _coBucket = a })
-- | Specifies caching behavior along the request/reply chain.
coCacheControl :: Lens' CopyObject (Maybe Text)
coCacheControl = lens _coCacheControl (\s a -> s { _coCacheControl = a })
-- | Specifies presentational information for the object.
coContentDisposition :: Lens' CopyObject (Maybe Text)
coContentDisposition =
lens _coContentDisposition (\s a -> s { _coContentDisposition = a })
-- | Specifies what content encodings have been applied to the object and thus
-- what decoding mechanisms must be applied to obtain the media-type referenced
-- by the Content-Type header field.
coContentEncoding :: Lens' CopyObject (Maybe Text)
coContentEncoding =
lens _coContentEncoding (\s a -> s { _coContentEncoding = a })
-- | The language the content is in.
coContentLanguage :: Lens' CopyObject (Maybe Text)
coContentLanguage =
lens _coContentLanguage (\s a -> s { _coContentLanguage = a })
-- | A standard MIME type describing the format of the object data.
coContentType :: Lens' CopyObject (Maybe Text)
coContentType = lens _coContentType (\s a -> s { _coContentType = a })
-- | The name of the source bucket and key name of the source object, separated by
-- a slash (/). Must be URL-encoded.
coCopySource :: Lens' CopyObject Text
coCopySource = lens _coCopySource (\s a -> s { _coCopySource = a })
-- | Copies the object if its entity tag (ETag) matches the specified tag.
coCopySourceIfMatch :: Lens' CopyObject (Maybe Text)
coCopySourceIfMatch =
lens _coCopySourceIfMatch (\s a -> s { _coCopySourceIfMatch = a })
-- | Copies the object if it has been modified since the specified time.
coCopySourceIfModifiedSince :: Lens' CopyObject (Maybe UTCTime)
coCopySourceIfModifiedSince =
lens _coCopySourceIfModifiedSince
(\s a -> s { _coCopySourceIfModifiedSince = a })
. mapping _Time
-- | Copies the object if its entity tag (ETag) is different than the specified
-- ETag.
coCopySourceIfNoneMatch :: Lens' CopyObject (Maybe Text)
coCopySourceIfNoneMatch =
lens _coCopySourceIfNoneMatch (\s a -> s { _coCopySourceIfNoneMatch = a })
-- | Copies the object if it hasn't been modified since the specified time.
coCopySourceIfUnmodifiedSince :: Lens' CopyObject (Maybe UTCTime)
coCopySourceIfUnmodifiedSince =
lens _coCopySourceIfUnmodifiedSince
(\s a -> s { _coCopySourceIfUnmodifiedSince = a })
. mapping _Time
-- | Specifies the algorithm to use when decrypting the source object (e.g.,
-- AES256).
coCopySourceSSECustomerAlgorithm :: Lens' CopyObject (Maybe Text)
coCopySourceSSECustomerAlgorithm =
lens _coCopySourceSSECustomerAlgorithm
(\s a -> s { _coCopySourceSSECustomerAlgorithm = a })
-- | Specifies the customer-provided encryption key for Amazon S3 to use to
-- decrypt the source object. The encryption key provided in this header must be
-- one that was used when the source object was created.
coCopySourceSSECustomerKey :: Lens' CopyObject (Maybe Text)
coCopySourceSSECustomerKey =
lens _coCopySourceSSECustomerKey
(\s a -> s { _coCopySourceSSECustomerKey = a })
. mapping _Sensitive
-- | Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321.
-- Amazon S3 uses this header for a message integrity check to ensure the
-- encryption key was transmitted without error.
coCopySourceSSECustomerKeyMD5 :: Lens' CopyObject (Maybe Text)
coCopySourceSSECustomerKeyMD5 =
lens _coCopySourceSSECustomerKeyMD5
(\s a -> s { _coCopySourceSSECustomerKeyMD5 = a })
-- | The date and time at which the object is no longer cacheable.
coExpires :: Lens' CopyObject (Maybe UTCTime)
coExpires = lens _coExpires (\s a -> s { _coExpires = a }) . mapping _Time
-- | Gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object.
coGrantFullControl :: Lens' CopyObject (Maybe Text)
coGrantFullControl =
lens _coGrantFullControl (\s a -> s { _coGrantFullControl = a })
-- | Allows grantee to read the object data and its metadata.
coGrantRead :: Lens' CopyObject (Maybe Text)
coGrantRead = lens _coGrantRead (\s a -> s { _coGrantRead = a })
-- | Allows grantee to read the object ACL.
coGrantReadACP :: Lens' CopyObject (Maybe Text)
coGrantReadACP = lens _coGrantReadACP (\s a -> s { _coGrantReadACP = a })
-- | Allows grantee to write the ACL for the applicable object.
coGrantWriteACP :: Lens' CopyObject (Maybe Text)
coGrantWriteACP = lens _coGrantWriteACP (\s a -> s { _coGrantWriteACP = a })
coKey :: Lens' CopyObject Text
coKey = lens _coKey (\s a -> s { _coKey = a })
-- | A map of metadata to store with the object in S3.
coMetadata :: Lens' CopyObject (HashMap (CI Text) Text)
coMetadata = lens _coMetadata (\s a -> s { _coMetadata = a }) . _Map
-- | Specifies whether the metadata is copied from the source object or replaced
-- with metadata provided in the request.
coMetadataDirective :: Lens' CopyObject (Maybe MetadataDirective)
coMetadataDirective =
lens _coMetadataDirective (\s a -> s { _coMetadataDirective = a })
-- | Specifies the algorithm to use to when encrypting the object (e.g., AES256,
-- aws:kms).
coSSECustomerAlgorithm :: Lens' CopyObject (Maybe Text)
coSSECustomerAlgorithm =
lens _coSSECustomerAlgorithm (\s a -> s { _coSSECustomerAlgorithm = a })
-- | Specifies the customer-provided encryption key for Amazon S3 to use in
-- encrypting data. This value is used to store the object and then it is
-- discarded; Amazon does not store the encryption key. The key must be
-- appropriate for use with the algorithm specified in the
-- x-amz-server-side-encryption-customer-algorithm header.
coSSECustomerKey :: Lens' CopyObject (Maybe Text)
coSSECustomerKey = lens _coSSECustomerKey (\s a -> s { _coSSECustomerKey = a }) . mapping _Sensitive
-- | Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321.
-- Amazon S3 uses this header for a message integrity check to ensure the
-- encryption key was transmitted without error.
coSSECustomerKeyMD5 :: Lens' CopyObject (Maybe Text)
coSSECustomerKeyMD5 =
lens _coSSECustomerKeyMD5 (\s a -> s { _coSSECustomerKeyMD5 = a })
-- | Specifies the AWS KMS key ID to use for object encryption. All GET and PUT
-- requests for an object protected by AWS KMS will fail if not made via SSL or
-- using SigV4. Documentation on configuring any of the officially supported AWS
-- SDKs and CLI can be found at
-- http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingAWSSDK.html#specify-signature-version
coSSEKMSKeyId :: Lens' CopyObject (Maybe Text)
coSSEKMSKeyId = lens _coSSEKMSKeyId (\s a -> s { _coSSEKMSKeyId = a }) . mapping _Sensitive
-- | The Server-side encryption algorithm used when storing this object in S3
-- (e.g., AES256, aws:kms).
coServerSideEncryption :: Lens' CopyObject (Maybe ServerSideEncryption)
coServerSideEncryption =
lens _coServerSideEncryption (\s a -> s { _coServerSideEncryption = a })
-- | The type of storage to use for the object. Defaults to 'STANDARD'.
coStorageClass :: Lens' CopyObject (Maybe StorageClass)
coStorageClass = lens _coStorageClass (\s a -> s { _coStorageClass = a })
-- | If the bucket is configured as a website, redirects requests for this object
-- to another object in the same bucket or to an external URL. Amazon S3 stores
-- the value of this header in the object metadata.
coWebsiteRedirectLocation :: Lens' CopyObject (Maybe Text)
coWebsiteRedirectLocation =
lens _coWebsiteRedirectLocation
(\s a -> s { _coWebsiteRedirectLocation = a })
data CopyObjectResponse = CopyObjectResponse
{ _corCopyObjectResult :: Maybe CopyObjectResult
, _corCopySourceVersionId :: Maybe Text
, _corExpiration :: Maybe Text
, _corSSECustomerAlgorithm :: Maybe Text
, _corSSECustomerKeyMD5 :: Maybe Text
, _corSSEKMSKeyId :: Maybe (Sensitive Text)
, _corServerSideEncryption :: Maybe ServerSideEncryption
} deriving (Eq, Read, Show)
-- | 'CopyObjectResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'corCopyObjectResult' @::@ 'Maybe' 'CopyObjectResult'
--
-- * 'corCopySourceVersionId' @::@ 'Maybe' 'Text'
--
-- * 'corExpiration' @::@ 'Maybe' 'Text'
--
-- * 'corSSECustomerAlgorithm' @::@ 'Maybe' 'Text'
--
-- * 'corSSECustomerKeyMD5' @::@ 'Maybe' 'Text'
--
-- * 'corSSEKMSKeyId' @::@ 'Maybe' 'Text'
--
-- * 'corServerSideEncryption' @::@ 'Maybe' 'ServerSideEncryption'
--
copyObjectResponse :: CopyObjectResponse
copyObjectResponse = CopyObjectResponse
{ _corCopyObjectResult = Nothing
, _corExpiration = Nothing
, _corCopySourceVersionId = Nothing
, _corServerSideEncryption = Nothing
, _corSSECustomerAlgorithm = Nothing
, _corSSECustomerKeyMD5 = Nothing
, _corSSEKMSKeyId = Nothing
}
corCopyObjectResult :: Lens' CopyObjectResponse (Maybe CopyObjectResult)
corCopyObjectResult =
lens _corCopyObjectResult (\s a -> s { _corCopyObjectResult = a })
corCopySourceVersionId :: Lens' CopyObjectResponse (Maybe Text)
corCopySourceVersionId =
lens _corCopySourceVersionId (\s a -> s { _corCopySourceVersionId = a })
-- | If the object expiration is configured, the response includes this header.
corExpiration :: Lens' CopyObjectResponse (Maybe Text)
corExpiration = lens _corExpiration (\s a -> s { _corExpiration = a })
-- | If server-side encryption with a customer-provided encryption key was
-- requested, the response will include this header confirming the encryption
-- algorithm used.
corSSECustomerAlgorithm :: Lens' CopyObjectResponse (Maybe Text)
corSSECustomerAlgorithm =
lens _corSSECustomerAlgorithm (\s a -> s { _corSSECustomerAlgorithm = a })
-- | If server-side encryption with a customer-provided encryption key was
-- requested, the response will include this header to provide round trip
-- message integrity verification of the customer-provided encryption key.
corSSECustomerKeyMD5 :: Lens' CopyObjectResponse (Maybe Text)
corSSECustomerKeyMD5 =
lens _corSSECustomerKeyMD5 (\s a -> s { _corSSECustomerKeyMD5 = a })
-- | If present, specifies the ID of the AWS Key Management Service (KMS) master
-- encryption key that was used for the object.
corSSEKMSKeyId :: Lens' CopyObjectResponse (Maybe Text)
corSSEKMSKeyId = lens _corSSEKMSKeyId (\s a -> s { _corSSEKMSKeyId = a }) . mapping _Sensitive
-- | The Server-side encryption algorithm used when storing this object in S3
-- (e.g., AES256, aws:kms).
corServerSideEncryption :: Lens' CopyObjectResponse (Maybe ServerSideEncryption)
corServerSideEncryption =
lens _corServerSideEncryption (\s a -> s { _corServerSideEncryption = a })
instance ToPath CopyObject where
toPath CopyObject{..} = mconcat
[ "/"
, toText _coBucket
, "/"
, toText _coKey
]
instance ToQuery CopyObject where
toQuery = const mempty
instance ToHeaders CopyObject where
toHeaders CopyObject{..} = mconcat
[ "x-amz-acl" =: _coACL
, "Cache-Control" =: _coCacheControl
, "Content-Disposition" =: _coContentDisposition
, "Content-Encoding" =: _coContentEncoding
, "Content-Language" =: _coContentLanguage
, "Content-Type" =: _coContentType
, "x-amz-copy-source" =: _coCopySource
, "x-amz-copy-source-if-match" =: _coCopySourceIfMatch
, "x-amz-copy-source-if-modified-since" =: _coCopySourceIfModifiedSince
, "x-amz-copy-source-if-none-match" =: _coCopySourceIfNoneMatch
, "x-amz-copy-source-if-unmodified-since" =: _coCopySourceIfUnmodifiedSince
, "Expires" =: _coExpires
, "x-amz-grant-full-control" =: _coGrantFullControl
, "x-amz-grant-read" =: _coGrantRead
, "x-amz-grant-read-acp" =: _coGrantReadACP
, "x-amz-grant-write-acp" =: _coGrantWriteACP
, "x-amz-meta-" =: _coMetadata
, "x-amz-metadata-directive" =: _coMetadataDirective
, "x-amz-server-side-encryption" =: _coServerSideEncryption
, "x-amz-storage-class" =: _coStorageClass
, "x-amz-website-redirect-location" =: _coWebsiteRedirectLocation
, "x-amz-server-side-encryption-customer-algorithm" =: _coSSECustomerAlgorithm
, "x-amz-server-side-encryption-customer-key" =: _coSSECustomerKey
, "x-amz-server-side-encryption-customer-key-MD5" =: _coSSECustomerKeyMD5
, "x-amz-server-side-encryption-aws-kms-key-id" =: _coSSEKMSKeyId
, "x-amz-copy-source-server-side-encryption-customer-algorithm" =: _coCopySourceSSECustomerAlgorithm
, "x-amz-copy-source-server-side-encryption-customer-key" =: _coCopySourceSSECustomerKey
, "x-amz-copy-source-server-side-encryption-customer-key-MD5" =: _coCopySourceSSECustomerKeyMD5
]
instance ToXMLRoot CopyObject where
toXMLRoot = const (namespaced ns "CopyObject" [])
instance ToXML CopyObject
instance AWSRequest CopyObject where
type Sv CopyObject = S3
type Rs CopyObject = CopyObjectResponse
request = put
response = xmlHeaderResponse $ \h x -> CopyObjectResponse
<$> x .@? "CopyObjectResult"
<*> h ~:? "x-amz-copy-source-version-id"
<*> h ~:? "x-amz-expiration"
<*> h ~:? "x-amz-server-side-encryption-customer-algorithm"
<*> h ~:? "x-amz-server-side-encryption-customer-key-MD5"
<*> h ~:? "x-amz-server-side-encryption-aws-kms-key-id"
<*> h ~:? "x-amz-server-side-encryption"
| dysinger/amazonka | amazonka-s3/gen/Network/AWS/S3/CopyObject.hs | mpl-2.0 | 21,998 | 0 | 21 | 5,649 | 3,095 | 1,811 | 1,284 | 299 | 1 |
module HelperSequences.A007814 (a007814) where
a007814 n = last $ takeWhile (\a -> n `mod` 2^a == 0) [0..]
| peterokagey/haskellOEIS | src/HelperSequences/A007814.hs | apache-2.0 | 108 | 0 | 11 | 19 | 53 | 30 | 23 | 2 | 1 |
-- Copyright 2016 TensorFlow authors.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-} -- For Fetchable (TensorExpr a)
module TensorFlow.Nodes where
import Control.Applicative (liftA2, liftA3)
import Data.Functor.Identity (Identity)
import Data.Map.Strict (Map)
import Data.Set (Set)
import Data.Text (Text)
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import TensorFlow.Build
import TensorFlow.Output
import TensorFlow.Tensor
import TensorFlow.Types
import qualified TensorFlow.Internal.FFI as FFI
-- | Types that contain ops which can be run.
class Nodes t where
getNodes :: t -> Build (Set NodeName)
-- | Types that tensor representations (e.g. 'Tensor', 'ControlNode') can be
-- fetched into.
--
-- Includes collections of tensors (e.g. tuples).
class Nodes t => Fetchable t a where
getFetch :: t -> Build (Fetch a)
-- | Fetch action. Keeps track of what needs to be fetched and how to decode
-- the fetched data.
data Fetch a = Fetch
{ -- | Nodes to fetch
fetches :: Set Text
-- | Function to create an 'a' from the fetched data.
, fetchRestore :: Map Text FFI.TensorData -> a
}
instance Functor Fetch where
fmap f (Fetch fetch restore) = Fetch fetch (f . restore)
instance Applicative Fetch where
pure x = Fetch Set.empty (const x)
Fetch fetch restore <*> Fetch fetch' restore' =
Fetch (fetch <> fetch') (restore <*> restore')
nodesUnion :: (Monoid b, Traversable t, Applicative f) => t (f b) -> f b
nodesUnion = fmap (foldMap id) . sequenceA
instance (Nodes t1, Nodes t2) => Nodes (t1, t2) where
getNodes (x, y) = nodesUnion [getNodes x, getNodes y]
instance (Nodes t1, Nodes t2, Nodes t3) => Nodes (t1, t2, t3) where
getNodes (x, y, z) = nodesUnion [getNodes x, getNodes y, getNodes z]
instance (Fetchable t1 a1, Fetchable t2 a2) => Fetchable (t1, t2) (a1, a2) where
getFetch (x, y) = liftA2 (,) <$> getFetch x <*> getFetch y
instance (Fetchable t1 a1, Fetchable t2 a2, Fetchable t3 a3)
=> Fetchable (t1, t2, t3) (a1, a2, a3) where
getFetch (x, y, z) =
liftA3 (,,) <$> getFetch x <*> getFetch y <*> getFetch z
instance Nodes t => Nodes [t] where
getNodes = nodesUnion . map getNodes
instance Fetchable t a => Fetchable [t] [a] where
getFetch ts = sequenceA <$> mapM getFetch ts
instance Nodes t => Nodes (Maybe t) where
getNodes = nodesUnion . fmap getNodes
instance Fetchable t a => Fetchable (Maybe t) (Maybe a) where
getFetch = fmap sequenceA . mapM getFetch
instance Nodes ControlNode where
getNodes (ControlNode o) = pure $ Set.singleton o
-- We use the constraint @(a ~ ())@ to help with type inference. For example,
-- if @t :: ControlNode@, then this constraint ensures that @run t :: Session
-- ()@. If we used @instance Fetchable ControlNode ()@ instead, then that
-- expression would be ambiguous without explicitly specifying the return type.
instance a ~ () => Fetchable ControlNode a where
getFetch _ = return $ pure ()
instance Nodes (ListOf f '[]) where
getNodes _ = return Set.empty
instance (Nodes (f a), Nodes (ListOf f as)) => Nodes (ListOf f (a ': as)) where
getNodes (x :/ xs) = liftA2 Set.union (getNodes x) (getNodes xs)
instance l ~ List '[] => Fetchable (ListOf f '[]) l where
getFetch _ = return $ pure Nil
instance (Fetchable (f t) a, Fetchable (ListOf f ts) (List as), i ~ Identity)
=> Fetchable (ListOf f (t ': ts)) (ListOf i (a ': as)) where
getFetch (x :/ xs) = liftA2 (\y ys -> y /:/ ys) <$> getFetch x <*> getFetch xs
instance Nodes (Tensor v a) where
getNodes (Tensor o) = Set.singleton . outputNodeName <$> toBuild o
fetchTensorVector :: forall a v . (TensorType a)
=> Tensor v a -> Build (Fetch (TensorData a))
fetchTensorVector (Tensor o) = do
outputName <- encodeOutput <$> toBuild o
pure $ Fetch (Set.singleton outputName) $ \tensors ->
let tensorData = tensors Map.! outputName
expectedType = tensorType (undefined :: a)
actualType = FFI.tensorDataType tensorData
badTypeError = error $ "Bad tensor type: expected "
++ show expectedType
++ ", got "
++ show actualType
in if expectedType /= actualType
then badTypeError
else TensorData tensorData
-- The constraint "a ~ a'" means that the input/output of fetch can constrain
-- the TensorType of each other.
instance (TensorType a, a ~ a') => Fetchable (Tensor v a) (TensorData a') where
getFetch = fetchTensorVector
instance (TensorType a, TensorDataType s a, a ~ a') => Fetchable (Tensor v a) (s a') where
getFetch t = fmap decodeTensorData <$> fetchTensorVector t
| tensorflow/haskell | tensorflow/src/TensorFlow/Nodes.hs | apache-2.0 | 5,616 | 0 | 16 | 1,281 | 1,591 | 839 | 752 | 89 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Main(main) where
import Data.Int
import DNA
import DDP
import DDP_Slice
----------------------------------------------------------------
-- Distributed dot product
--
-- Note that actors which do not spawn actors on other nodes do not
-- receive CAD.
----------------------------------------------------------------
-- | Actor for calculating dot product
ddpDotProduct :: Actor Int64 Double
ddpDotProduct = actor $ \size -> do
-- Find how into how many chunks we need to split vector
let nChunk = fromIntegral $ size `div` (100*1000*1000)
-- Chunk & send out
res <- selectMany (Frac 1) (NNodes 1) [UseLocal]
shell <- startGroupN res Failout nChunk $(mkStaticClosure 'ddpProductSlice)
sendParam (Slice 0 size) shell
-- Collect results
partials <- delayGroup shell
x <- duration "collecting vectors" $ gather partials (+) 0
return x
main :: IO ()
main = dnaRun rtable $ do
-- Size of vectors. We can pre-compute the expected result.
--
-- > + 100e4 doubles per node/per run
-- > + 4 runs per/node
-- > + 4 nodes
let n = 1600*1000*1000
expected = fromIntegral n*(fromIntegral n-1)/2 * 0.1
-- Run it
b <- eval ddpDotProduct n
liftIO $ putStrLn $ concat
[ "RESULT: ", show b
, " EXPECTED: ", show expected
, if b == expected then " -- ok" else " -- WRONG!"
]
where
rtable = DDP.__remoteTable
. DDP_Slice.__remoteTable
| SKA-ScienceDataProcessor/RC | MS2/dna-programs/ddp-in-memory-large.hs | apache-2.0 | 1,497 | 0 | 16 | 362 | 345 | 182 | 163 | 26 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.