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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
import Test.Hspec
import qualified Jenkins.TypesSpec as TypesSpec
main :: IO ()
main = hspec TypesSpec.test
| afiore/jenkins-tty.hs | test/Suite.hs | mit | 109 | 0 | 6 | 16 | 34 | 19 | 15 | 4 | 1 |
{-# LANGUAGE BangPatterns #-}
module LMisc (zipp, zipp4, tokens, tokens', in2out, rDoubleS
, findWithRemainder ,differentiateBy,findWithAdjs
, takeFirst, mtone3, subs, subsN, choose, force
,ascending,nppP
, allPieces, nPieces, adjustMatrix , myMin
, nPieces2,nPiecesPOpt, trendLine , predict, nPiecesP
, butLastElm,maintainBy,myTake,maintainBy',sumBy,similarBy
, fillZeroes,fillZeroes_aux, takeFirstM, oSubs
, zipp3, myMin',zipMaybe,allPositiveSlopes , findIndexesPresent, maintainByLen
, findCuts,mkIntervals,getOppFuns,printElm,printElmChr,predsFromLP
, manyInvNS,findGrps
, lastN, mapSnd
)
where
--- some miscellaneous list operations
import qualified Control.Parallel.Strategies as St ---(parList, rseq)
import IO
import Data.List (transpose, delete,findIndex,foldl',nub,maximumBy,minimumBy,find)
import Data.Ord (comparing)
import Data.Maybe (listToMaybe)
import Control.Parallel (par, pseq)
import Numeric.LinearAlgebra (fromList, toList, join, Vector, foldVector,takesV,dim,(@>),mapVector )
import Numeric.GSL.Statistics (mean,stddev)
----------------------------------------------------------------------------------------------------
--- create pairs of consecutive members of a lists
----------------------------------------------------------------------------------------------------
zipp :: [a] ->[(a,a)]
zipp (x:y:xs) = (x,y):zipp (y:xs)
zipp _ = []
--
unZipp :: [(a,a)] -> [a]
unZipp [(a,b)] = [a,b]
unZipp ((a,_) : xs) = a : unZipp xs
unZipp _ = []
--
zipp3 :: [a] -> [(a,a,a)]
zipp3 (a:b:c:xs) = (a,b,c): zipp3 (b:c:xs)
zipp3 _ = []
--
zipp4 :: [a] -> [(a,a,a,a)]
zipp4 (a:b:c:d:xs) = (a,b,c,d): zipp4 (c:d:xs)
zipp4 _ = []
------------------------------------------------------------
-- --
zipMaybe :: [a] ->[b] ->[(Maybe a, Maybe b)]
zipMaybe [] [] = []
zipMaybe (a:as) [] = (Just a, Nothing) : zipMaybe as []
zipMaybe [] (b:bs) = (Nothing, Just b) : zipMaybe [] bs
zipMaybe (a:as) (b:bs) = (Just a, Just b) : zipMaybe as bs
------------------------------------------------------------
--mapSnd
mapSnd :: ([a],b) -> [(a,b)]
mapSnd (xs,y) = St.parMap St.rseq (\a -> (a,y)) xs
-- find the number of unique elements in a list
num_unique [] = 0
num_unique (a:xs)| null ass = num_unique rest
| otherwise = 1 + num_unique rest
where (ass, rest) = span (==a) xs
---- LastN : the dual of take n
lastN :: Int -> [a] -> [a]
lastN n xs = drop (m-n) xs
where m = length xs
-- myTake - a strict version of take
myTake _ [] = []
myTake 0 _ = []
myTake n (x:xs) = ys `seq` (x:ys)
where ys = myTake (n-1) xs
--- summing using a function
sumBy :: Num a => (b -> a) -> [b] -> a
sumBy f = foldl' (\b a -> b + f a) 0
--- force a list down to the last term
force :: [a] -> ()
force xs = go xs `pseq` ()
where go (_:xs) = go xs
go [] = 1
--- finds an element of a list and returns the element along with
-- the remainder of the list
findWithRemainder :: (a -> Bool) -> [a] -> (Maybe a, [a])
findWithRemainder f [] = (Nothing, [])
findWithRemainder f (x:xs)
| f x = (Just x , xs)
| otherwise =
case findWithRemainder f xs of
(mf, ys) -> (mf , x : ys)
--- finds an element of a list and returns the element along
-- with other elemens adjacent to it
findWithAdjs :: (a -> Bool) -> [a] -> ([a] , Maybe a, [a])
findWithAdjs f [] = ([] , Nothing, [])
findWithAdjs f (x:xs)
| f x = ([] , Just x , xs)
| otherwise =
case findWithAdjs f xs of
(fs, mf, ys) -> (x: fs , mf , ys)
-- differentiateBy f xs ys: returns all elements in ys where
-- that are similar, after an application of f, to xs (in the first argument)
--- along with the remaining elemets of ys (in the second argument)
differentiateBy :: Eq a => (a -> a) -> [a] -> [a] -> ([a],[a])
differentiateBy f [] ys = ([],ys)
differentiateBy f _ [] = ([],[])
differentiateBy f (x:xs) ys =
case findWithRemainder ((== x) . f) ys of
(Nothing , zs) -> differentiateBy f xs zs
(Just k, zs) -> (k : ps , qs)
where (ps, qs) = differentiateBy f xs zs
---
--- findIndexesPresent f xs ys: finds the indexes of elements xs
--- where f i is in ys
findIndexesPresent :: Eq a => (b -> a) -> [b] -> [a] -> [Int]
findIndexesPresent f [] _ = []
findIndexesPresent f _ [] = []
findIndexesPresent f (x:xs) ys =
case findIndex (== f x) ys of
Nothing -> findIndexesPresent f xs ys
Just k -> k : findIndexesPresent f xs ys
--}
--- repeatedly preforms differentiateBy over a list of elements
differentiateList :: Eq a => (a -> a) -> [[a]] -> [a] -> [[a]]
differentiateList f [] _ = []
differentiateList f (xs:xss) ys
| null zs = differentiateList f xss rest
| otherwise = zs : differentiateList f xss rest
where (zs, rest) = differentiateBy f xs ys
----------------------------------------------------------------------------------------------------
-- monotone decreasing lists
----------------------------------------------------------------------------------------------------
mtone3 :: Ord a => [a] -> [a]
mtone3 (w:x:y:z:zs) | w >= x && x >= y && y >= z = y: mtone3 (z:zs)
| otherwise = mtone3 (z:zs)
mtone3 _ = []
--
----------- minimum function that does not crash -------------------
myMin :: (Ord a) => [a] -> Maybe a
myMin [] = Nothing
myMin xs = Just (minimum xs)
-- need to write this function
myMin' :: (Ord a) => [(a,b)] -> (a,b)
myMin' [] = error "minimum empty list"
myMin' ((a,b):xs) = foldl mF (a,b) xs
where mF (x,y) (p,q) = if x < p then (x,y) else (p,q)
----------------------------------------------------------------------------------------------------
-- | returns a list with the penultimate element removed along with the element
-- | that was removed. Only works for list of lenght greater than 2.
butLastElm :: [a] -> Maybe ([a],a)
butLastElm [x,y,z] = Just ([x,z],y)
butLastElm (x:xs) = case butLastElm xs of
Nothing -> Nothing
Just (ys,k) -> Just (x:ys, k)
butLastElm _ = Nothing
-- choose all sublists
subs :: [a] -> [[a]]
subs [] = [[]]
subs (x:xs) = ys ++ map (x:) ys
where
ys = subs xs
---
subsN _ [] = [[]]
subsN n (x:xs) = [ks | ks <- map (x:) ys ++ ys , length ks == n]
where
ys = subsN n xs
--- choose all possible sublists of xs with length less or equal to xs
choose xs n = [ x | x <- subs xs , length x == n]
-- nSegs :: [a] -> > [[a]]
nSegs _ [] = []
nSegs 0 xs = [xs]
nSegs n xs@(_:ys) | n >= length xs = [xs]
| otherwise = take n xs : nSegs n ys
-- determine whether two lists have the same element
sameElements :: Eq a => [a] -> [a] -> Bool
sameElements [] [] = True
sameElements (x:xs) ys = sameElements xs (delete x ys)
sameElements _ _ = False
----------------------------------------------------------------------------------------------------
-- COMPUTING THE ADJUSTED MATRIX
----------------------------------------------------------------------------------------------------
-- ordered sub lists. The ordering is subject to the aprori arrangement of the list
oSubs :: [a] -> [[a]]
oSubs [] = []
oSubs xs@(_:xs') = [take i xs | i <- [1..length xs]] ++ oSubs xs'
-- return all possible pieces, ignoring pieces that treat individual points
-- as a line segment. I may have to add the possibility to treat at least the
-- final point as a piece when annalysing segments
allPieces :: Eq a => [a] -> [[[a]]]
allPieces xs = [ ys | let n = length xs, i <- [1.. n], ys <- allOperms_aux i n xs]
where allOperms_aux _ _ [] = []
allOperms_aux n m xs | n == 1 = [[xs]]
| n == 2 = [[ys,zs] | i <- [1 .. length xs],
let (ys,zs) = splitAt i xs, not (null ys),
length zs > 1, length ys > 1] -- ]
| otherwise = [(ns:ps) | i <- [1.. m],
let (ns, ms) = splitAt i xs,
let mm = length ms, length ns > 1,
ps <- allOperms_aux (n-1) mm ms]
-- | nPieces : all possible adjacent elements from n cuts of the list, excluding empty subslists
nPieces :: Eq a => Int -> [a] -> [[[a]]]
nPieces n xs
| n == 0 = [[xs]]
| otherwise = [(ns:ps) | i <- [1.. (length xs - 1)],
let (ns, ms) = splitAt i xs, not $ null ns,
ps <- nPieces (n-1) ms, all (not . null) ps]
---
-- | nPieces : all possible adjacent elements from n cuts of the list, excluding empty subslists
nPiecesF :: (Eq a, Ord b) => ([a] -> b) -> Int -> [a] -> [[[a]]]
nPiecesF f n xs
| n == 0 = [[xs]]
| otherwise = [ (ns:ps) | i <- [2.. 5],
let (ns, ms) = splitAt i xs, not $ null ns,
ps <- (nPiecesF f (n-1) ms)]
-- all (not . null) ps]
{-# INLINE nppP #-}
---- towards a more efficient version of the npieces function
---- to be continued
nppP :: Int -> Int -> [a] -> [([[a]],[Int])]
nppP 0 lim xs = [([xs],[])]
nppP 1 lim xs = nppP' lim (length xs - lim + 1) xs --
nppP m lim xs = [(ns : ps, i : ks) | i <- [lim .. (length xs - lim)]
, let (ns, ms) = splitAt i xs
-- now recursively build-up the tail with sublists longer than lim
, (ps,ks) <- nppP (m-1) lim ms
, all ( < 10) (i : ks) ]
{-# INLINE nppP' #-}
nppP' :: Int -> Int -> [a] -> [([[a]],[Int])]
nppP' _ _ [] = []
nppP' st en xs
| st >= en = []
| null back = [([front], [st])] -- ] : nppP' (st + 1) en xs
| otherwise = ([front,back], [st,length back]) : nppP' (st + 1) en xs
where
!ln = length front
(front,back) = splitAt st xs
----------------------------------------------------------------------------------------------------
-- | nPieces: all possible adjacent adjacent elements from n cuts of the list built from
-- | least lim elements, keeping track of the occurrence of cuts
{-# INLINE nPiecesP #-}
nPiecesP :: Int -> -- ^ The number of splits for the lsit
Int -> -- ^ The minimum length of the shortest piece
Maybe Int -> -- ^ The maximum length of the longest piece (bar the first bit)
[a] -> -- ^ The list to split up
[([[a]],[Int])]
nPiecesP m lim mLn xs
| null xs = []
| m == 0 = [([xs],[])]
-- | length xs <= m = [([xs],[])]
| otherwise = [(ns:ps, i : ks) |
i <- [lim .. (length xs - lim)]
-- get the first element, making sure it is longer than lim
, let (ns, ms) = splitAt i xs -- length ns >= lim,
-- now recursively build-up the tail with sublists longer than lim
, (ps,ks) <- nPP (m-1) lim mLn ms
, let pss = ns:ps
, maybe (all ((>= lim) . length) pss) (\n -> maxLn n pss) mLn
]
where
nPP mn lm mlN ys = let npp = nPiecesP mn lm mlN ys in npp `pseq` npp
maxLn mx = all (\xs -> let lm = length xs in (lm >= lim ) && (lm <= mx))
----------------------------------------------------------------------------------------------------
{-# INLINE nPiecesPF #-}
nPiecesPF :: (Ord a , Num a) => Int -> -- ^ The number of splits for the lsit
Int -> -- ^ The minimum length of the shortest piece
(a -> a) ->
Maybe Int -> -- ^ The maximum length of the longest piece (bar the first bit)
[a] -> -- ^ The list to split up
[([[a]],[Int])]
nPiecesPF m lim f mLn xs -- = maintainBy' (sumBy (sumBy f) . fst) (Just 6) . nPiecesP m lim mLn
| null xs = []
| m == 0 = [([xs],[])]
-- | length xs <= m = [([xs],[])]
| otherwise = [(pss, i : ks) |
i <- [lim .. (length xs - lim)]
-- get the first element, making sure it is longer than lim
, let (ns, ms) = splitAt i xs -- length ns >= lim,
-- now recursively build-up the tail with sublists longer than lim
, (ps,ks) <- take 2 $ nPP (m-1) lim mLn ms
, let pss = (ns:ps)
, maybe (all ((>= lim) . length) pss) (\n -> maxLn n pss) mLn
]
where
nPP mn lm mlN ys = let npp = nPiecesPF mn lm f mlN ys in npp `pseq` npp
maxLn mx = all (\xs -> let lm = length xs in (lm >= lim ) && (lm <= mx))
----------------------------------------------------------------------------------------------------}
nPiecesPOpt :: Int -> -- ^ The minimum length of the shortest piece
-- Int -> -- ^ The maximum length of the longest piece
[a] -> -- ^ The list to split up
[([[a]],[Int])]
nPiecesPOpt lim xs =
[(ns:ps, i : ks) | i <- [lim .. (length xs - lim)],
-- get the first element, making sure it is longer than lim
let (ns, ms) = splitAt i xs , length ns >= lim,
-- now build-up the tail with sublists longer than lim
(ps,ks) <- splits lim lim (length xs - lim) ms, all ((>= lim) . length) ps]
where
splits :: Int -> Int -> Int -> [a] -> [([[a]], [Int])]
splits _ _ _ [] = []
splits mn m n xs
| length xs <= n + m = [ ([front,back],[m])]
| m >= n = splits mn mn n xs
| otherwise =
case splits mn (m+1) n back of
[] -> [([front],[m]) ]
((ps,zs) :rest) -> (front : ps, m : zs) : rest
where
(front, back) = splitAt m xs
--- maintain elements of a list that are valid by
maintainBy' :: (Eq a , Ord b ) => (a -> b) -> Maybe Int -> [a] -> [a]
maintainBy' f mb = maybe (($!) (maintainBy f)) (\n -> myTake n . maintainBy f) mb
maintainBy :: (Eq a , Ord b ) => (a -> b) -> [a] -> [a]
maintainBy _ [] = []
maintainBy f (x:xs) = maintainBy_aux f x [] xs
where
maintainBy_aux :: (Eq a , Ord b) => (a -> b) -> a -> [a] -> [a] -> [a]
maintainBy_aux _ _ acc [] = acc
maintainBy_aux f a acc (y:ys)
| f a < f y = maintainBy_aux f a (a <:> acc) ys
| otherwise = maintainBy_aux f y (y <:> acc) ys
where
(<:>) :: Eq c => c -> [c] -> [c]
(<:>) x [] = [x]
(<:>) x ys@(y:_)
| x == y = ys
| otherwise = x : ys
--- filter out "poor values" inroder to preserve a list of length n
maintainByLen :: (Eq a , Ord b) => Int -> (a -> b) -> [a] -> [a]
maintainByLen n f xs
| n < length xs = maintainBy' f (Just n) xs -- xs
| otherwise = xs -- maintainBy' f (Just n) xs
----------------------------------------------------------------------------------------------------
-- return the first elements of a list when ther are all similiar by a given predicate
similarBy :: (a -> a -> Bool) -> [a] -> Maybe a
-- similarBy p [a] = Just a
similarBy p [a,b]
| p a b = Just a
| otherwise = Nothing
similarBy p (a:b:c:xs)
| p a b && p b c = Just a
| otherwise = similarBy p (b:c:xs)
similarBy p _ = Nothing
----------------------------------------------------------------------------------------------------
-- nPieces2: Gets all possible combinations of adjacent n pieces, without single
-- pieces at the end. Suitable for MML2DS
nPieces2 :: Eq a => Int -> Int -> Int -> [a] -> [[[a]]]
nPieces2 n m len xs | n == 0 = [[xs]]
| n == 1 = [[ys,zs] | i <- [3 .. len],
let (ys,zs) = splitAt i xs, -- not (null zs),
length zs > 1, length zs <= m, length ys <= m]
| otherwise = [(ns:ps) | i <- [3.. len],
let (ns, ms) = splitAt i xs,
length ms > 1, length ns <= m, -- length ms <= m,
ps <- nPieces2 (n-1) m (len - i) ms]
--- filling zeroes to align the pieces -------------------------------------------------------------
fillZeroes_aux :: Num a => Int -> Int -> Int -> [[a]] -> [[a]]
fillZeroes_aux _ _ _ [] = []
fillZeroes_aux n m i (xs:xss)
| null xss && m == 0 = [zeros (n - lxs) ++ xs]
| i == 1 = inKtor : appZros : fillZeroes_aux n ml (i+1) xss
| otherwise = inKtor : zerosXz : fillZeroes_aux n ml (i+1) xss
where
lxs = length xs
ml = m + lxs
zeros k = [0 | _ <- [1..k]]
nmxs = n - ml
appZros = (xs ++ zeros (n - lxs))
zerosXz = (zeros m ++ xs ++ zeros nmxs)
inKtor = (zeros m ++ [1 | _ <- xs] ++ zeros nmxs)
fillZeroes :: Num a => [[a]] -> [[a]]
fillZeroes xs = fillZeroes_aux (length xs) 0 1 xs
-- Finally, adjusting the matrix. This is achieved by removing the
-- last indicator vector and adding it to the first indicator vector.
-- This operation is only performed for lists of length greater than 2.
adjustMatrix :: Num a => [[a]] -> [[a]]
adjustMatrix xss = case butLastElm xss of
Nothing -> xss
Just ((ys:yss), zs) -> (sub ys zs) : yss
where sub ps qs = zipWith (-) ps qs
--- END OF ADJUSTED MATRIX DEFINITIONS
---------------------------------------------------------------------------------------------------
findCuts :: Ord a => [a] -> [[a]]
findCuts xs
| null xs = []
| null asenBlock = [xs]
| otherwise = front : findCuts rest
where
asenBlock = [(ps,qs) | (ps,qs) <- firstNs 1 xs, ascDes ps ]
(front, rest) = last asenBlock
--
ascDes xs = ascending xs || desending xs
--
firstNs :: Int -> [a] -> [([a],[a])]
firstNs n xs
| n > length xs = []
| otherwise = (ys, zs) : firstNs (n+1) xs
where
(ys, zs) = splitAt n xs
---- remove increasing cuts
remIncrCuts :: Bool -> [[Double]] -> [[Double]]
remIncrCuts positive xs
| not positive = xs
| 1 >= length xs = xs
| otherwise = (unZipp . map remIncrCuts_aux . zipp) xs
where
remIncrCuts_aux :: ([Double],[Double]) -> ([Double],[Double])
remIncrCuts_aux (xs,ys)
| any null [xs,ys] = (xs,ys)
| last xs < head ys =
case (find (/= 0) (reverse xs)) of
Nothing -> (xs, ys)
Just k -> (xs , (mkAscending . map (minusUntil k)) ys)
| otherwise = (xs, ys)
--- remove increasing cuts
minusUntil :: Double -> Double -> Double
minusUntil n m
-- | n == 0 = minusUntil (n + 0.5) m
| m <= n = m
| otherwise = minusUntil n (m - (n + 0.0001))
-- make a set of points ascending
mkAscending :: [Double] -> [Double]
mkAscending (a : b : xs)
| a <= b = a : mkAscending ( b : xs)
| otherwise = b : (b + 0.12) : mkAscending (map (+ b) xs)
mkAscending xs = xs
-- says if the elements of a list are in ascending
ascending_aux ((a,b,c,d):xs)
| a <= b && b <= c && c <= d = ascending_aux xs
| otherwise = False
ascending_aux _ = True -- monotone True
--ascending4 = ascending_aux . zipp4
--desending4 = not . ascending4 -- all (uncurry (>)) . zipp
ascending :: Ord a => [a ] -> Bool
ascending = all (uncurry (<=)) . zipp -- monotone True
--
desending :: Ord a => [a ] -> Bool
desending = all (uncurry (>)) . zipp
--desending' = all (uncurry (>=)) . zipp
------------------------------------------------------------------------------------
-- FUNCTIONS FOR GRAPHING
------------------------------------------------------------------------------------
-- mkIntervals : takes a lsit of known predictions and a list of the
-- frequency of cuts and produces a lsits of predictions relating to
-- each cut, along with the length of the list
mkIntervals :: [a] -> [Int] -> [([a],Int)]
mkIntervals [] _ = []
mkIntervals predts [] = [(predts, length predts)]
mkIntervals predts (n:ns) = (front,length front): mkIntervals rest ns
where (front,rest) = splitAt n predts
---------------
-- just like mkIntervals but considers a minimum number of points
mkIntervals1 :: [a] -> [Int] -> [[a]]
mkIntervals1 [] _ = []
mkIntervals1 predts [] = [predts]
mkIntervals1 predts (n:ns) = front : mkIntervals1 rest ns
-- | length rest < 4 = front : [rest]
-- | otherwise =
where (front,rest) = splitAt n predts
-- calculates that function defined over the entire range
trendLine :: [Double] -> [Int] -> Double -> Double
trendLine ys = getFun . mkIntervals ys
where
getFun xs = getFun' xs 1
f = fromIntegral
getFun' [(xs,_)] k x = fun xs k x
getFun' ((xs,n):rest) k x
| x <= k - 0.9999999 + f n = fun xs k x
| otherwise = getFun' rest (k + f n) x
predict :: [Double] -> [Int] -> Double -> Double
predict xs ns = predict_aux xs ns 1
where
predict_aux xs [] k = fun xs k
predict_aux xs (n:ns) k = let (_,rest) = splitAt n xs in
predict_aux rest ns (k + f n)
f = fromIntegral
-- computing a linear frunction defined over a monotone list of points
fun xs k x = m * x + c
where
m = (last xs - head xs) / (fromIntegral (length xs) - 1)
c = head xs - m * k
---- list of length k with inverted predictions
getOppFuns :: Double -> [Double] -> [Vector Double]
getOppFuns k xs
| null xs = []
| otherwise = zipWith mFl mfs (replicate (floor k) [1 .. fLen xs])
where
mFl f = fromList . map f
hs = head xs
ms = mean (fromList xs)
fLen = fromIntegral . length
m = (last xs - hs) / (fLen xs - 0.5)
mf n x = (fst n) * x + (snd n - fst n)
mfs = map mf $ zip (map (m/) [-1 * k .. -1]) mkSlp
mkSlp | m >= 0 = [ms ,ms + (1/k) .. ]
| otherwise = [ms , ms - (1/k) .. ]
--- given a list of predictions, check that all of it is ascending.
--- if all are not, calculate the inversion of the descending slopes and
--- combine them up to form a larger list
manyInvNS :: Bool -> [Double] -> [[Double]]
manyInvNS positive = take 1 . map toList. combWithInv positive . remIncrCuts positive . findCuts
where
combWithInv :: Bool -> [[Double]] -> [Vector Double]
combWithInv pos [] = []
combWithInv pos (x:xs)
| pos && ascending x =
case combWithInv pos xs of
[] -> [fromList x]
xss -> [vAdd (fromList x) k | k <- xss]
| (not pos) && desending x =
case combWithInv pos xs of
[] -> [fromList x]
xss -> [vAdd (fromList x) k | k <- xss]
| otherwise =
case combWithInv pos xs of
[] -> vss
yss -> concatMap (\a -> map (flip vAdd a) vss) yss
where
vAdd v1 v2 = join [v1,v2]
vss = getOppFuns 20 x
-----------------------------------
---returning the gradient of each new slope, which determins how steep the inversions are
getOppFuns1 :: Double -> [Double] -> [(Double ,Vector Double)]
getOppFuns1 k xs
| null xs = []
| otherwise = [ (fst (yss !! i) , vs) | (yss,i) <- zip mprs [0,1 .. length xs - 1]
, let vs = fromList $ map snd yss
, let vsum = foldVector (+) 0 vs
, vsum /= 0 ]
where
mprs :: [[(Double,Double) ]]
mprs = zipWith map mfs (replicate (floor k) [1 .. fLen])
---
hs1 = head xs
hs = if hs == 0 then 0.0000001 else hs1
ms = mean (fromList xs)
fLen = (fromIntegral . length) xs
mm = (last xs - hs) / (fLen - 0.5)
mf (m,c) x = (m, m * x + c)
--
mfs :: [Double -> (Double , Double)]
mfs = map mf $ zip (map (mm/) [-(2 * k) .. -1]) intercept
intercept | mm <= 0 = iterate ((+) (1/k)) ms
| otherwise = iterate ((-) (1/k)) ms
-- given a list of predictions, returns a lists where the portions of the predictions
-- with negative slopes are inverted (in the sense that the least possible positive slope is
-- drawn where slope is not zero)
manyInvNS1 :: Bool -> [Double] -> [(Double ,[Double])]
manyInvNS1 pos = map (\(a,b) -> (a,toList b)) . combWithInv pos . remIncrCuts pos . findCuts
where
--
combWithInv :: Bool -> [[Double]] -> [(Double , Vector Double)]
combWithInv pos [] = []
combWithInv pos (x:xs)
| (pos && ascending x) || ((not pos) && desending x) =
case combWithInv pos xs of
[] -> [ (1, fromList x)]
xss -> [ (i , vAdd (fromList x) k) | (i,k) <- xss]
| otherwise =
case combWithInv pos xs of
[] -> vss
yss -> concatMap (\(j,a) -> [(j,flip vAdd a k) | (_,k) <- vss]) yss
where
vAdd v1 v2 = join [v1,v2]
len = length x
ln = if len < 20 then 15 else 20
vss_aux = getOppFuns1 (fromIntegral ln) x
vss = maybe [(0,fromList x)] (:[]) (listToMaybe vss_aux)
-----------------------------------------------------------------------------------------------
{--
allPositiveSlopes : takes a list of known predictions, paired with
a list frequency of cuts in the predictions, and decides whether all
slopes among the predictions are >= 0. The function returns
True if all slopes are at least 0 and False otherwise.
--}
allPositiveSlopes :: [Double] -> [Int] -> Bool
allPositiveSlopes predts cuts = all id slopes
where
slopes = [ascending points | (points, _) <- mkIntervals predts cuts]
gradient xs | null xs = 0
| otherwise = m xs
m xs = (last xs - head xs) / (fromIntegral (length xs) - 1)
---------------------------------------------------------------------------------------------------
--- takes a list of functions, a list of split positions and a
--- list of the input (i.e x) values for the functions
piecewiseFun :: [(Double -> Double)] -> [Int] -> [Double] -> Double -> Double
piecewiseFun xs@(f:_) [] _ k = f k
piecewiseFun (f:fs) (n:ns) ys k | k < x = f k
| otherwise = piecewiseFun fs ns rest k
where
x = (ys !! n-1)
(_,!rest) = splitAt n ys
--- predictions from linear parameters
predsFromLP :: [Double] -> [Int] -> Double -> Double
predsFromLP [c,m] [] x = c + m* x
predsFromLP (c:m:xs) (y:ys) x
| x <= (fromIntegral y) = c + m * x
| otherwise = predsFromLP xs ys x
predsFromLP _ _ x = x
-- factorize then common----}
--
appFunAfterFactoring :: Eq a => (a -> b) -> [[a]] -> [[b]]
appFunAfterFactoring f xs = concat [appF f zs | zs <- factorHead xs]
where
appF :: (a -> b) -> Either (a,[[a]]) [a] -> [[b]]
appF f eth = case eth of
Left !ps -> multiplyThrough f ps
Right !qs -> [map f qs]
--
multiplyThrough :: (a -> b) -> (a, [[a]]) -> [[b]]
multiplyThrough f (x, xs) = fx `seq` map ((fx:) . map f) xs
where fx = f x
--
factorHead :: Eq a => [[a]] -> [Either (a,[[a]]) [a]]
factorHead [] = []
factorHead ((x:xs):ys) | null ys = [(Right (x:xs))]
| null front = (Right (x:xs)) : factorHead back
| otherwise = (Left (x,xs: map tail front)) : factorHead back
where (front,back) = span ((== x) . head) ys
--------------------------------------------------------------------------------------------------
findGrps :: ( Eq a) => Double -> Int -> (a -> a -> Double) -> [a] -> [[Int]]
findGrps tol lim f xs -- move sg and replace it with an integer reppresenting the maximum ot group
| tol <= 0.2 = groups: [ js | let lss = preCombine1 False groups, js <- [groups,lss]]
| length groups < lim = [ ks | ks <- recomnFix groups]
| otherwise = findGrps (tol - 0.05) lim f xs
where
groups = findGrps_aux 1 f tol xs
-- possCuts -- groups elements together to possiblt form a group
possCuts m n xs
| n > (length xs - m) = []
| otherwise = (front, length front) : possCuts m (n+1) xs
where front = take n xs
--- add
preCombine1 :: Bool -> [Int] -> [Int]
preCombine1 bb (x:y:z:xs)
-- | null xs =
| all1 [y,z] = preCombine1 bb (x : 2 : xs)
| x == 1 = preCombine1 bb ((1 + y) : z : xs)
| y == 1 = preCombine1 bb ((x + 1) : z : xs)
| all1 [y,z] && x == 1 = preCombine1 bb (3 : xs)
| all1 [x,y] = preCombine1 bb (2 : z : xs)
| otherwise = x : preCombine1 bb (y : z : xs)
where
all1 :: [Int] -> Bool
all1 xs = all (== 1) xs
preCombine1 _ xs = xs
---
findGrps_aux :: ( Eq a) => Int -> (a -> a -> Double) -> Double -> [a] -> [Int]
findGrps_aux _ _ _ [] = []
findGrps_aux _ _ _ [a] = [1]
findGrps_aux mn f trh ks@(x:xs) = mxx : findGrps_aux mn f trh (drop mxx ks)
where
mxx = maybe mn (\_ -> maximum mkGrps) (listToMaybe mkGrps)
mkGrps = [ n | (ys,n) <- possCuts mn mn ks
, let rss = map (f x) ys
, all (>= trh) rss
]
--- recombinining with fixed groups
recomnFix :: [Int] -> [[Int]]
recomnFix cls
| lcls <= 25 = combinations 0 2 cls
| lcls <= 32 = combinations 7 (lim `div` 15) cls
| otherwise = combinations 8 (lim `div` 10) cls
where
lcls = length cls
combinations m k xs = [kss | i <- [m .. 19], (ks,_) <- nPiecesP i k Nothing xs , kss <- [map sum ks]]
----------------------------------------------------------------
-- returns the first elements that satisfies a given predicate
takeFirst :: (a -> Bool) -> [a] -> [a]
takeFirst f = myTake 1 . filter f
-- alternative takeFirst returning maybe a
takeFirstM :: (a -> Bool) -> [a] -> Maybe a
takeFirstM f = listToMaybe . takeFirst f
-----------------------------------------------------------------------
-- change the suffix of an inout file
in2out :: String -> String
in2out ".dat" = ".nrm"
in2out (x:xs) = x : in2out xs
in2out xs = xs
-- tokens
tokens :: String -> Char -> [String]
tokens [] a = []
tokens (x:xs) a | x == a = tokens xs a
| otherwise = let (front, back) = span ( /= a) xs in
(x:front) : tokens back a
-- make tokens of a list of a given number of elements
tokeNn :: Int -> [a] -> [[a]]
tokeNn _ [] = []
tokeNn n xs = y : tokeNn n ys
where (y , ys) = splitAt n xs
-- puts a character between every element of a list of strings
rToks :: [String] -> Char -> String
rToks (x:xs) a = x ++ foldr (\bs as -> (flip (:) bs a) ++ as) "" xs
rToks [] _ = []
--- rDoubleS: takes a lists of numbers as strings and returns then as list of Double
rDoubleS :: [String] -> [Double]
rDoubleS = map rDouble
rDouble :: String -> Double
rDouble = read
-- does the opposite to rDoubles
showDoubles :: [Double] -> [String]
showDoubles = map show
tokens' = flip tokens
-- i want the files in the .nrm file to be standardised
------------------------------------------------------------------------------------------------
printElmChr :: Show a => Char -> [a] -> String
printElmChr chr = foldl' prt []
where prt b a | null b = show a
| otherwise = b ++ (chr : show a)
printElm :: Show a => [a] -> String
printElm = printElmChr ','
---------------------------------------------------------------------
printStrings :: [String] -> Handle -> IO ()
printStrings [] _ = return ()
printStrings (x:xs) handle = do hPutStrLn handle x
printStrings xs handle
-- removes the brackets from a string
remSqBrcs xs = filter (\a -> a /= ']' && a /= '[') xs
| rawlep/EQS | sourceCode/LMisc.hs | mit | 34,881 | 0 | 17 | 12,589 | 12,042 | 6,411 | 5,631 | 523 | 5 |
module GameTypes.ServerGame where
import Net.Communication (open, accept, receive, send)
import Net.Protocol (Message(..))
import Players.RemotePlayer (RemotePlayer(..))
import Players.LocalPlayer (LocalPlayer(..))
import Network.Socket (sClose)
import System.IO
import TicTacToe (Token(..))
-- closes the client handle and the server socket
cleanUp :: (LocalPlayer, RemotePlayer) -> IO ()
cleanUp (LocalPlayer _ _ hdl Nothing, _) = hClose hdl
cleanUp (LocalPlayer _ _ hdl (Just sock), _) = do
hClose hdl
sClose sock
-- initiates communication between a server and a
-- client by opening a server socket, and accepting
-- a connection. Then, hellos are exchanged.
create :: IO (LocalPlayer, RemotePlayer)
create = do
putStrLn "What is your name?"
xPlayer <- getLine
putStrLn "Waiting for player..."
sock <- open 2345
accept sock >>= onJoined xPlayer sock
where
onJoined ln sock (hdl, _, _) = do
(Hello name) <- receive hdl
Hello ln `send` hdl
let lp = LocalPlayer ln X hdl (Just sock)
let rm = RemotePlayer name O hdl
return (lp, rm)
| davidarnarsson/tictactoe | GameTypes/ServerGame.hs | mit | 1,187 | 0 | 14 | 310 | 351 | 185 | 166 | 26 | 1 |
module Util.PrettyPrint
( PrettyPrint(..)
, Util.PrettyPrint.print
, Out
, pprName
, nil
, str
, num
, append
, newline
, indent
, Util.PrettyPrint.concat
, interleave
) where
-- Data type for Output
data Out
= Str String
| Newline
| Indent Out
| Nil
| Append Out Out
-- helpers
nil :: Out
nil = Nil
str :: String -> Out
str = Str
num :: (Num n, Show n) => n -> Out
num n = str (show n)
append :: Out -> Out -> Out
append = Append
newline :: Out
newline = Newline
indent :: Out -> Out
indent = Indent
concat :: [Out] -> Out
concat = foldr append Nil
interleave :: Out -> [Out] -> Out
interleave _ [] = Nil
interleave _ [o] = o
interleave sep (o : os) = (o `append` sep) `append` interleave sep os
-- Class for PrettyPrinting with Out
class PrettyPrint a where
pprint :: a -> Out
-- Printing Out
instance Show Out where
show out = flatten 0 [(out, 0)]
-- Idempotent
instance PrettyPrint Out where
pprint a = a
print :: PrettyPrint a => a -> String
print = show . pprint
flatten :: Int -> [(Out, Int)] -> String
flatten _ [] = ""
flatten _ ((Newline, indent) : out) = '\n' : spaces indent ++ flatten indent out
flatten col ((Str s, _) : out) = s ++ flatten col out
flatten col ((Indent o, _) : out) = flatten col ((o, col + 1) : out)
flatten col ((Nil, _) : out) = flatten col out
flatten col ((Append o1 o2, indent) : out) = flatten col ((o1, indent) : (o2, indent) : out)
spaces :: Int -> String
spaces n = replicate (n * indent_size) ' '
indent_size :: Int
indent_size = 2
-- should be (re)moved
pprName :: String -> String
pprName = reverse . takeWhile (/= '.') . reverse
| tadeuzagallo/verve-lang | src/Util/PrettyPrint.hs | mit | 1,635 | 0 | 9 | 381 | 691 | 384 | 307 | 58 | 1 |
-----------------------------------------------------------------------------
--
-- Module : TypeNum.TypeFunctions
-- Copyright :
-- License : MIT
--
-- Maintainer : -
-- Stability :
-- Portability :
--
-- |
--
{-# LANGUAGE PolyKinds, ConstraintKinds #-}
module TypeNum.TypeFunctions (
-- * Types equality
TypesEq(..) , type (==)
, type (=~=), type (/~=)
-- * Types ordering
, TypesOrd(..) -- , Cmp
, type (<), type (>), type (<=), type (>=)
, Min, Max
-- * Pairs deconstruction
, Fst, Snd, ZipPairs
-- * Maybe
, FromMaybe
-- * Arrow-like tuple operations
, First, Second
-- * Different tuple operations
, Firsts, Seconds
-- * Containers
, TContainerElem(..) -- Contains, All, Any, Prepend, Append, Rm
, type (++), ContainsEach
, TContainers(..) -- , Concat, SameSize
, TContainerSameSize(..) -- , Zip
-- -- * Folds
-- , Fold, FoldWhile
-- * Functions
, (:$:)
, Curry, Uncurry
-- * Some :$: functions
, EqFunc, EqualFunc, CmpFunc
, ContainsFunc
) where
import Data.Type.Bool
import Data.Type.Equality
-----------------------------------------------------------------------------
infix 4 ~=~, =~=, /~=
infix 4 <, <=, >, >=
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
class TypesEq (x :: a) (y :: b) where
-- | Types equality, permitting types of different kinds.
type (~=~) (x :: a) (y :: b) :: Bool
type (=~=) a b = (a ~=~ b) ~ True
type (/~=) a b = (a ~=~ b) ~ False
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
class (TypesEq x y) =>
TypesOrd (x :: a) (y :: b) where
-- | Types ordering.
type Cmp (x :: a) (y :: b) :: Ordering
type family (x :: a) < (y :: b) where a < b = Cmp a b == LT
type family (x :: a) > (y :: b) where a > b = Cmp a b == GT
type family (x :: a) <= (y :: b) where a <= b = a ~=~ b || a < b
type family (x :: a) >= (y :: b) where a >= b = a ~=~ b || a > b
type Max (x :: a) (y :: b) = If (x >= y) x y
type Min (x :: a) (y :: b) = If (x <= y) x y
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
instance TypesEq (a :: Ordering) (b :: Ordering) where type a ~=~ b = a == b
-----------------------------------------------------------------------------
instance TypesEq (a :: (x,y)) (b :: (x,y)) where
type a ~=~ b = (Fst a == Fst b) && (Snd a == Snd b)
instance TypesOrd (a :: (x,y)) (b :: (x,y)) where
type Cmp a b = Cmp2 a b
-----------------------------------------------------------------------------
instance TypesEq (a :: [x]) (b :: [x]) where
type a ~=~ b = All EqFunc (Zip a b)
-- Lexicographical order.
instance TypesOrd (h1 ': t1 :: [x]) (h2 ': t2 :: [x]) where
type Cmp (h1 ': t1) (h2 ': t2) = CmpTypesOrd (Cmp h1 h2) t1 t2
type family CmpTypesOrd (o :: Ordering) (a :: [x]) (b :: [x]) :: Ordering where
CmpTypesOrd EQ (h1 ': t1) (h2 ': t2) = CmpTypesOrd (Cmp h1 h2) t1 t2
CmpTypesOrd EQ '[] '[] = EQ
CmpTypesOrd EQ '[] l2 = LT
CmpTypesOrd EQ l1 '[] = GT
CmpTypesOrd o l1 l2 = o
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
type family Fst (p :: (a, b)) :: a where Fst '(a, b) = a
type family Snd (p :: (a, b)) :: b where Snd '(a, b) = b
-----------------------------------------------------------------------------
type family Cmp2 (a :: (x,y)) (b :: (x,y)) :: Ordering where
Cmp2 '(x1, y1) '(x2, y2) = If (x1 == x2) (Cmp y1 y2) (Cmp x1 x2)
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Apply a type-level function. Extendable.
type family (:$:) (f :: a -> b -> *) (x :: a) :: b
-----------------------------------------------------------------------------
type family Curry (f :: (a,b) -> c -> *) (x :: a) (y :: b) :: c
where Curry f x y = f :$: '(x, y)
type family Uncurry (f :: a -> (b -> c -> *) -> *) (p :: (a,b)) :: c
where Uncurry f '(x,y) = (f :$: x) :$: y
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Arrow-like tuple operations
type family First (p :: (a,b)) f :: (c,b) where
First '(a,b) f = '(f :$: a, b)
type family Second (p :: (a,b)) f :: (a,c) where
Second '(a,b) f = '(a, f :$: b)
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
type family ZipPairs (p1 :: (a,a)) (p2 :: (b,b)) :: ((a,b), (a,b)) where
ZipPairs '(a1, a2) '(b1, b2) = '( '(a1,b1), '(a2,b2))
type family Firsts (p :: ((a,b), (a,b))) f :: ((c,b), (c,b))
where Firsts '( '(a1,b1), '(a2,b2)) f = ZipPairs (f :$: '(a1, a2)) '(b1,b2)
type family Seconds (p :: ((a,b), (a,b))) f :: ((a,c), (a,c))
where Seconds '( '(a1,b1), '(a2,b2)) f = ZipPairs '(a1,a2) (f :$: '(b1, b2))
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
data EqFunc (arg :: (a,b)) (res :: Bool)
type instance EqFunc :$: '(x,y) = x ~=~ y
data EqualFunc (val :: a) (arg :: b) (res :: Bool)
type instance EqualFunc x :$: y = x ~=~ y
data CmpFunc (c :: (a,b)) (o :: Ordering)
type instance CmpFunc :$: '(x,y) = Cmp x y
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
class TContainerElem (t :: k) (x :: e) where
type Contains x t :: Bool
type All (cond :: e -> Bool -> *) t :: Bool
type Any (cond :: e -> Bool -> *) t :: Bool
type Prepend x t :: k
type Append t x :: k
type Rm x t :: k
class TContainers (t1 :: k) (t2 :: k) where
type Concat t1 t2 :: k
type SameSize t1 t2 :: Bool
-- class (SameSize t1 t2 ~ True) =>
-- TContainerSameSize (t1 :: k) (t2 :: k) where
-- type Zip t1 t2 :: k
class (SameSize t1 t2 ~ True) =>
TContainerSameSize (t1 :: k) (t2 :: k) (res :: k') where
type Zip t1 t2 :: k'
data ContainsFunc (t :: k) (x :: e) (res :: Bool)
type instance ContainsFunc t :$: x = Contains x t
type ContainsEach (t :: k) (xs :: k) = All (ContainsFunc t) xs
type xs ++ ys = Concat xs ys
-----------------------------------------------------------------------------
class FoldableT (t :: k) (x :: e) (x0 :: r) where
type Fold (f :: (r, e) -> r -> *) x0 t :: r
type FoldWhile (cond :: e -> Bool -> *) (f :: (r, e) -> r -> *) x0 t :: r
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
instance TContainerElem ('[] :: [a]) (x :: a) where
type Contains x '[] = False
type All cond '[] = True
type Any cond '[] = False
type Prepend x '[] = '[x]
type Append '[] x = '[x]
type Rm x '[] = '[]
instance TContainerElem ((h ': t) :: [a]) (x :: a) where
type Contains x (h ': t) = h == x || Contains x t
type All cond (h ': t) = (cond :$: h) && All cond t
type Any cond (h ': t) = (cond :$: h) || Any cond t
type Prepend x (h ': t) = x ': h ': t
type Append (h ': t) x = h ': Append t x
type Rm x (h ': t) = If (h == x) (Rm x t) (h ': Rm x t)
-----------------------------------------------------------------------------
instance TContainers ('[] :: [a]) ('[] :: [a]) where
type Concat '[] '[] = '[]
type SameSize '[] '[] = True
instance TContainers ('[] :: [a]) ((h ': t) :: [a]) where
type Concat '[] (h ': t) = (h ': t)
type SameSize '[] (h ': t) = False
instance TContainers ((h ': t) :: [a]) ('[] :: [a]) where
type Concat (h ': t) '[] = (h ': t)
type SameSize (h ': t) '[] = False
instance TContainers ((h1 ': t1) :: [a]) ((h2 ': t2) :: [a]) where
type Concat (h1 ': t1) (h2 ': t2) = h1 ': Concat t1 (h2 ': t2)
type SameSize (h1 ': t1) (h2 ': t2) = SameSize t1 t2
-----------------------------------------------------------------------------
instance TContainerSameSize ('[] :: [a]) ('[] :: [a]) ('[] :: [(a,a)]) where
type Zip '[] '[] = '[]
instance (SameSize t1 t2 ~ True) => TContainerSameSize ((h1 ': t1) :: [a])
((h2 ': t2) :: [a])
(res :: [(a,a)])
where
type Zip (h1 ': t1) (h2 ': t2) = '(h1, h2) ': Zip t1 t2
-----------------------------------------------------------------------------
instance FoldableT ('[] :: [a]) (x :: a) x0 where
type Fold f x0 '[] = x0
type FoldWhile cond f x0 '[] = x0
instance FoldableT ((h ': t) :: [a]) (x :: a) x0 where
type Fold f x0 (x ': xs) = Fold f (f :$: '(x0, x)) xs
type FoldWhile cond f x0 (x ': xs) = If (cond :$: x)
(FoldWhile cond f (f :$: '(x0, x)) xs)
x0
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
type family FromMaybe (mb :: Maybe b) f (x0 :: a) :: a where
FromMaybe (Just x) f x0 = f :$: x
FromMaybe Nothing f x0 = x0
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Tests
data A = A'
data B = B'
data C = C'
data ACFunc a c
type instance ACFunc :$: A' = C'
type X = First '(A', B') ACFunc
data ACFunc2 a c
type instance ACFunc2 :$: '(A', A') = '(C', C')
type Y = Firsts '( '(A',B'), '(A',B')) ACFunc2
| fehu/TypeNumerics | src/TypeNum/TypeFunctions.hs | mit | 9,940 | 34 | 12 | 2,132 | 3,837 | 2,279 | 1,558 | -1 | -1 |
import Data.List (maximumBy)
import MyLib (fact,numOfDgt)
main = print $ answer 1000
answer n = sndmax (cycs n)
-- sndmax [(2,0),(0,5),(3,1)]==(0,5)
-- sndmax [(2,0),(0,2),(3,3)]==(3,3)
sndmax :: Ord a => [(b,a)] -> (b,a)
sndmax = maximumBy (\(x,y) (z,w)->compare y w)
-- cycs 3 == []
cycs :: Integral a => a -> [(a,a)]
cycs n = zip [1..n] [cyc i | i<-[1..n]]
-- trim 6==3, trim 70=7
trim :: Integral a => a -> a
trim n = (product.drop25.fact) n
-- drop25 [2,2,3,3,5,5,5,7] == [3,3,7]
drop25 :: Integral a => [a] -> [a]
drop25 [] = []
drop25 (x:xs) = if x==2 || x==5
then drop25 xs else x:drop25 xs
-- cyc 10 == 0, cyc 3 == 1, cyc 7 == 6
cyc :: Integral a => a->a
cyc n | trim n == 1 = 0
| otherwise = helper 1 where
helper i | isCyc n i = i
| otherwise = helper (i+1)
-- isCyc 3 1 == True, isCyc 7 6 == True
isCyc :: Integral a => a -> a -> Bool
isCyc n d= f==g where
f = sub (trim n) (d+offset)
g = sub (trim n) (d*2+offset) `mod` (10^d)
offset = numOfDgt (trim n) - 1
-- sub 6 2 == 16, sub 6 5 == 16666
sub :: Integral a => a -> a -> a
sub n i = numer `div` demin where
numer = 10^(fromIntegral i)
demin = fromIntegral n
| yuto-matsum/contest-util-hs | src/Euler/026.hs | mit | 1,181 | 0 | 11 | 297 | 567 | 297 | 270 | 28 | 2 |
module GHCJS.DOM.RTCIceCandidateEvent (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/RTCIceCandidateEvent.hs | mit | 50 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
----------------------------------------------------------------------------
---- |
---- Module: ETL
---- Description: Transform scrabble scores from [(score: [letter])] map to
---- [(letter:score)] map
---- Copyright: (c) 2015 Alex Dzyoba <[email protected]>
---- License: MIT
----------------------------------------------------------------------------
module ETL (transform)
where
import qualified Data.Map as M
import qualified Data.Text as T
type OldScores = M.Map Int [String]
type NewScores = M.Map String Int
-- | Transform old scores to the new one
---- We iterate over key-value pairs and fold them into empty map of new scores
transform :: OldScores -> NewScores
transform old = M.foldWithKey transformEntry M.empty old
-- | Transform single entry of old scores
---- This iterates over letters and fold them into newScores
transformEntry :: Int -> [String] -> NewScores -> NewScores
transformEntry score letters newScores = foldr (updateWithScore score) newScores letters
-- | Insert single letter with score into map of new scores.
---- Letter is converted to lowercase
updateWithScore :: Int -> String -> NewScores -> NewScores
updateWithScore score letter newScores = M.insert (toLower letter) score newScores
-- | Little helper to convert string to lowercase with help of Data.Text
toLower :: String -> String
toLower = T.unpack . T.toLower . T.pack
| dzeban/haskell-exercism | etl/ETL.hs | mit | 1,388 | 0 | 7 | 216 | 214 | 123 | 91 | 13 | 1 |
import Data.ByteString.Char8 (pack)
import Crypto.Hash
main = do
let input = "vkjiggvb"
result = compute input
print result
type Coord = (Int, Int)
type Dir = Char
type State = (Coord, [Dir], String)
bounds :: Int
bounds = 3
start :: Coord
start = (0,0)
initState :: String -> State
initState input = (start, [], input)
compute :: String -> Int
compute input = length $ search [initState input] []
isGoal :: State -> Bool
isGoal (coord, _, _) = coord == (bounds, bounds)
nextStates :: State -> [State]
nextStates s@(coord, dirs, input) = up ++ down ++ left ++ right
where h = take 4 $ getHash (input ++ dirs)
up = if open (h !! 0) then moveState 'U' s else []
down = if open (h !! 1) then moveState 'D' s else []
left = if open (h !! 2) then moveState 'L' s else []
right = if open (h !! 3) then moveState 'R' s else []
open :: Char -> Bool
open c = c `elem` "bcdef"
moveState :: Char -> State -> [State]
moveState 'U' ((x, y), dirs, input)
| y == 0 = []
| otherwise = [((x, y - 1), dirs ++ ['U'], input)]
moveState 'D' ((x, y), dirs, input)
| y == bounds = []
| otherwise = [((x, y + 1), dirs ++ ['D'], input)]
moveState 'L' ((x, y), dirs, input)
| x == 0 = []
| otherwise = [((x - 1, y), dirs ++ ['L'], input)]
moveState 'R' ((x, y), dirs, input)
| x == bounds = []
| otherwise = [((x + 1, y), dirs ++ ['R'], input)]
-- Breadth-first search
search :: [State] -> [Dir] -> [Dir]
search [] dirs = dirs
search (current : rest) dirs
| isGoal current = let (_, path, _) = current in search rest path
| otherwise = search (rest ++ (nextStates current)) dirs
getHash :: String -> String
getHash input = show (hash $ pack input :: Digest MD5) | aBhallo/AoC2016 | Day 17/day17part2.hs | mit | 1,805 | 0 | 10 | 501 | 882 | 484 | 398 | 48 | 5 |
module Solidran.Lexf.DetailSpec (spec) where
import Test.Hspec
import Solidran.Lexf.Detail
spec :: Spec
spec = do
describe "Solidran.Lexf.Detail" $ do
describe "getAlphabetStrings" $ do
it "should return an empty list on empty alphabet" $ do
getAlphabetStrings 2 []
`shouldBe` []
it "should return a single string on 0-length strings" $ do
getAlphabetStrings 0 "AB"
`shouldBe` [""]
it "should work for 1-length strings" $ do
getAlphabetStrings 1 "TAGC"
`shouldBe` ["T", "A", "G", "C"]
it "should work for 1-symbol alphabets" $ do
getAlphabetStrings 3 "A"
`shouldBe` ["AAA"]
it "should work on the given example" $ do
getAlphabetStrings 2 "TAGC"
`shouldBe` [ "TT", "TA", "TG", "TC"
, "AT", "AA", "AG", "AC"
, "GT", "GA", "GG", "GC"
, "CT", "CA", "CG", "CC" ]
| Jefffrey/Solidran | test/Solidran/Lexf/DetailSpec.hs | mit | 1,105 | 0 | 18 | 464 | 243 | 130 | 113 | 25 | 1 |
import State (Token(..), State(..), TransitionFunction(..), Transition(..), TransitionMap)
import qualified NDFSM (NDFSM(..))
import NDFSM (NDFSM, NDState, exploreTransitions, flatten, tabulate, acceptsState, eps)
import qualified FSM (FSM(..))
import FSM (FSM, mapTransitions, mapToFunc, accepts)
import qualified Data.Set as Set (fromList, singleton, empty)
import Data.Bimap (elems, keys, (!))
import PrettyPrinter (ndfsm_to_fsm_string)
import Control.Applicative ((<$>))
import ExampleNDFSMs (abba_ndfsm)
-- Transforms an NDFSM into an FSM
ndfsm_to_fsm :: NDFSM -> FSM
ndfsm_to_fsm ndfsm = FSM.FSM {FSM.states = Set.fromList $ elems correspondence,
FSM.state0 = correspondence ! (eps ndfsm $ NDFSM.state0 ndfsm),
FSM.accepting = Set.fromList $
[correspondence ! ndstate |
ndstate <- keys correspondence,
ndfsm `acceptsState` ndstate],
FSM.transitionFunction = mapToFunc transitionMap,
FSM.alphabet = NDFSM.alphabet ndfsm }
where
nd_transitions = exploreTransitions ndfsm
d_transitions = flatten nd_transitions
-- Bimap correspondence between ND states and D states
correspondence = tabulate nd_transitions
transitionMap = mapTransitions d_transitions
my_ndfsm = abba_ndfsm
my_fsm = ndfsm_to_fsm my_ndfsm
strings = ["abab", "babb", "abb", "babba", "abbaabba", "abbabbbb"]
main = do
putStrLn "generated FSM:"
putStrLn $ ndfsm_to_fsm_string my_ndfsm
putStrLn $ "matching " ++ show strings
let matches = (my_fsm `accepts`) <$> map Token <$> strings
putStrLn $ "matches: " ++ show matches | wyager/NDFSMtoFSM | StateMachine.hs | mit | 1,601 | 16 | 13 | 295 | 466 | 268 | 198 | 32 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
{-# OPTIONS_GHC -fno-warn-missing-methods #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MagicHash #-}
module Main (main) where
import Test.HUnit hiding (Test)
import Test.QuickCheck hiding ((.&.))
import Test.Framework ( Test, defaultMain )
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Providers.HUnit
import Data.Word.N
import Data.Word.N.Util
import Data.Bits
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString.Lazy as LZ
import GHC.TypeLits
import Data.Word
-- Most of these properties come from the package 'largeword' (on hackage).
-- This is because that package and this one expose pretty much the same api.
encode' :: (8 :|: n) => W n -> LZ.ByteString
encode' = disassembleR (runPut . putWord8 . (fromIntegral :: W 8 -> Word8))
decode' :: (8 :|: n) => LZ.ByteString -> W n
decode' = runGet (assembleR (fmap (fromIntegral :: Word8 -> W 8) getWord8))
instance (8 :|: n) => Arbitrary (W n) where
arbitrary = assembleL $ fmap (fromIntegral :: (Word8 -> W 8)) arbitrary
pShiftRightShiftLeft :: W 128 -> Bool
pShiftRightShiftLeft x = shiftR (shiftL x 1) 1 == x .&. (fromInteger ((2^127) - 1))
u1 :: Assertion
u1 = shiftR (18446744073709551616 :: W 128) 64 @?= 1
pQuotRem :: W 256 -> Bool
pQuotRem x = rx == fromInteger ry
where
(_qx, rx) = quotRem x 16
(_qy, ry) = quotRem ((fromIntegral x) :: Integer) 16
encodeDecode :: (8 :|: n) => W n -> Bool
encodeDecode word = decode' encoded == word
where
encoded = encode' word
{-# NOINLINE encoded #-}
correctEncoding :: Assertion
correctEncoding = (decode' . LZ.pack)
[0,0,0,0,0,0,0,0,50,89,125,125,237,119,73,240
,217,12,178,101,235,8,44,221,50,122,244,125,115,181,239,78]
@?=
(1234567891234567891234567812345678123456781234567812345678 :: W 256)
pRotateLeftRight :: W 256 -> Bool
pRotateLeftRight x = rotate (rotate x 8) (-8) == x
pRepeatedShift :: Int -> Property
pRepeatedShift n =
(n >= 0) && (n <= 1024) ==>
(((iterate (`shift` 8) (1::W 192))!!n) == shift (1::W 192) (n*8))
pRepeatedShift' :: Int -> Property
pRepeatedShift' n =
(n >= 0) && (n <= 1024) ==>
(((iterate (`shift` 8) a)!!n) == shift a (n*8))
where a :: W 192
a = 0x0123456789ABCDEFFEDCBA98765432100011223344556677
pRepeatedShift160 :: Int -> Property
pRepeatedShift160 n =
(n >= 0) && (n <= 1024) ==>
(((iterate (`shift` 8) (1::W 160))!!n) == shift (1::W 160) (n*8))
u2 :: Assertion
u2 = (2 :: W (256 + 128)) ^ 254 @?=
(fromInteger (2 :: Integer) ^ 254)
u3 :: Assertion
u3 = rotate (rotate ((2^255) :: W 256) (1)) (-1) @?=
((2^255) :: W 256)
u4 :: Assertion
u4 = shift (0x0123456789ABCDEFFEDCBA98765432100011223344556677 :: W 192) 80 @?=
(0xBA9876543210001122334455667700000000000000000000 :: W 192)
u5 :: Assertion
u5 = shift (0x112233445566778899AABBCC :: W 96) 40 @?=
(0x66778899AABBCC0000000000 :: W 96)
u6 :: Assertion
u6 = rotate ((2^95) :: W 96) (1) @?= 1
tests :: [Test]
tests =
[ testProperty "largeword shift left then right" pShiftRightShiftLeft
, testProperty "largeword quotRem by 16" pQuotRem
, testProperty "largeword rotate left then right" pRotateLeftRight
, testProperty "largeword repeated shift vs single shift" pRepeatedShift
, testProperty "largeword repeated shift vs single shift" pRepeatedShift'
, testProperty "largeword repeated shift vs single shift" pRepeatedShift160
, testCase "largeword shift 2^64 by 2^64" u1
, testCase "largeword exponentiation 2^254" u2
, testCase "largeword rotation by 1" u3
, testCase "largeword shift by 80" u4
, testCase "largeword shift by 40" u5
, testCase "largeword rotate by 1" u6
, testCase "big-endian encoding" correctEncoding
, testProperty "Word96 encode/decode loop" (encodeDecode::W 96 -> Bool)
, testProperty "Word128 encode/decode loop" (encodeDecode::W 128 -> Bool)
, testProperty "Word160 encode/decode loop" (encodeDecode::W 160 -> Bool)
, testProperty "Word192 encode/decode loop" (encodeDecode::W 192 -> Bool)
, testProperty "Word224 encode/decode loop" (encodeDecode::W 224 -> Bool)
, testProperty "Word256 encode/decode loop" (encodeDecode::W 256 -> Bool)
]
main :: IO ()
main = defaultMain tests
| nickspinale/bigword | tests/Properties.hs | mit | 5,100 | 0 | 13 | 1,073 | 1,473 | 824 | 649 | 112 | 1 |
{-|
Module : DataAssociation.Abstract
Description : Rules mining abstractions.
License : MIT
Stability : development
Rules mining abstractions.
-}
module DataAssociation.Abstract (
LargeItemsetsExtractor(..)
, AssociationRulesGenerator(..)
) where
import DataAssociation.Definitions
import Data.Map (Map)
-- | An abstraction for extracting __Large__ 'Itemset's.
class (Itemset set it) =>
LargeItemsetsExtractor set it where
findLargeItemsets :: MinSupport -- ^ minimal support to consider an itemset __large__
-> [set it] -- ^ input 'Itemset's
-> Map (set it) Float -- ^ __large__ itemsets with the corresponding support
-- | An abstraction for generating the association rules from the __large__ 'Itemset's.
class (Itemset set it) =>
AssociationRulesGenerator set it where
generateAssociationRules :: MinConfidence -- ^ minimal confidence for accepting a rule
-> [set it] -- ^ original full list of 'Itemset's
-> Map (set it) Float -- ^ __large__ 'Itemset's with the corresponding support
-> [AssocRule set it] -- ^ association rules
| fehu/min-dat--a-priori | core/src/DataAssociation/Abstract.hs | mit | 1,277 | 0 | 12 | 387 | 163 | 92 | 71 | -1 | -1 |
{-# OPTIONS_GHC -Wall #-}
-- {-# LANGUAGE DatatypeContexts #-}
module ApplicativeFunctors where
-- import Prelude hiding (Maybe)
-- import Data.Maybe hiding (Maybe)
import Control.Applicative
type Name = String
data Employee = Employee
{ name :: Name
, phone :: String }
deriving (Show)
-- data Maybe a = Nothing
-- | Just a
-- instance Applicative Maybe where
-- pure = Just
-- Nothing <*> _ = Nothing
-- _ <*> Nothing = Nothing
-- Just f <*> Just x = Just (f x)
mName, mName' :: Maybe Name
mName = Nothing
mName' = Just "Brent"
mPhone, mPhone' :: Maybe String
mPhone = Nothing
mPhone' = Just "555-1234"
ex01, ex02, ex03, ex04 :: Maybe Employee
ex01 = Employee <$> mName <*> mPhone
ex02 = Employee <$> mName <*> mPhone'
ex03 = Employee <$> mName' <*> mPhone
ex04 = Employee <$> mName' <*> mPhone'
| harrisi/on-being-better | list-expansion/Haskell/Learning/ApplicativeFunctors.hs | cc0-1.0 | 873 | 0 | 8 | 218 | 166 | 102 | 64 | 19 | 1 |
{- This module was generated from data in the Kate syntax
highlighting file rust.xml, version 1.1, by -}
module Text.Highlighting.Kate.Syntax.Rust
(highlight, parseExpression, syntaxName, syntaxExtensions)
where
import Text.Highlighting.Kate.Types
import Text.Highlighting.Kate.Common
import Text.ParserCombinators.Parsec hiding (State)
import Control.Monad.State
import Data.Char (isSpace)
import qualified Data.Set as Set
-- | Full name of language.
syntaxName :: String
syntaxName = "Rust"
-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.rs"
-- | Highlight source code using this syntax definition.
highlight :: String -> [SourceLine]
highlight input = evalState (mapM parseSourceLine $ lines input) startingState
parseSourceLine :: String -> State SyntaxState SourceLine
parseSourceLine = mkParseSourceLine (parseExpression Nothing)
-- | Parse an expression using appropriate local context.
parseExpression :: Maybe (String,String)
-> KateParser Token
parseExpression mbcontext = do
(lang,cont) <- maybe currentContext return mbcontext
result <- parseRules (lang,cont)
optional $ do eof
updateState $ \st -> st{ synStPrevChar = '\n' }
pEndLine
return result
startingState = SyntaxState {synStContexts = [("Rust","Normal")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []}
pEndLine = do
updateState $ \st -> st{ synStPrevNonspace = False }
context <- currentContext
contexts <- synStContexts `fmap` getState
st <- getState
if length contexts >= 2
then case context of
_ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False }
("Rust","Normal") -> return ()
("Rust","Attribute") -> return ()
("Rust","Function") -> return ()
("Rust","Type") -> return ()
("Rust","String") -> return ()
("Rust","RawString") -> return ()
("Rust","RawHashed1") -> return ()
("Rust","RawHashed2") -> return ()
("Rust","Character") -> (popContext) >> pEndLine
("Rust","CharEscape") -> (popContext) >> pEndLine
("Rust","Commentar 1") -> (popContext) >> pEndLine
("Rust","Commentar 2") -> return ()
_ -> return ()
else return ()
withAttribute attr txt = do
when (null txt) $ fail "Parser matched no text"
updateState $ \st -> st { synStPrevChar = last txt
, synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) }
return (attr, txt)
list_fn = Set.fromList $ words $ "fn"
list_type = Set.fromList $ words $ "type"
list_keywords = Set.fromList $ words $ "abstract alignof as become box break const continue crate do else enum extern final for if impl in let loop macro match mod move mut offsetof override priv proc pub pure ref return Self self sizeof static struct super trait type typeof unsafe unsized use virtual where while yield"
list_traits = Set.fromList $ words $ "AsSlice CharExt Clone Copy Debug Decodable Default Display DoubleEndedIterator Drop Encodable Eq Default Extend Fn FnMut FnOnce FromPrimitive Hash Iterator IteratorExt MutPtrExt Ord PartialEq PartialOrd PtrExt Rand Send Sized SliceConcatExt SliceExt Str StrExt Sync ToString"
list_types = Set.fromList $ words $ "bool int isize uint usize i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 float char str Option Result Self Box Vec String"
list_ctypes = Set.fromList $ words $ "c_float c_double c_void FILE fpos_t DIR dirent c_char c_schar c_uchar c_short c_ushort c_int c_uint c_long c_ulong size_t ptrdiff_t clock_t time_t c_longlong c_ulonglong intptr_t uintptr_t off_t dev_t ino_t pid_t mode_t ssize_t"
list_self = Set.fromList $ words $ "self"
list_constants = Set.fromList $ words $ "true false Some None Ok Err Success Failure Cons Nil"
list_cconstants = Set.fromList $ words $ "EXIT_FAILURE EXIT_SUCCESS RAND_MAX EOF SEEK_SET SEEK_CUR SEEK_END _IOFBF _IONBF _IOLBF BUFSIZ FOPEN_MAX FILENAME_MAX L_tmpnam TMP_MAX O_RDONLY O_WRONLY O_RDWR O_APPEND O_CREAT O_EXCL O_TRUNC S_IFIFO S_IFCHR S_IFBLK S_IFDIR S_IFREG S_IFMT S_IEXEC S_IWRITE S_IREAD S_IRWXU S_IXUSR S_IWUSR S_IRUSR F_OK R_OK W_OK X_OK STDIN_FILENO STDOUT_FILENO STDERR_FILENO"
regex_0x'5b0'2d9a'2dfA'2dF'5f'5d'2b'28'5biu'5d'288'7c16'7c32'7c64'29'3f'29'3f = compileRegex True "0x[0-9a-fA-F_]+([iu](8|16|32|64)?)?"
regex_0o'5b0'2d7'5f'5d'2b'28'5biu'5d'288'7c16'7c32'7c64'29'3f'29'3f = compileRegex True "0o[0-7_]+([iu](8|16|32|64)?)?"
regex_0b'5b0'2d1'5f'5d'2b'28'5biu'5d'288'7c16'7c32'7c64'29'3f'29'3f = compileRegex True "0b[0-1_]+([iu](8|16|32|64)?)?"
regex_'5b0'2d9'5d'5b0'2d9'5f'5d'2a'5c'2e'5b0'2d9'5f'5d'2a'28'5beE'5d'5b'2b'2d'5d'3f'5b0'2d9'5f'5d'2b'29'3f'28f32'7cf64'7cf'29'3f = compileRegex True "[0-9][0-9_]*\\.[0-9_]*([eE][+-]?[0-9_]+)?(f32|f64|f)?"
regex_'5b0'2d9'5d'5b0'2d9'5f'5d'2a'28'5biu'5d'288'7c16'7c32'7c64'29'3f'29'3f = compileRegex True "[0-9][0-9_]*([iu](8|16|32|64)?)?"
regex_'5ba'2dzA'2dZ'5f'5d'5ba'2dzA'2dZ'5f0'2d9'5d'2a'3a'3a = compileRegex True "[a-zA-Z_][a-zA-Z_0-9]*::"
regex_'5ba'2dzA'2dZ'5f'5d'5ba'2dzA'2dZ'5f0'2d9'5d'2a'21 = compileRegex True "[a-zA-Z_][a-zA-Z_0-9]*!"
regex_'27'5ba'2dzA'2dZ'5f'5d'5ba'2dzA'2dZ'5f0'2d9'5d'2a'28'3f'21'27'29 = compileRegex True "'[a-zA-Z_][a-zA-Z_0-9]*(?!')"
regex_x'5b0'2d9a'2dfA'2dF'5d'7b2'7d = compileRegex True "x[0-9a-fA-F]{2}"
regex_u'5c'7b'5b0'2d9a'2dfA'2dF'5d'7b1'2c6'7d'5c'7d = compileRegex True "u\\{[0-9a-fA-F]{1,6}\\}"
regex_u'5b0'2d9a'2dfA'2dF'5d'7b4'7d = compileRegex True "u[0-9a-fA-F]{4}"
regex_U'5b0'2d9a'2dfA'2dF'5d'7b8'7d = compileRegex True "U[0-9a-fA-F]{8}"
regex_'2e = compileRegex True "."
parseRules ("Rust","Normal") =
(((pDetectSpaces >>= withAttribute NormalTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_fn >>= withAttribute KeywordTok) >>~ pushContext ("Rust","Function"))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_type >>= withAttribute KeywordTok) >>~ pushContext ("Rust","Type"))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywords >>= withAttribute KeywordTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_types >>= withAttribute DataTypeTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_traits >>= withAttribute BuiltInTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_ctypes >>= withAttribute DataTypeTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_self >>= withAttribute KeywordTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_constants >>= withAttribute ConstantTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_cconstants >>= withAttribute ConstantTok))
<|>
((pDetect2Chars False '/' '/' >>= withAttribute CommentTok) >>~ pushContext ("Rust","Commentar 1"))
<|>
((pDetect2Chars False '/' '*' >>= withAttribute CommentTok) >>~ pushContext ("Rust","Commentar 2"))
<|>
((pRegExpr regex_0x'5b0'2d9a'2dfA'2dF'5f'5d'2b'28'5biu'5d'288'7c16'7c32'7c64'29'3f'29'3f >>= withAttribute DecValTok))
<|>
((pRegExpr regex_0o'5b0'2d7'5f'5d'2b'28'5biu'5d'288'7c16'7c32'7c64'29'3f'29'3f >>= withAttribute DecValTok))
<|>
((pRegExpr regex_0b'5b0'2d1'5f'5d'2b'28'5biu'5d'288'7c16'7c32'7c64'29'3f'29'3f >>= withAttribute DecValTok))
<|>
((pRegExpr regex_'5b0'2d9'5d'5b0'2d9'5f'5d'2a'5c'2e'5b0'2d9'5f'5d'2a'28'5beE'5d'5b'2b'2d'5d'3f'5b0'2d9'5f'5d'2b'29'3f'28f32'7cf64'7cf'29'3f >>= withAttribute DecValTok))
<|>
((pRegExpr regex_'5b0'2d9'5d'5b0'2d9'5f'5d'2a'28'5biu'5d'288'7c16'7c32'7c64'29'3f'29'3f >>= withAttribute DecValTok))
<|>
((pDetect2Chars False '#' '[' >>= withAttribute AttributeTok) >>~ pushContext ("Rust","Attribute"))
<|>
((pString False "#![" >>= withAttribute AttributeTok) >>~ pushContext ("Rust","Attribute"))
<|>
((pRegExpr regex_'5ba'2dzA'2dZ'5f'5d'5ba'2dzA'2dZ'5f0'2d9'5d'2a'3a'3a >>= withAttribute NormalTok))
<|>
((pRegExpr regex_'5ba'2dzA'2dZ'5f'5d'5ba'2dzA'2dZ'5f0'2d9'5d'2a'21 >>= withAttribute PreprocessorTok))
<|>
((pRegExpr regex_'27'5ba'2dzA'2dZ'5f'5d'5ba'2dzA'2dZ'5f0'2d9'5d'2a'28'3f'21'27'29 >>= withAttribute OtherTok))
<|>
((pDetectChar False '{' >>= withAttribute NormalTok))
<|>
((pDetectChar False '}' >>= withAttribute NormalTok))
<|>
((pDetect2Chars False 'r' '"' >>= withAttribute StringTok) >>~ pushContext ("Rust","RawString"))
<|>
((pString False "r##\"" >>= withAttribute StringTok) >>~ pushContext ("Rust","RawHashed2"))
<|>
((pString False "r#\"" >>= withAttribute StringTok) >>~ pushContext ("Rust","RawHashed1"))
<|>
((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("Rust","String"))
<|>
((pDetectChar False '\'' >>= withAttribute CharTok) >>~ pushContext ("Rust","Character"))
<|>
((pDetectChar False '[' >>= withAttribute NormalTok))
<|>
((pDetectChar False ']' >>= withAttribute NormalTok))
<|>
((pDetectIdentifier >>= withAttribute NormalTok))
<|>
(currentContext >>= \x -> guard (x == ("Rust","Normal")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Rust","Attribute") =
(((pDetectChar False ']' >>= withAttribute AttributeTok) >>~ (popContext))
<|>
((parseRules ("Rust","Normal")))
<|>
(currentContext >>= \x -> guard (x == ("Rust","Attribute")) >> pDefault >>= withAttribute AttributeTok))
parseRules ("Rust","Function") =
(((pDetectSpaces >>= withAttribute NormalTok))
<|>
((pDetectChar False '(' >>= withAttribute NormalTok) >>~ (popContext))
<|>
((pDetectChar False '<' >>= withAttribute NormalTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Rust","Function")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Rust","Type") =
(((pDetectSpaces >>= withAttribute NormalTok))
<|>
((pDetectChar False '=' >>= withAttribute NormalTok) >>~ (popContext))
<|>
((pDetectChar False '<' >>= withAttribute NormalTok) >>~ (popContext))
<|>
((pDetectChar False ';' >>= withAttribute NormalTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Rust","Type")) >> pDefault >>= withAttribute NormalTok))
parseRules ("Rust","String") =
(((pDetectChar False '\\' >>= withAttribute SpecialCharTok) >>~ pushContext ("Rust","CharEscape"))
<|>
((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Rust","String")) >> pDefault >>= withAttribute StringTok))
parseRules ("Rust","RawString") =
(((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Rust","RawString")) >> pDefault >>= withAttribute StringTok))
parseRules ("Rust","RawHashed1") =
(((pDetect2Chars False '"' '#' >>= withAttribute StringTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Rust","RawHashed1")) >> pDefault >>= withAttribute StringTok))
parseRules ("Rust","RawHashed2") =
(((pString False "\"##" >>= withAttribute StringTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Rust","RawHashed2")) >> pDefault >>= withAttribute StringTok))
parseRules ("Rust","Character") =
(((pDetectChar False '\\' >>= withAttribute SpecialCharTok) >>~ pushContext ("Rust","CharEscape"))
<|>
((pDetectChar False '\'' >>= withAttribute CharTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Rust","Character")) >> pDefault >>= withAttribute CharTok))
parseRules ("Rust","CharEscape") =
(((pAnyChar "nrt\\'\"" >>= withAttribute SpecialCharTok) >>~ (popContext))
<|>
((pRegExpr regex_x'5b0'2d9a'2dfA'2dF'5d'7b2'7d >>= withAttribute SpecialCharTok) >>~ (popContext))
<|>
((pRegExpr regex_u'5c'7b'5b0'2d9a'2dfA'2dF'5d'7b1'2c6'7d'5c'7d >>= withAttribute SpecialCharTok) >>~ (popContext))
<|>
((pRegExpr regex_u'5b0'2d9a'2dfA'2dF'5d'7b4'7d >>= withAttribute SpecialCharTok) >>~ (popContext))
<|>
((pRegExpr regex_U'5b0'2d9a'2dfA'2dF'5d'7b8'7d >>= withAttribute SpecialCharTok) >>~ (popContext))
<|>
((pRegExpr regex_'2e >>= withAttribute ErrorTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Rust","CharEscape")) >> pDefault >>= withAttribute SpecialCharTok))
parseRules ("Rust","Commentar 1") =
(currentContext >>= \x -> guard (x == ("Rust","Commentar 1")) >> pDefault >>= withAttribute CommentTok)
parseRules ("Rust","Commentar 2") =
(((pDetectSpaces >>= withAttribute CommentTok))
<|>
((pDetect2Chars False '*' '/' >>= withAttribute CommentTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("Rust","Commentar 2")) >> pDefault >>= withAttribute CommentTok))
parseRules x = parseRules ("Rust","Normal") <|> fail ("Unknown context" ++ show x)
| ambiata/highlighting-kate | Text/Highlighting/Kate/Syntax/Rust.hs | gpl-2.0 | 12,776 | 0 | 42 | 1,886 | 3,205 | 1,697 | 1,508 | 212 | 15 |
{- |
Module : ./Static/ToJson.hs
Description : json output of Hets development graphs
Copyright : (c) Christian Maeder, DFKI GmbH 2014
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable(Grothendieck)
Json of Hets DGs
-}
module Static.ToJson
( dGraph
, lnode
, dgSymbols
, showSymbols
, showSymbolsTh
) where
import Driver.Options
import Static.DgUtils
import Static.DevGraph
import Static.GTheory
import Static.ComputeTheory (getImportNames)
import Static.PrintDevGraph
import Logic.Prover
import Logic.Logic
import Logic.Comorphism
import Logic.Grothendieck
import Common.AS_Annotation
import Common.ConvertGlobalAnnos
import Common.Consistency
import Common.DocUtils
import Common.ExtSign
import Common.GlobalAnnotations
import Common.Id
import Common.IRI
import Common.LibName
import qualified Common.OrderedMap as OMap
import Common.Result
import Common.Json
import Data.Graph.Inductive.Graph as Graph
import Data.Maybe
import qualified Data.Map as Map
import qualified Data.Set as Set (toList)
{- |
Export the development graph as json. If the flag full is True then
symbols for all nodes are shown as declarations, otherwise (the
default) only declaration for basic spec nodes are shown as is done
for the corresponding xml output. -}
dGraph :: HetcatsOpts -> LibEnv -> LibName -> DGraph -> Json
dGraph opts lenv ln dg =
let body = dgBody dg
ga = globalAnnos dg
lnodes = labNodes body
ledges = labEdges body
in tagJson "DGraph" $ mkJObj
[ mkJPair "filename" $ getFilePath ln
, mkJPair "mime-type" . fromMaybe "unknown" $ mimeType ln
, mkJPair "libname" . show $ setAngles False $ getLibId ln
, ("dgnodes", mkJNum $ length lnodes)
, ("dgedges", mkJNum $ length ledges)
, ("nextlinkid", mkJNum . getEdgeNum $ getNewEdgeId dg)
, ("Global", mkJArr . map (anToJson ga) . convertGlobalAnnos
$ removeDOLprefixes ga)
, ("DGNode", mkJArr $ map (lnode opts ga lenv) lnodes)
, ("DGLink", mkJArr $ map (ledge opts ga dg) ledges) ]
gmorph :: HetcatsOpts -> GlobalAnnos -> GMorphism -> Json
gmorph opts ga gm@(GMorphism cid (ExtSign ssig _) _ tmor _) =
case map_sign cid ssig of
Result _ mr -> case mr of
Nothing -> error $ "Static.ToXml.gmorph: " ++ showGlobalDoc ga gm ""
Just (tsig, tsens) -> let
tid = targetLogic cid
sl = Map.toList . Map.filterWithKey (/=) $ symmap_of tid tmor
in mkJObj
$ mkNameJPair (language_name cid)
: [("ComorphismAxioms", mkJArr
$ map (showSen opts (targetLogic cid) ga Nothing tsig) tsens)
| not (fullTheories opts) && not (null tsens) ]
++ [("Map", mkJArr $
map (\ (s, t) -> mkJObj
[("map", showSym tid s), ("to", showSym tid t)]) sl)
| not $ null sl]
prettySymbol :: (GetRange a, Pretty a) => GlobalAnnos -> a -> [JPair]
prettySymbol = rangedToJson "Symbol"
lnode :: HetcatsOpts -> GlobalAnnos -> LibEnv -> LNode DGNodeLab -> Json
lnode opts ga lenv (_, lbl) =
let nm = dgn_name lbl
(spn, xp) = case reverse $ xpath nm of
ElemName s : t -> (s, showXPath t)
l -> ("?", showXPath l)
in mkJObj
$ mkNameJPair (showName nm)
: rangeToJPair (srcRange nm)
++ [("reference", mkJBool $ isDGRef lbl)]
++ case signOf $ dgn_theory lbl of
G_sign slid _ _ -> mkJPair "logic" (show slid)
: if not (isDGRef lbl) && dgn_origin lbl < DGProof then
[mkJPair "refname" spn, mkJPair "relxpath" xp ]
else []
++ case nodeInfo lbl of
DGRef li rf ->
[ ("Reference", mkJObj
[ mkJPair "library" $ show $ setAngles False $ getLibId li
, mkJPair "location" $ getFilePath li
, mkJPair "node" $ getNameOfNode rf $ lookupDGraph li lenv ])]
DGNode orig cs -> consStatus cs ++ case orig of
DGBasicSpec _ (G_sign lid (ExtSign dsig _) _) _ ->
let syms = mostSymsOf lid dsig in
[ ("Declarations", mkJArr
$ map (showSym lid) syms) | not $ null syms ]
DGRestriction _ hidSyms ->
[ ("Hidden", mkJArr
. map (mkJObj . prettySymbol ga)
$ Set.toList hidSyms) ]
_ -> []
++ case dgn_theory lbl of
G_theory lid _ (ExtSign sig _) _ thsens _ -> let
(axs, thms) = OMap.partition isAxiom thsens
nAxs = toNamedList axs
nThms = OMap.toList thms
in
[("Symbols", mkJArr . map (showSym lid) $ symlist_of lid sig)
| fullSign opts ]
++ [("Axioms", mkJArr
$ map (showSen opts lid ga Nothing sig) nAxs) | not $ null nAxs ]
++ [("Theorems", mkJArr
$ map (\ (s, t) -> showSen opts lid ga
(Just $ isProvenSenStatus t) sig $ toNamed s t)
nThms) | not $ null nThms]
++ if fullTheories opts then case globalTheory lbl of
Just (G_theory glid _ _ _ allSens _) -> case
coerceThSens glid lid "xml-lnode" allSens of
Just gsens -> let
nSens = toNamedList
$ OMap.filter ((`notElem` map sentence
(OMap.elems thsens)) . sentence) gsens
in [("ImpAxioms", mkJArr
$ map (showSen opts lid ga Nothing sig) nSens)
| not $ null nSens ]
_ -> []
_ -> []
else []
-- | a status may be open, proven or outdated
mkStatusJPair :: String -> JPair
mkStatusJPair = mkJPair "status"
mkProvenJPair :: Bool -> JPair
mkProvenJPair b = mkStatusJPair $ if b then "proven" else "open"
consStatus :: ConsStatus -> [JPair]
consStatus cs = case getConsOfStatus cs of
None -> []
cStat -> [("ConsStatus", mkJStr $ show cStat)]
ledge :: HetcatsOpts -> GlobalAnnos -> DGraph -> LEdge DGLinkLab -> Json
ledge opts ga dg (f, t, lbl) = let
typ = dgl_type lbl
mor = gmorph opts ga $ dgl_morphism lbl
mkMor n = [mkJPair "morphismsource" $ getNameOfNode n dg]
lnkSt = case thmLinkStatus typ of
Nothing -> []
Just tls -> case tls of
LeftOpen -> []
Proven r ls -> dgrule r
++ let bs = Set.toList $ proofBasis ls in
[("ProofBasis", mkJArr
$ map (mkJNum . getEdgeNum) bs) | not $ null bs]
in mkJObj
$ [ mkJPair "source" $ getNameOfNode f dg
, mkJPair "target" $ getNameOfNode t dg
, ("linkid", mkJNum . getEdgeNum $ dgl_id lbl) ]
++ case dgl_origin lbl of
DGLinkView i _ ->
[mkNameJPair . iriToStringShortUnsecure $ setAngles False i]
_ -> []
++ mkJPair "Type" (getDGLinkType lbl) : lnkSt
++ consStatus (getLinkConsStatus typ)
++ case typ of
HidingFreeOrCofreeThm _ n _ _ -> mkMor n
FreeOrCofreeDefLink _ (JustNode ns) -> mkMor $ getNode ns
_ -> []
++ [("GMorphism", mor)]
dgrule :: DGRule -> [JPair]
dgrule r =
mkJPair "Rule" (dgRuleHeader r)
: case r of
DGRuleLocalInference m -> [("MovedTheorems", mkJArr
$ map (\ (s, t) -> mkJObj [mkNameJPair s, mkJPair "renamedTo" t]) m)]
Composition es ->
[("Composition", mkJArr $ map (mkJNum . getEdgeNum) es)]
DGRuleWithEdge _ e -> [("RuleTarget", mkJNum $ getEdgeNum e)]
_ -> []
-- | collects all symbols from dg and displays them as json
dgSymbols :: HetcatsOpts -> DGraph -> Json
dgSymbols opts dg = let ga = globalAnnos dg in tagJson "Ontologies"
$ mkJArr $ map (\ (i, lbl) -> let ins = getImportNames dg i in
showSymbols opts ins ga lbl) $ labNodesDG dg
showSymbols :: HetcatsOpts -> [String] -> GlobalAnnos -> DGNodeLab -> Json
showSymbols opts ins ga lbl = showSymbolsTh opts ins (getDGNodeName lbl) ga
$ dgn_theory lbl
showSymbolsTh :: HetcatsOpts -> [String] -> String -> GlobalAnnos -> G_theory -> Json
showSymbolsTh opts ins name ga th = case th of
G_theory lid _ (ExtSign sig _) _ sens _ -> mkJObj
[ mkJPair "logic" $ language_name lid
, mkNameJPair name
, ("Ontology", mkJObj
[ ("Symbols", mkJArr . map (showSym lid) $ symlist_of lid sig)
, ("Axioms", mkJArr . map (showSen opts lid ga Nothing sig)
$ toNamedList sens)
, ("Import", mkJArr $ map mkJStr ins) ])]
showSen :: ( GetRange sentence, Pretty sentence
, Sentences lid sentence sign morphism symbol) =>
HetcatsOpts -> lid -> GlobalAnnos -> Maybe Bool -> sign -> Named sentence -> Json
showSen opts lid ga mt sig ns = let s = sentence ns in mkJObj
$ case mt of
Nothing -> []
Just b -> [mkProvenJPair b]
++ mkNameJPair (senAttr ns) : rangeToJPair (getRangeSpan s)
++ case priority ns of
Just p -> [mkPriorityJPair p]
_ -> []
++ mkJPair (if isJust mt then "Theorem" else "Axiom")
(show . useGlobalAnnos ga . print_named lid
. makeNamed "" $ simplify_sen lid sig s)
: (let syms = symsOfSen lid sig s in
[("SenSymbols", mkJArr $ map (showSym lid) syms)
| not $ null syms])
++ case senMark ns of
"" -> []
m -> [mkJPair "ComorphismOrigin" m]
++ if printAST opts
then [("AST", asJson s)]
else []
showSym :: Sentences lid sentence sign morphism symbol => lid -> symbol -> Json
showSym lid s = mkJObj
$ [ mkJPair "kind" $ symKind lid s
, mkNameJPair . show $ sym_name lid s
, mkJPair "iri" $ fullSymName lid s ]
++ prettySymbol emptyGlobalAnnos s
| gnn/Hets | Static/ToJson.hs | gpl-2.0 | 9,841 | 0 | 33 | 3,012 | 3,243 | 1,648 | 1,595 | 217 | 9 |
{-# OPTIONS_GHC -Wall -fwarn-tabs -Werror #-}
-------------------------------------------------------------------------------
-- |
-- Module : World
-- Copyright : Copyright (c) 2014 Michael R. Shannon
-- License : GPLv2 or Later
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : portable
--
-- World module.
-------------------------------------------------------------------------------
module World
( World(..)
, AnimationState(..)
, Sun(..)
, defaultWorld
) where
import World.Types
defaultWorld :: World
defaultWorld = World
{ animationState = Running
, sun = Sun
{ inclination = 45.0 + 90.0
, elevation = 10.0
}
, sunTexture = Nothing
, groundTexture = Nothing
, treeBarkTexture = Nothing
, leaves1Texture = Nothing
, leaves2Texture = Nothing
, skyboxTextures = Nothing
}
| mrshannon/trees | src/World.hs | gpl-2.0 | 917 | 0 | 9 | 211 | 125 | 86 | 39 | 19 | 1 |
module Main (main) where
import Language.Haskell.HLint (hlint)
import System.Exit (exitFailure, exitSuccess)
arguments :: [String]
arguments =
[ "parse-packages"
, "src"
, "test"
]
main :: IO ()
main = do
hints <- hlint arguments
if null hints then exitSuccess else exitFailure
| vikraman/packages-ng | test/HLint.hs | gpl-2.0 | 336 | 0 | 8 | 99 | 94 | 54 | 40 | 12 | 2 |
module Test (tests) where
import Data.Time
import Data.Time.Format
import Data.Time.LocalTime
import Main
import System.Locale
import Test.HUnit
sampleTime :: ParseTime t => Int -> t
sampleTime n = times !! n
where times = map readLocalTime [ ("%F", "2014-06-21")
, ("%F %R", "2014-06-21 07:00")
, ("%F", "2014-06-22")
, ("%F", "2014-06-23")
]
readLocalTime (fmt, s) = readTime defaultTimeLocale fmt s
testTimeAround =
"timeAround" ~:
("2014-06-14T00:00:00+0000", "2014-06-28T00:00:00+0000") ~=?
timeAround (sampleTime 0)
testListEventsUri =
"listEventsUri" ~:
"https://www.googleapis.com/calendar/v3/calendars/" ++
"id%20with%20space/events?singleEvents=true&" ++
"timeMin=mintime&timeMax=maxtime&access_token=token" ~=?
listEventsUri "token" "mintime" "maxtime" "id with space"
testOrgTimestamp =
"orgTimestamp" ~:
[ "Date" ~:
[ "same day" ~:
"<2014-06-21 Sat>" ~=? orgSample Date 0 2
, "different day" ~:
"<2014-06-21 Sat>--<2014-06-22 Sun>" ~=? orgSample Date 0 3
]
, "DateTime" ~:
[ "same day" ~:
"<2014-06-21 Sat 00:00-07:00>" ~=? orgSample DateTime 0 1
, "different day" ~:
"<2014-06-21 Sat 07:00>--<2014-06-22 Sun 00:00>" ~=?
orgSample DateTime 1 2
]
]
where orgSample tc m n =
orgTimestamp (tc $ sampleTime m) (tc $ sampleTime n)
testEventToOrg = "eventToOrg" ~: org ~=? eventToOrg e
where e = Event "summary" (Just "description")
(DateTime $ sampleTime 0)
(DateTime $ sampleTime 1)
org = "** summary\n" ++
" <2014-06-21 Sat 00:00-07:00>\n" ++
"description"
tests = runTestTT $ test [ testTimeAround
, testListEventsUri
, testOrgTimestamp
, testEventToOrg
]
| Yuhta/hs-gcal2org | Test.hs | gpl-3.0 | 1,991 | 0 | 10 | 634 | 423 | 228 | 195 | 50 | 1 |
{-| Module : Args
License : GPL
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module Helium.Main.Args
( Option(..)
, processHeliumArgs
, processRunHeliumArgs
, processTexthintArgs
, lvmPathFromOptions
, basePathFromOptions
, loggerDEFAULTHOST
, simplifyOptions
, argsToOptions
, loggerDEFAULTPORT
, hostFromOptions
, portFromOptions
, overloadingFromOptions
, hasAlertOption
) where
import System.Exit
import System.FilePath
import Helium.Main.Version
import Data.Maybe
import Control.Monad(when)
import System.Console.GetOpt
import Data.Char
loggerDEFAULTHOST :: String
loggerDEFAULTHOST = "helium.zoo.cs.uu.nl"
loggerDEFAULTPORT :: Int
loggerDEFAULTPORT = 5010
unwordsBy :: String -> [String] -> String
unwordsBy _ [] = ""
unwordsBy _ [w] = w
unwordsBy sep (w:ws) = w ++ sep ++ unwordsBy sep ws
-- Keep only the last of the overloading flags and the last of the logging enable flags.
-- The alert flag overrides logging turned off.
-- This function also collects all -P flags together and merges them into one. The order of the
-- directories is the order in which they were specified.
simplifyOptions :: [Option] -> [Option]
simplifyOptions ops =
let
revdefops = reverse ops
modops = case alertMessageFromOptions revdefops of
(Just _) -> EnableLogging : revdefops -- Explicitly enable logging as well, just to be safe
Nothing -> revdefops
in
collectPaths (keepFirst [Overloading, NoOverloading] (keepFirst [EnableLogging, DisableLogging] modops)) [] []
where
-- Assumes the options are in reverse order, and also reverses them.
-- Collects several LvmPath options into one
collectPaths [] paths newops = LvmPath (unwordsBy [searchPathSeparator] paths) : newops
collectPaths (LvmPath path : rest) paths newops
= collectPaths rest (path : paths) newops
collectPaths (opt : rest) paths newops
= collectPaths rest paths (opt : newops)
keepFirst _ [] = []
keepFirst fromList (opt : rest) = if opt `elem` fromList then
opt : optionFilter fromList rest
else
opt : keepFirst fromList rest
optionFilter _ [] = []
optionFilter fromList (opt : rest) = if opt `elem` fromList then
optionFilter fromList rest
else
opt : optionFilter fromList rest
terminateWithMessage :: [Option] -> String -> [String] -> IO ([Option], Maybe String)
terminateWithMessage options message errors = do
let experimentalOptions = ExperimentalOptions `elem` options
let moreOptions = MoreOptions `elem` options || experimentalOptions
putStrLn message
putStrLn (unlines errors)
putStrLn $ "Helium compiler " ++ version
putStrLn (usageInfo "Usage: helium [options] file [options]" (optionDescription moreOptions experimentalOptions))
exitWith (ExitFailure 1)
processTexthintArgs :: [String] -> IO ([Option], Maybe String)
processTexthintArgs = basicProcessArgs []
processHeliumArgs :: [String] -> IO ([Option], Maybe String)
processHeliumArgs args = do
(options, maybeFiles) <- basicProcessArgs [DisableLogging, Overloading] args
case maybeFiles of
Nothing ->
terminateWithMessage options "Error in invocation: the name of the module to be compiled seems to be missing." []
Just _ ->
return (options, maybeFiles)
processRunHeliumArgs :: [String] -> IO ([Option], Maybe String)
processRunHeliumArgs args = do
(options, maybeFiles) <- basicProcessArgs [] args
case maybeFiles of
Nothing ->
terminateWithMessage options "Error in invocation: the name of the lvm file to be run seems to be missing." []
Just _ ->
return (options, maybeFiles)
-- Sometimes you know the options are correct. Then you can use this.
argsToOptions :: [String] -> [Option]
argsToOptions args =
let
(opts,_,_) = getOpt Permute (optionDescription True True) args
in
opts
-- The Maybe String indicates that a file may be missing. Resulting options are simplified
basicProcessArgs :: [Option] -> [String] -> IO ([Option], Maybe String)
basicProcessArgs defaults args =
let (options, arguments, errors) = getOpt Permute (optionDescription True True) args
in if not (null errors) then
terminateWithMessage options "Error in invocation: list of parameters is erroneous.\nProblem(s):"
(map (" " ++) errors)
else
if length arguments > 1 then
terminateWithMessage options ("Error in invocation: only one non-option parameter expected, but found instead:\n" ++ unlines (map (" "++) arguments)) []
else
do
let simpleOptions = simplifyOptions (defaults ++ options)
argument = if null arguments then Nothing else Just (head arguments)
when (Verbose `elem` simpleOptions) $ do
mapM_ putStrLn ("Options after simplification: " : map show simpleOptions)
putStrLn ("Argument: " ++ show argument)
return (simpleOptions, argument)
optionDescription :: Bool -> Bool -> [OptDescr Option]
optionDescription moreOptions experimentalOptions =
-- Main options
[ Option "b" [flag BuildOne] (NoArg BuildOne) "recompile module even if up to date"
, Option "B" [flag BuildAll] (NoArg BuildAll) "recompile all modules even if up to date"
, Option "i" [flag DumpInformationForThisModule] (NoArg DumpInformationForThisModule) "show information about this module"
, Option "I" [flag DumpInformationForAllModules] (NoArg DumpInformationForAllModules) "show information about all imported modules"
, Option "" [flag EnableLogging] (NoArg EnableLogging) "enable logging, overrides previous disable-logging"
, Option "" [flag DisableLogging] (NoArg DisableLogging) "disable logging (default), overrides previous enable-logging flags"
, Option "a" [flag (Alert "")] (ReqArg Alert "MESSAGE") "compiles with alert flag in logging; MESSAGE specifies the reason for the alert."
, Option "" [flag Overloading] (NoArg Overloading) "turn overloading on (default), overrides all previous no-overloading flags"
, Option "" [flag NoOverloading] (NoArg NoOverloading) "turn overloading off, overrides all previous overloading flags"
, Option "P" [flag (LvmPath "")] (ReqArg LvmPath "PATH") "use PATH as search path"
, Option "v" [flag Verbose] (NoArg Verbose) "show the phase the compiler is in"
, Option "w" [flag NoWarnings] (NoArg NoWarnings) "do notflag warnings"
, Option "X" [flag MoreOptions] (NoArg MoreOptions) "show more compiler options"
, Option "" [flag (Information "")] (ReqArg Information "NAME") "display information about NAME"
]
++
-- More options
if not moreOptions then [] else
[ Option "1" [flag StopAfterParser] (NoArg StopAfterParser) "stop after parsing"
, Option "2" [flag StopAfterStaticAnalysis] (NoArg StopAfterStaticAnalysis) "stop after static analysis"
, Option "3" [flag StopAfterTypeInferencing] (NoArg StopAfterTypeInferencing) "stop after type inferencing"
, Option "4" [flag StopAfterDesugar] (NoArg StopAfterDesugar) "stop after desugaring into Core"
, Option "t" [flag DumpTokens] (NoArg DumpTokens) "dump tokens to screen"
, Option "u" [flag DumpUHA] (NoArg DumpUHA) "pretty print abstract syntax tree"
, Option "c" [flag DumpCore] (NoArg DumpCore) "pretty print Core program"
, Option "C" [flag DumpCoreToFile] (NoArg DumpCoreToFile) "write Core program to file"
, Option "" [flag DebugLogger] (NoArg DebugLogger) "show logger debug information"
, Option "" [flag (Host "")] (ReqArg Host "HOST") ("specify which HOST to use for logging (default " ++ loggerDEFAULTHOST ++ ")")
, Option "" [flag (Port 0)] (ReqArg selectPort "PORT") ("select the PORT number for the logger (default: " ++ show loggerDEFAULTPORT ++ ")")
, Option "d" [flag DumpTypeDebug] (NoArg DumpTypeDebug) "debug constraint-based type inference"
, Option "W" [flag AlgorithmW] (NoArg AlgorithmW) "use bottom-up type inference algorithm W"
, Option "M" [flag AlgorithmM ] (NoArg AlgorithmM) "use folklore top-down type inference algorithm M"
, Option "" [flag DisableDirectives] (NoArg DisableDirectives) "disable type inference directives"
, Option "" [flag NoRepairHeuristics] (NoArg NoRepairHeuristics) "don't suggest program fixes"
, Option "" [flag HFullQualification] (NoArg HFullQualification) "to determine fully qualified names for Holmes"
, Option "" [flag (BasePath "")] (ReqArg BasePath "PATH") "use PATH as base path instead"
]
++
-- Experimental options
if not experimentalOptions then [] else
[ Option "" [flag ExperimentalOptions] (NoArg ExperimentalOptions) "show experimental compiler options"
, Option "" [flag KindInferencing] (NoArg KindInferencing) "perform kind inference (experimental)"
, Option "" [flag SignatureWarnings] (NoArg SignatureWarnings) "warn for too specific signatures (experimental)"
, Option "" [flag RightToLeft] (NoArg RightToLeft) "right-to-left treewalk"
, Option "" [flag NoSpreading] (NoArg NoSpreading) "do not spread type constraints (experimental)"
, Option "" [flag TreeWalkTopDown] (NoArg TreeWalkTopDown) "top-down treewalk"
, Option "" [flag TreeWalkBottomUp] (NoArg TreeWalkBottomUp) "bottom up-treewalk"
, Option "" [flag TreeWalkInorderTopFirstPre] (NoArg TreeWalkInorderTopFirstPre) "treewalk (top;upward;child)"
, Option "" [flag TreeWalkInorderTopLastPre] (NoArg TreeWalkInorderTopLastPre) "treewalk (upward;child;top)"
, Option "" [flag TreeWalkInorderTopFirstPost] (NoArg TreeWalkInorderTopFirstPost) "treewalk (top;child;upward)"
, Option "" [flag TreeWalkInorderTopLastPost] (NoArg TreeWalkInorderTopLastPost) "treewalk (child;upward;top)"
, Option "" [flag SolverSimple] (NoArg SolverSimple) "a simple constraint solver"
, Option "" [flag SolverGreedy] (NoArg SolverGreedy) "a fast constraint solver"
, Option "" [flag SolverTypeGraph] (NoArg SolverTypeGraph) "type graph constraint solver"
, Option "" [flag SolverCombination] (NoArg SolverCombination) "switches between \"greedy\" and \"type graph\""
, Option "" [flag SolverChunks] (NoArg SolverChunks) "solves chunks of constraints (default)"
, Option "" [flag UnifierHeuristics] (NoArg UnifierHeuristics) "use unifier heuristics (experimental)"
, Option "" [flag (SelectConstraintNumber 0)] (ReqArg selectCNR "CNR") "select constraint number to be reported"
, Option "" [flag NoOverloadingTypeCheck] (NoArg NoOverloadingTypeCheck) "disable overloading errors (experimental)"
, Option "" [flag NoPrelude] (NoArg NoPrelude) "do not import the prelude (experimental)"
]
data Option
-- Main options
= BuildOne | BuildAll | DumpInformationForThisModule | DumpInformationForAllModules
| DisableLogging | EnableLogging | Alert String | Overloading | NoOverloading | LvmPath String | Verbose | NoWarnings | MoreOptions
| Information String | BasePath String
-- More options
| StopAfterParser | StopAfterStaticAnalysis | StopAfterTypeInferencing | StopAfterDesugar
| DumpTokens | DumpUHA | DumpCore | DumpCoreToFile
| DebugLogger | Host String | Port Int
| DumpTypeDebug | AlgorithmW | AlgorithmM | DisableDirectives | NoRepairHeuristics | HFullQualification
-- Experimental options
| ExperimentalOptions | KindInferencing | SignatureWarnings | RightToLeft | NoSpreading
| TreeWalkTopDown | TreeWalkBottomUp | TreeWalkInorderTopFirstPre | TreeWalkInorderTopLastPre
| TreeWalkInorderTopFirstPost | TreeWalkInorderTopLastPost | SolverSimple | SolverGreedy
| SolverTypeGraph | SolverCombination | SolverChunks | UnifierHeuristics
| SelectConstraintNumber Int | NoOverloadingTypeCheck | NoPrelude | UseTutor
deriving (Eq)
stripShow :: String -> String
stripShow name = tail (tail (takeWhile ('=' /=) name))
flag :: Option -> String
flag = stripShow . show
instance Show Option where
show BuildOne = "--build"
show BuildAll = "--build-all"
show DumpInformationForThisModule = "--dump-information"
show DumpInformationForAllModules = "--dump-all-information"
show EnableLogging = "--enable-logging"
show DisableLogging = "--disable-logging"
show (Alert str) = "--alert=\"" ++ str ++ "\"" -- May contain spaces
show Overloading = "--overloading"
show NoOverloading = "--no-overloading"
show (LvmPath str) = "--lvmpath=\"" ++ str ++ "\"" -- May contain spaces
show (BasePath str) = "--basepath=\"" ++ str ++ "\"" -- May contain spaces
show Verbose = "--verbose"
show NoWarnings = "--no-warnings"
show MoreOptions = "--moreoptions"
show (Information str) = "--info=" ++ str
show StopAfterParser = "--stop-after-parsing"
show StopAfterStaticAnalysis = "--stop-after-static-analysis"
show StopAfterTypeInferencing = "--stop-after-type-inferencing"
show StopAfterDesugar = "--stop-after-desugaring"
show DumpTokens = "--dump-tokens"
show DumpUHA = "--dump-uha"
show DumpCore = "--dump-core"
show DumpCoreToFile = "--save-core"
show DebugLogger = "--debug-logger"
show (Host host) = "--host=" ++ host
show (Port port) = "--port=" ++ show port
show DumpTypeDebug = "--type-debug"
show AlgorithmW = "--algorithm-w"
show AlgorithmM = "--algorithm-m"
show DisableDirectives = "--no-directives"
show NoRepairHeuristics = "--no-repair-heuristics"
show ExperimentalOptions = "--experimental-options"
show KindInferencing = "--kind-inferencing"
show SignatureWarnings = "--signature-warnings"
show RightToLeft = "--right-to-left"
show NoSpreading = "--no-spreading"
show TreeWalkTopDown = "--treewalk-topdown"
show TreeWalkBottomUp = "--treewalk-bottomup"
show TreeWalkInorderTopFirstPre = "--treewalk-inorder1"
show TreeWalkInorderTopLastPre = "--treewalk-inorder2"
show TreeWalkInorderTopFirstPost = "--treewalk-inorder3"
show TreeWalkInorderTopLastPost = "--treewalk-inorder4"
show SolverSimple = "--solver-simple"
show SolverGreedy = "--solver-greedy"
show SolverTypeGraph = "--solver-typegraph"
show SolverCombination = "--solver-combination"
show SolverChunks = "--solver-chunks"
show UnifierHeuristics = "--unifier-heuristics"
show (SelectConstraintNumber cnr) = "--select-cnr=" ++ show cnr
show HFullQualification = "--H-fullqualification"
show NoOverloadingTypeCheck = "--no-overloading-typecheck"
show NoPrelude = "--no-prelude"
show UseTutor = "--use-tutor"
basePathFromOptions :: [Option] -> Maybe String
basePathFromOptions [] = Nothing
basePathFromOptions (BasePath s : _) = Just s
basePathFromOptions (_ : rest) = basePathFromOptions rest
lvmPathFromOptions :: [Option] -> Maybe String
lvmPathFromOptions [] = Nothing
lvmPathFromOptions (LvmPath s : _) = Just s
lvmPathFromOptions (_ : rest) = lvmPathFromOptions rest
-- Assumes removed duplicates!
overloadingFromOptions :: [Option] -> Bool
overloadingFromOptions [] = error "Internal error in Args.overloadingFromOptions"
overloadingFromOptions (Overloading:_) = True
overloadingFromOptions (NoOverloading:_) = False
overloadingFromOptions (_:rest) = overloadingFromOptions rest
-- Takes the first in the list. Better to remove duplicates!
hostFromOptions :: [Option] -> Maybe String
hostFromOptions [] = Nothing
hostFromOptions (Host s : _) = Just s
hostFromOptions (_ : rest) = hostFromOptions rest
-- Takes the first in the list. Better to remove duplicates!
portFromOptions :: [Option] -> Maybe Int
portFromOptions [] = Nothing
portFromOptions (Port pn: _) = Just pn
portFromOptions (_ : rest) = portFromOptions rest
-- Extracts the alert message. Returns Nothing if such is not present.
alertMessageFromOptions :: [Option] -> Maybe String
alertMessageFromOptions [] = Nothing
alertMessageFromOptions (Alert message: _) = Just message
alertMessageFromOptions (_ : rest) = alertMessageFromOptions rest
hasAlertOption :: [Option] -> Bool
hasAlertOption = isJust . alertMessageFromOptions
selectPort :: String -> Option
selectPort pn
| all isDigit pn = Port (read ('0':pn))
| otherwise = Port (-1) -- problem with argument
selectCNR :: String -> Option
selectCNR s
| all isDigit s = SelectConstraintNumber (read ('0':s))
| otherwise = SelectConstraintNumber (-1) -- problem with argument
| roberth/uu-helium | src/Helium/Main/Args.hs | gpl-3.0 | 18,762 | 0 | 17 | 5,372 | 3,946 | 2,045 | 1,901 | 263 | 8 |
module Data.Automaton where
data Automaton state input output = Automaton
{ initialState :: state
, transitions :: [(state,input,state,output)]
} deriving (Eq,Show)
| svenkeidel/hsedit | src/Data/Automaton.hs | gpl-3.0 | 173 | 0 | 10 | 29 | 56 | 36 | 20 | 5 | 0 |
module Main where
import Utils.All
import Assets
import Lib
import Repl
import ArgumentParser
import System.Environment
import System.IO
import Data.Char
import Data.List
import Control.Monad
versionCount = [0,2,0,4]
versionMessage = "Hi Reddit! Stuff should actually work now..."
version = (versionCount, versionMessage)
main :: IO ()
main = do args <- getArgs
args' <- parseArgs version args
when (get dumpTemplate args') $ do
writeFile "Template.language" Assets._Resources_Template_language
putStrLn "Template/Tutorial was written as Template.language in the current directory"
get replOpts args' & ifJust (\opts ->
do let fp = get replPath opts
let modul = get replModule opts
let modul' = if ".language" `isSuffixOf` modul then take (length modul - 9) modul else modul
repl fp (uncalate '.' modul'))
| pietervdvn/ALGT2 | app/Main.hs | gpl-3.0 | 844 | 21 | 9 | 152 | 256 | 140 | 116 | 25 | 2 |
{-# LANGUAGE Arrows #-}
module SIRTests
( sirPropTests
) where
import Data.List
import Data.Maybe
import Data.Void
import FRP.Yampa
import Test.Tasty
import Test.Tasty.QuickCheck as QC
import SIR.SIR
import SIR.Utils
import StatsUtils
import Debug.Trace
instance Arbitrary SIRState where
-- arbitrary :: Gen SIRState
arbitrary = elements [Susceptible, Infected, Recovered]
paramContactRate :: Double
paramContactRate = 5.0
paramInfectivity :: Double
paramInfectivity = 0.05
paramIllnessDuration :: Double
paramIllnessDuration = 15.0
sirPropTests :: RandomGen g
=> g
-> TestTree
sirPropTests g
= testGroup "SIR Simulation Tests" [ test_agent_behaviour_quickgroup g]
test_agent_behaviour_quickgroup :: RandomGen g
=> g
-> TestTree
test_agent_behaviour_quickgroup g
= testGroup "agent behaviour"
[ QC.testProperty "susceptible behaviour = infection rate" (prop_infection_rate g)
--, QC.testProperty "infected behaviour = average duration" (prop_avg_duration g)
--, QC.testProperty "infected behaviour = recovery rate" (prop_recovery_rate g)
]
-- | Testing behaviour of susceptible agent
-- a susceptible agent makes on average contact
-- with contact rate other agents per time-unit
-- => when running N susceptible agents for 1.0
-- time-unit then
-- N * infectivity * contactRate * (infectedAgentsCount / totalAgentsCount)
-- agents should become infected
-- NOTE: this also allows to estimate the dt: to
-- achieve a sufficiently close match one selects
-- a very small epsilon and then reduces the dt
-- until the average falls into the epsilon environment
-- NOTE: this is black-box verification
prop_infection_rate :: RandomGen g
=> g
-> [SIRState]
-> Bool
prop_infection_rate g0 as
-- in case of nothing, there is no variance in the rate-samples and all are the same
-- thus we assume that it is equal the target-rate and simply take the first element
| isNothing tTestRet = head irs == targetRate
-- t-test resulted in Just
| otherwise = if fromJust tTestRet
then trace ("PASS! as = " ++ show as ++ "\nirs = " ++ show irs ++ "\ntargetRate = " ++ show targetRate) True
else trace ("FAIL! as = " ++ show as ++ "\nirs = " ++ show irs ++ "\ntargetRate = " ++ show targetRate) False
where
-- we have n other agents, each in one of the states
-- this means, that this susceptible agent will pick
-- on average an Infected with a probability of 1/n
otherAgentsCount = length as
infOtherAgents = length $ filter (Infected==) as
infToNonInfRatio
-- prevent division by zero
= if 0 == otherAgentsCount
then 0
else fromIntegral infOtherAgents / fromIntegral otherAgentsCount
-- multiply with contactRate because we make on
-- average contact with contactRate other agents
-- per time-unit (we are running the agent for
-- 1.0 time-unit)
-- also multiply with ratio of infected to non-infected
-- NOTE: this is actually the recovery-rate formula from SD!
infectivity = paramInfectivity
contactRate = paramContactRate
targetRate = infectivity * contactRate * infToNonInfRatio
reps = 100
(rngs, _) = rngSplits g0 reps []
irs = map infectionRateRun rngs
confidence = 0.95
-- perform a 1-sided test because we test the difference of the rates
-- tTestRet = tTest "infection rate" irs 0.05 (1 - confidence) LT
-- perform a 2-sided test because we test if the means are statistically equal
-- put in other words: if the difference of the means is statistically insignificant
tTestRet = tTest "infection rate" irs targetRate (1 - confidence) EQ
infectionRateRun :: RandomGen g
=> g
-> Double
infectionRateRun gRun = infRatio -- abs (targetRate - infRatio)
where
repls = 100
dt = 0.01
inf = infectionRateRunAux gRun repls 0
infRatio = fromIntegral inf / fromIntegral repls
infectionRateRunAux :: RandomGen g
=> g
-> Int
-> Int
-> Int
infectionRateRunAux _ 0 countInf = countInf
infectionRateRunAux g n countInf
= infectionRateRunAux g'' (n-1) countInf'
where
(g', g'') = split g
stepsCount = floor (1.0 / dt)
steps = replicate stepsCount (dt, Nothing)
ret = embed (testSusceptibleSF as g') ((), steps)
gotInfected = True `elem` ret
countInf' = if gotInfected then countInf + 1 else countInf
testSusceptibleSF :: RandomGen g
=> [SIRState]
-> g
-> SF () Bool
testSusceptibleSF otherAgents g = proc _ -> do
ret <- susceptibleAgent paramContactRate paramInfectivity paramIllnessDuration g -< otherAgents
case ret of
Susceptible -> returnA -< False
Infected -> returnA -< True
Recovered -> returnA -< False -- TODO: should never occur, can we test this? seems not so, but we can pretty easily guarantee it due to simplicity of code
-- | Testing behaviour of infected agent
-- run test until agent recovers, which happens
-- on average after illnessDuration
-- we are running this test a larger number of
-- times N and averaging the durations of all
-- agents until their recovery
-- should be within an epsilon of illnessDuration
-- NOTE: this is black-box verification
_prop_avg_duration :: RandomGen g
=> g
-> [SIRState]
-> Bool
_prop_avg_duration g0 as = diff <= eps
where
repls = 10000
eps = 0.5
dt = 0.25
diff = testInfected
testInfected :: Double -- ^ difference to target
testInfected = abs (target - durationsAvg)
where
durations = testInfectedAux g0 repls []
durationsAvg = sum durations / fromIntegral (length durations)
target = paramIllnessDuration
testInfectedAux :: RandomGen g
=> g
-> Int
-> [Double]
-> [Double]
testInfectedAux _ 0 acc = acc
testInfectedAux g n acc
= testInfectedAux g'' (n-1) acc'
where
(g', g'') = split g
steps = repeat (dt, Nothing)
evts = embed (testInfectedSF g' as) ((), steps)
-- assumption about implementation: there will always be an event, testInfectedSF will eventuall return an event
(Event t) = fromJust $ find isEvent evts
acc' = t : acc
_prop_recovery_rate :: RandomGen g
=> g
-> Bool
_prop_recovery_rate g0 = trace ("target = " ++ show target ++ " actual = " ++ show actual) diff <= eps
where
inf = 10000
repls = 100 :: Int
eps = 0.5
dt = 0.1
actuals = testInfected g0 repls []
avgActuals = fromIntegral (sum actuals) / fromIntegral (length actuals)
-- TODO: maybe a t-test?
target = fromIntegral inf / paramIllnessDuration
actual = avgActuals / paramIllnessDuration
diff = abs (target - actual)
testInfected :: RandomGen g
=> g
-> Int
-> [Int]
-> [Int]
testInfected _ 0 acc = acc
testInfected g n acc = testInfected g'' (n-1) acc'
where
(g', g'') = split g
recCount = testInfectedAux g' inf 0
acc' = recCount : acc
testInfectedAux :: RandomGen g
=> g
-> Int
-> Int
-> Int
testInfectedAux _ 0 countRec = countRec
testInfectedAux ga i countRec
= testInfectedAux ga'' (i-1) countRec'
where
(ga', ga'') = split ga
stepsCount = floor (1.0 / dt)
steps = replicate stepsCount (dt, Nothing)
evts = embed (testInfectedSF ga' []) ((), steps)
recovered = isJust $ find isEvent evts
countRec' = if recovered then countRec + 1 else countRec
testInfectedSF :: RandomGen g
=> g
-> [SIRState]
-> SF () (Event Time)
testInfectedSF g otherAgents = proc _ -> do
-- note that the otheragents are fed into the infected agents
-- but that they are ignored for checking whether the test
-- has failed or not. from this we can infer, that they
-- don't play a role in the infected agents behaviour at all
ret <- infectedAgent paramIllnessDuration g -< otherAgents
t <- time -< ()
case ret of
Susceptible -> returnA -< NoEvent -- TODO: should never occur, can we test this? seems not so, but we can pretty easily guarantee it due to simplicity of code
Infected -> returnA -< NoEvent
Recovered -> returnA -< Event t
-- | Testing behaviour of recovered agent
-- A correct recovered agent will stay recovered
-- forever, which cannot be tested through
-- computation. We can reason that it is correct
-- simply by looking at the code, which
-- is so simple (1 line) that it is correct
-- by definition: its basically a constant function
-- We indicated by Void and undefined that this
-- test does not make sense.
_testCaseRecovered :: Void
_testCaseRecovered = undefined | thalerjonathan/phd | public/propabs/sir/src/test/SIRTests.hs | gpl-3.0 | 9,716 | 2 | 14 | 3,139 | 1,711 | 915 | 796 | 164 | 5 |
-- | Sugared evaluation results
{-# LANGUAGE TemplateHaskell #-}
module Lamdu.Sugar.Types.Eval
( EvalScopes
, ParamScopes, EvaluationScopes
, ScopeId
, ER.EvalTypeError(..)
, ER.CompiledErrorType(..)
, ER._DependencyTypeOutOfDate, ER._ReachedHole, ER._UnhandledCase
, ER.Error(..), ER._CompiledError, ER._RuntimeError
, EvalException(..), evalExceptionType, evalExceptionJumpTo
, EvalCompletionResult(..), _EvalSuccess, _EvalError
, EvalCompletion
, ResRecord(..), recordFields
, ResTable(..), rtHeaders, rtRows
, ResTree(..), rtRoot, rtSubtrees
, ResList(..), rsHead
, ResInject(..), riTag, riVal
, ResBody(..)
, _RRecord, _RInject, _RFunc, _RArray, _RError, _RBytes, _RFloat
, _RList, _RTree, _RText
, ResVal(..), resPayload, resBody
) where
import qualified Control.Lens as Lens
import Data.CurAndPrev (CurAndPrev)
import Lamdu.Data.Anchors (BinderParamScopeId)
import Lamdu.Eval.Results (ScopeId)
import qualified Lamdu.Eval.Results as ER
import Lamdu.Sugar.EntityId (EntityId)
import Lamdu.Sugar.Types.Tag
import Lamdu.Prelude
newtype ResRecord name v = ResRecord
{ _recordFields :: [(Tag name, v)]
} deriving stock (Functor, Foldable, Traversable, Generic)
data ResInject name v = ResInject
{ _riTag :: Tag name
, _riVal :: Maybe v
} deriving (Functor, Foldable, Traversable, Generic)
data ResTree v = ResTree
{ _rtRoot :: v
, _rtSubtrees :: [v]
} deriving (Functor, Foldable, Traversable, Generic)
data ResTable name v = ResTable
{ _rtHeaders :: [Tag name]
, _rtRows :: [[v]] -- All rows are same length as each other and the headers
} deriving (Functor, Foldable, Traversable, Generic)
newtype ResList v = ResList
{ _rsHead :: v
} deriving stock (Functor, Foldable, Traversable, Generic)
data ResBody name v
= RRecord (ResRecord name v)
| RInject (ResInject name v)
| RFunc Int -- Identifier for function instance
| RArray [v] -- TODO: Vector here?
| RError ER.EvalTypeError
| RBytes ByteString
| RFloat Double
-- Sugared forms:
| RTable (ResTable name v)
| RList (ResList v)
| RTree (ResTree v)
| RText Text
deriving (Functor, Foldable, Traversable, Generic)
data ResVal name = ResVal
{ _resPayload :: EntityId
, _resBody :: ResBody name (ResVal name)
} deriving (Generic)
type EvalScopes a = CurAndPrev (Map ScopeId a)
type ParamScopes = EvalScopes [BinderParamScopeId]
-- For parameters: if there were any applies-of-lam in a parent scope,
-- even if they got no values yet, it will be `Just mempty`, which
-- will not fall back to showing the prev
-- TODO: Does this actually happen? Do we generate empty lists of
-- scope-val pairs for lams?
--
-- Values are wrapped in an "i" action to avoid unnecessarily passing on all
-- values during the names pass.
type EvaluationScopes name i = CurAndPrev (Maybe (Map ScopeId (i (ResVal name))))
data EvalException o = EvalException
{ _evalExceptionType :: ER.Error
, _evalExceptionJumpTo :: Maybe (o EntityId)
} deriving Generic
data EvalCompletionResult o
= EvalSuccess
| EvalError (EvalException o)
deriving Generic
type EvalCompletion o = CurAndPrev (Maybe (EvalCompletionResult o))
traverse Lens.makeLenses
[''EvalException, ''ResInject, ''ResRecord, ''ResList, ''ResTable, ''ResTree, ''ResVal]
<&> concat
Lens.makePrisms ''EvalCompletionResult
Lens.makePrisms ''ResBody
| Peaker/lamdu | src/Lamdu/Sugar/Types/Eval.hs | gpl-3.0 | 3,538 | 0 | 13 | 752 | 904 | 549 | 355 | -1 | -1 |
module HMeans.Common where
import Data.Clustering.Hierarchical
import qualified Data.IntSet as ISet
import qualified Data.IntMap.Strict as IMap
import qualified Data.Map.Strict as Map
import qualified Data.Vector.Unboxed as UV
newtype Partition a = Partition {getPartition :: IMap.IntMap (Cluster a)}
newtype BasicData a = BasicData {getData :: (a, Int)}
deriving Show
type DoubleList = [Double]
-- newtype DoubleVector = DoubleVector {getVector :: UV.Vector Double}
-- deriving Show
type DoubleVector = UV.Vector Double
type DoubleIntMap = IMap.IntMap Double
data Cluster a = Cluster {nPoints :: Int,
lSum :: a,
sSum :: a,
pointsIn :: ISet.IntSet,
pointsOut :: ISet.IntSet}
deriving (Eq, Ord)
data HMeansParams = HierarchicalParams {linkageType :: Linkage}
| KMeansParams {maxIters :: Int}
deriving Show
data Params = Params {nMicroClusters :: Int,
nClusters :: Int,
nDataPoints :: Int,
nDims :: Int,
hParams :: HMeansParams}
deriving Show
data DistTable = DistTable {getTable :: IMap.IntMap (Map.Map Double ISet.IntSet)}
instance (Show a) => Show (Partition a) where
show (Partition p) = "Partition:" ++ (concat $ IMap.elems $ IMap.mapWithKey showCluster p)
where
showCluster k c = "\n\tCluster #" ++ show k ++ ": " ++ show c
instance Show a => Show (Cluster a) where
show (Cluster n l _ p _) = "Cluster with " ++ show n ++ " points" -- , namely " ++ show p
| ehlemur/HMeans | src/HMeans/Common.hs | gpl-3.0 | 1,821 | 0 | 12 | 670 | 432 | 254 | 178 | 33 | 0 |
-- http://www.codewars.com/kata/52b757663a95b11b3d00062d
module WeIrDStRiNgCaSe where
import Data.Char
import Data.List.Split
toWeirdCase :: String -> String
toWeirdCase = unwords . map weirdise . words where
weirdise = concatMap f . chunksOf 2
f (x:xs) = toUpper x : map toLower xs | Bodigrim/katas | src/haskell/6-WeIrD-StRiNg-CaSe.hs | bsd-2-clause | 288 | 0 | 9 | 44 | 85 | 45 | 40 | 7 | 1 |
-- | Command line options.
module Options
(
-- * Options type
Options(..)
-- * Options parsing
, options
)
where
import Control.Applicative
import Options.Applicative
-- | Data type for command options.
data Options
= Options
{ inputFile :: FilePath -- ^ File to be compiled.
, outputFile :: Maybe FilePath -- ^ Where to put the resulting C++ code.
, addRuntime :: Bool -- ^ Whether to add the C++ runtime
-- directly.
, includeDir :: Maybe FilePath -- ^ Location of the C++ runtime.
, useGuards :: Bool -- ^ Whether to use @#include@ guards.
}
deriving (Eq, Show)
-- | The actual command line parser. All options are aggregated into
-- a single value of type 'Options'.
options :: ParserInfo Options
options = info (helper <*> opts)
( fullDesc
<> progDesc "Compile source code in INPUT into C++ template metaprogram."
)
where
opts = Options
<$> argument str
( metavar "INPUT"
<> help "Location of the source code"
)
<*> (optional . strOption)
( long "output"
<> short 'o'
<> metavar "OUTPUT"
<> help "Location of the compiled code"
)
<*> switch
( long "addruntime"
<> short 'a'
<> help "Whether to directly include the runtime"
)
<*> (optional . strOption)
( long "includedir"
<> short 'i'
<> metavar "DIR"
<> help "Location of the C++ \"runtime\""
)
<*> (fmap not . switch)
( long "noguards"
<> short 'n'
<> help "Do not add #include guards"
)
| vituscze/norri | src/Options.hs | bsd-3-clause | 1,784 | 0 | 16 | 678 | 304 | 161 | 143 | 40 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
module Control.CP.FD.OvertonFD.Sugar (
) where
import Data.Set(Set)
import qualified Data.Set as Set
import Control.CP.Debug
import Control.Mixin.Mixin
import Control.CP.Solver
import Control.CP.FD.FD
import Control.CP.FD.SimpleFD
import Data.Expr.Data
import Data.Expr.Sugar
-- import Control.CP.FD.Expr.Util
import Control.CP.FD.Model
import Control.CP.FD.Graph
import Control.CP.FD.OvertonFD.OvertonFD
newVars :: Term s t => Int -> s [t]
newVars 0 = return []
newVars n = do
l <- newVars $ n-1
n <- newvar
return $ n:l
instance FDSolver OvertonFD where
type FDIntTerm OvertonFD = FDVar
type FDBoolTerm OvertonFD = FDVar
type FDIntSpec OvertonFD = FDVar
type FDBoolSpec OvertonFD = FDVar
type FDColSpec OvertonFD = [FDVar]
type FDIntSpecType OvertonFD = ()
type FDBoolSpecType OvertonFD = ()
type FDColSpecType OvertonFD = ()
fdIntSpec_const (Const i) = ((),do
v <- newvar
add $ OHasValue v $ fromInteger i
return v)
fdIntSpec_term i = ((),return i)
fdBoolSpec_const (BoolConst i) = ((),do
v <- newvar
add $ OHasValue v $ if i then 1 else 0
return v)
fdBoolSpec_term i = ((),return i)
fdColSpec_list l = ((),return l)
fdColSpec_size (Const s) = ((),newVars $ fromInteger s)
fdColSpec_const l = ((),error "constant collections not yet supported by overton interface")
fdColInspect = return
fdSpecify = specify <@> simple_fdSpecify
fdProcess = process <@> simple_fdProcess
fdEqualInt v1 v2 = addFD $ OSame v1 v2
fdEqualBool v1 v2 = addFD $ OSame v1 v2
fdEqualCol v1 v2 = do
if length v1 /= length v2
then setFailed
else sequence_ $ zipWith (\a b -> addFD $ OSame a b) v1 v2
fdIntVarSpec = return . Just
fdBoolVarSpec = return . Just
fdSplitIntDomain b = do
d <- fd_domain b
return $ (map (b `OHasValue`) d, True)
fdSplitBoolDomain b = do
d <- fd_domain b
return $ (map (b `OHasValue`) $ filter (\x -> x==0 || x==1) d, True)
-- processBinary :: (EGVarId,EGVarId,EGVarId) -> (FDVar -> FDVar -> FDVar -> OConstraint) -> FDInstance OvertonFD ()
processBinary (v1,v2,va) f = addFD $ f (getDefIntSpec v1) (getDefIntSpec v2) (getDefIntSpec va)
-- processUnary :: (EGVarId,EGVarId) -> (FDVar -> FDVar -> OConstraint) -> FDInstance OvertonFD ()
processUnary (v1,va) f = addFD $ f (getDefIntSpec v1) (getDefIntSpec va)
specify :: Mixin (SpecFn OvertonFD)
specify s t edge = case (debug ("overton-specify("++(show edge)++")") edge) of
EGEdge { egeCons = EGChannel, egeLinks = EGTypeData { intData=[i], boolData=[b] } } ->
([(1000,b,True,do
s <- getIntSpec i
case s of
Just ss -> return $ SpecResSpec ((),return (ss,Nothing))
_ -> return SpecResNone
)],[(1000,i,True,do
s <- getBoolSpec b
case s of
Just ss -> return $ SpecResSpec ((),return (ss,Nothing))
_ -> return SpecResNone
)],[])
_ -> s edge
-- process :: Mixin (EGEdge -> FDInstance OvertonFD ())
process s t con info = case (con,info) of
(EGIntValue c, ([],[a],[])) -> case c of
Const v -> addFD $ OHasValue (getDefIntSpec a) (fromInteger v)
_ -> error "Overton solver does not support parametrized values"
(EGPlus, ([],[a,b,c],[])) -> processBinary (b,c,a) OAdd
(EGMinus, ([],[a,b,c],[])) -> processBinary (a,c,b) OAdd
(EGMult, ([],[a,b,c],[])) -> processBinary (b,c,a) OMult
(EGAbs, ([],[a,b],[])) -> processUnary (b,a) OAbs
(EGDiff, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ ODiff (getDefIntSpec a) (getDefIntSpec b)
(EGLess True, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ OLess (getDefIntSpec a) (getDefIntSpec b)
(EGLess False, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ OLessEq (getDefIntSpec a) (getDefIntSpec b)
(EGEqual, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ OSame (getDefIntSpec a) (getDefIntSpec b)
_ -> s con info
| neothemachine/monadiccp | src/Control/CP/FD/OvertonFD/Sugar.hs | bsd-3-clause | 4,046 | 0 | 20 | 822 | 1,669 | 905 | 764 | 90 | 11 |
module Tests.WebTest
(tests)
where
import Test.HUnit
import qualified Data.DataHandler
import qualified Service.ServiceHandler
import qualified Configuration.Util
import qualified Service.Users
import qualified Web.WebHandler
import qualified Web.WebHelper
import Control.Monad.Trans.Resource
import Data.ByteString.Lazy.UTF8
import Blaze.ByteString.Builder
import Data.Conduit
import Network.Wai
tests = TestList [
TestLabel "web to service to database test"
$ TestCase $ do
Just configuration <- Configuration.Util.readConfiguration "Configuration.yaml"
configurationTVar <- Data.DataHandler.setupDataMonad configuration
serviceConfiguration <- Service.ServiceHandler.setupServiceMonad configuration configurationTVar
webConfiguration <- Web.WebHandler.setupHandlerMonad configuration serviceConfiguration
let handler = do
Web.WebHandler.renderView $ Web.WebHelper.toBuilder ["One","Two"]
ResponseBuilder _ _ returnValue <- runResourceT $ Web.WebHandler.handleMonadWithConfiguration webConfiguration handler
assertEqual "Return value" (toLazyByteString returnValue) (fromString "OneTwo")
] | stevechy/HaskellCakeStore | Tests/WebTest.hs | bsd-3-clause | 1,143 | 0 | 17 | 145 | 242 | 130 | 112 | 25 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program
-- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This provides an abstraction which deals with configuring and running
-- programs. A 'Program' is a static notion of a known program. A
-- 'ConfiguredProgram' is a 'Program' that has been found on the current
-- machine and is ready to be run (possibly with some user-supplied default
-- args). Configuring a program involves finding its location and if necessary
-- finding its version. There is also a 'ProgramConfiguration' type which holds
-- configured and not-yet configured programs. It is the parameter to lots of
-- actions elsewhere in Cabal that need to look up and run programs. If we had
-- a Cabal monad, the 'ProgramConfiguration' would probably be a reader or
-- state component of it.
--
-- The module also defines all the known built-in 'Program's and the
-- 'defaultProgramConfiguration' which contains them all.
--
-- One nice thing about using it is that any program that is
-- registered with Cabal will get some \"configure\" and \".cabal\"
-- helpers like --with-foo-args --foo-path= and extra-foo-args.
--
-- There's also good default behavior for trying to find \"foo\" in
-- PATH, being able to override its location, etc.
--
-- There's also a hook for adding programs in a Setup.lhs script. See
-- hookedPrograms in 'Distribution.Simple.UserHooks'. This gives a
-- hook user the ability to get the above flags and such so that they
-- don't have to write all the PATH logic inside Setup.lhs.
module Distribution.Simple.Program (
-- * Program and functions for constructing them
Program(..)
, simpleProgram
, findProgramLocation
, findProgramVersion
-- * Configured program and related functions
, ConfiguredProgram(..)
, programPath
, ProgArg
, ProgramLocation(..)
, runProgram
, getProgramOutput
-- * Program invocations
, ProgramInvocation(..)
, emptyProgramInvocation
, simpleProgramInvocation
, programInvocation
, runProgramInvocation
, getProgramInvocationOutput
-- * The collection of unconfigured and configured progams
, builtinPrograms
-- * The collection of configured programs we can run
, ProgramConfiguration
, emptyProgramConfiguration
, defaultProgramConfiguration
, restoreProgramConfiguration
, addKnownProgram
, addKnownPrograms
, lookupKnownProgram
, knownPrograms
, userSpecifyPath
, userSpecifyPaths
, userMaybeSpecifyPath
, userSpecifyArgs
, userSpecifyArgss
, userSpecifiedArgs
, lookupProgram
, updateProgram
, configureProgram
, configureAllKnownPrograms
, reconfigurePrograms
, requireProgram
, requireProgramVersion
, runDbProgram
, getDbProgramOutput
-- * Programs that Cabal knows about
, ghcProgram
, ghcPkgProgram
, gccProgram
, ranlibProgram
, arProgram
, stripProgram
, happyProgram
, alexProgram
, hsc2hsProgram
, c2hsProgram
, cpphsProgram
, hscolourProgram
, haddockProgram
, greencardProgram
, ldProgram
, tarProgram
, touchProgram
, ibtoolProgram
, cppProgram
, pkgConfigProgram
, hpcProgram
-- * deprecated
, rawSystemProgram
, rawSystemProgramStdout
, rawSystemProgramConf
, rawSystemProgramStdoutConf
, findProgramOnPath
) where
import Distribution.Simple.Program.Types
import Distribution.Simple.Program.Run
import Distribution.Simple.Program.Db
import Distribution.Simple.Program.Builtin
import Distribution.Simple.Utils
( die, findProgramLocation, findProgramVersion )
import Distribution.Verbosity
( Verbosity )
-- | Runs the given configured program.
--
runProgram :: Verbosity -- ^Verbosity
-> ConfiguredProgram -- ^The program to run
-> [ProgArg] -- ^Any /extra/ arguments to add
-> IO ()
runProgram verbosity prog args =
runProgramInvocation verbosity (programInvocation prog args)
-- | Runs the given configured program and gets the output.
--
getProgramOutput :: Verbosity -- ^Verbosity
-> ConfiguredProgram -- ^The program to run
-> [ProgArg] -- ^Any /extra/ arguments to add
-> IO String
getProgramOutput verbosity prog args =
getProgramInvocationOutput verbosity (programInvocation prog args)
-- | Looks up the given program in the program database and runs it.
--
runDbProgram :: Verbosity -- ^verbosity
-> Program -- ^The program to run
-> ProgramDb -- ^look up the program here
-> [ProgArg] -- ^Any /extra/ arguments to add
-> IO ()
runDbProgram verbosity prog programDb args =
case lookupProgram prog programDb of
Nothing -> die notFound
Just configuredProg -> runProgram verbosity configuredProg args
where
notFound = "The program " ++ programName prog
++ " is required but it could not be found"
-- | Looks up the given program in the program database and runs it.
--
getDbProgramOutput :: Verbosity -- ^verbosity
-> Program -- ^The program to run
-> ProgramDb -- ^look up the program here
-> [ProgArg] -- ^Any /extra/ arguments to add
-> IO String
getDbProgramOutput verbosity prog programDb args =
case lookupProgram prog programDb of
Nothing -> die notFound
Just configuredProg -> getProgramOutput verbosity configuredProg args
where
notFound = "The program " ++ programName prog
++ " is required but it could not be found"
---------------------
-- Deprecated aliases
--
rawSystemProgram :: Verbosity -> ConfiguredProgram
-> [ProgArg] -> IO ()
rawSystemProgram = runProgram
rawSystemProgramStdout :: Verbosity -> ConfiguredProgram
-> [ProgArg] -> IO String
rawSystemProgramStdout = getProgramOutput
rawSystemProgramConf :: Verbosity -> Program -> ProgramConfiguration
-> [ProgArg] -> IO ()
rawSystemProgramConf = runDbProgram
rawSystemProgramStdoutConf :: Verbosity -> Program -> ProgramConfiguration
-> [ProgArg] -> IO String
rawSystemProgramStdoutConf = getDbProgramOutput
type ProgramConfiguration = ProgramDb
emptyProgramConfiguration, defaultProgramConfiguration :: ProgramConfiguration
emptyProgramConfiguration = emptyProgramDb
defaultProgramConfiguration = defaultProgramDb
restoreProgramConfiguration :: [Program] -> ProgramConfiguration
-> ProgramConfiguration
restoreProgramConfiguration = restoreProgramDb
{-# DEPRECATED findProgramOnPath "use findProgramLocation instead" #-}
findProgramOnPath :: String -> Verbosity -> IO (Maybe FilePath)
findProgramOnPath = flip findProgramLocation
| IreneKnapp/Faction | libfaction/Distribution/Simple/Program.hs | bsd-3-clause | 7,075 | 0 | 10 | 1,663 | 828 | 501 | 327 | 131 | 2 |
module PolyGraph.ReadOnly.DiGraph.Properties where
import PolyGraph.ReadOnly (GMorphism(..), isValidGraphDataSet)
import PolyGraph.ReadOnly.DiGraph (DiGraph, DiEdgeSemantics(..))
import PolyGraph.Common (OPair(..), PairLike(toPair))
import qualified Data.Maybe as M
import qualified Data.Foldable as F
isValidDiGraph :: forall g v e t . DiGraph g v e t => g -> Bool
isValidDiGraph = isValidGraphDataSet (toPair . resolveDiEdge)
-- | to be valid eTrans and resolveEdge needs to commute with the vTrans ignoring the pair order
isValidMorphism :: forall v0 e0 v1 e1 . (Eq v0, Eq v1, DiEdgeSemantics e0 v0, DiEdgeSemantics e1 v1) =>
[e0] -> GMorphism v0 e0 v1 e1 -> Bool
isValidMorphism es m = M.isNothing $ F.find (isValidMorphismSingleEdge m) es
-- | NOTE UOPair == is diffrent from OPair ==
-- forcing different implementation for EdgeSemantics and DiEdgeSemantics
isValidMorphismSingleEdge :: forall v0 e0 v1 e1 . (Eq v0, Eq v1, DiEdgeSemantics e0 v0, DiEdgeSemantics e1 v1) =>
GMorphism v0 e0 v1 e1 -> e0 -> Bool
isValidMorphismSingleEdge m e0 =
let OPair(v0a, v0b) = resolveDiEdge e0
e1 = eTrans m e0
in OPair(vTrans m v0a, vTrans m v0b) == resolveDiEdge e1
| rpeszek/GraphPlay | src/PolyGraph/ReadOnly/DiGraph/Properties.hs | bsd-3-clause | 1,308 | 0 | 10 | 323 | 352 | 198 | 154 | -1 | -1 |
module WorkerClient where
import Control.Monad
import qualified Data.Aeson as A
import Data.ByteString.Lazy.Char8
import Codec.Picture
import qualified Network.WebSockets as WS
import qualified Model as Model
import Job
import Message
-- import WebSocketServer
import Options.Applicative
--------------------------------------------------------------------
-- Entry point for CBaaS worker nodes
runWorker :: (Model.FromVal a, Model.ToVal b) => (a -> IO b) -> IO ()
runWorker f = WS.runClient "localhost" 9160 "/worker?name=test&function=size" $
\conn -> forever $ do
msg <- WS.receive conn
let t = case msg of
WS.DataMessage (WS.Text x) -> Just x
WS.DataMessage (WS.Binary y) -> Just y
_ -> Nothing
case A.decode =<< t of
Just (JobRequested (i, j)) -> do
print "Good decode of job request"
-- print (Model.fromVal $ _jArg j)
print "About to send to worker"
r <- f (Model.fromVal $ _jArg j)
print "Result: "
print (Model.toVal r)
WS.sendTextData conn
(A.encode $ WorkerFinished (i, (JobResult (Model.toVal r) i)))
Just x -> print $ "Good decode for unexpected message: " ++ show x
Nothing -> print $ fmap (("Bad decode of " ++) . unpack ) t
-- x -> print $ "Got non-text message: " ++ show x
| CBMM/CBaaS | cbaas-server/src/WorkerClient.hs | bsd-3-clause | 1,443 | 0 | 24 | 437 | 385 | 198 | 187 | 29 | 5 |
{-# language TemplateHaskell #-}
module Phil.Core.Kinds.KindError where
import Control.Lens
import Data.Text (unpack)
import Text.PrettyPrint.ANSI.Leijen hiding ((<$>))
import Phil.Core.AST.Identifier
import Phil.Core.Kinds.Kind
import Phil.ErrorMsg
import Phil.Typecheck.Unification
data KindError
= KVarNotDefined Ident
| KCtorNotDefined Ctor
| KUnificationError (UnificationError Kind)
deriving (Eq, Show)
makeClassyPrisms ''KindError
-- kindErrorMsg :: AsKindError e => e -> Maybe Doc
-- kindErrorMsg = previews _KindError (errorMsg "Kind error" . msgBody)
kindErrorMsg = errorMsg "Kind error" . msgBody
where
msgBody (KVarNotDefined name)
= hsep $ text <$>
[ "Variable"
, unpack $ getIdent name
, "not in scope"
]
msgBody (KCtorNotDefined name)
= hsep $ text <$>
[ "Type constructor"
, unpack $ getCtor name
, "not in scope"
]
msgBody (KUnificationError (CannotUnify k k'))
= vcat
[ hsep [text "Cannot unify", renderKind k]
, text "with"
, hsep [renderKind k']
]
msgBody (KUnificationError (Occurs var k))
= hsep
[ text "Cannot constuct infinite kind"
, squotes $ hsep [text . unpack $ getIdent var, text "=", renderKind k]
]
| LightAndLight/hindley-milner | src/Phil/Core/Kinds/KindError.hs | bsd-3-clause | 1,340 | 0 | 13 | 369 | 328 | 179 | 149 | 35 | 4 |
{-# LANGUAGE RankNTypes, NoMonomorphismRestriction, BangPatterns,
DeriveDataTypeable, GADTs, ScopedTypeVariables,
ExistentialQuantification, StandaloneDeriving #-}
{-# OPTIONS -Wall #-}
module Language.Hakaru.Metropolis where
import System.Random (RandomGen, StdGen, randomR, getStdGen)
import Data.Dynamic
import Data.Maybe
import qualified Data.Map.Strict as M
import Language.Hakaru.Types
{-
Shortcomings of this implementation
* uses parent-conditional sampling for proposal distribution
* re-evaluates entire program at every sample
* lacks way to block sample groups of variables
-}
type DistVal = Dynamic
-- and what does XRP stand for?
data XRP where
XRP :: Typeable e => (Density e, Dist e) -> XRP
unXRP :: Typeable a => XRP -> Maybe (Density a, Dist a)
unXRP (XRP (e,f)) = cast (e,f)
type Visited = Bool
type Observed = Bool
type LL = LogLikelihood
type Subloc = Int
type Name = [Subloc]
data DBEntry = DBEntry {
xrp :: XRP,
llhd :: LL,
vis :: Visited,
observed :: Observed }
type Database = M.Map Name DBEntry
data SamplerState g where
S :: { ldb :: Database, -- ldb = local database
-- (total likelihood, total likelihood of XRPs newly introduced)
llh2 :: {-# UNPACK #-} !(LL, LL),
cnds :: [Cond], -- conditions left to process
seed :: g } -> SamplerState g
type Sampler a = forall g. (RandomGen g) => SamplerState g -> (a, SamplerState g)
sreturn :: a -> Sampler a
sreturn x s = (x, s)
sbind :: Sampler a -> (a -> Sampler b) -> Sampler b
sbind s k = \ st -> let (v, s') = s st in k v s'
smap :: (a -> b) -> Sampler a -> Sampler b
smap f s = sbind s (\a -> sreturn (f a))
newtype Measure a = Measure {unMeasure :: Name -> Sampler a }
deriving (Typeable)
return_ :: a -> Measure a
return_ x = Measure $ \ _ -> sreturn x
updateXRP :: Typeable a => Name -> Cond -> Dist a -> Sampler a
updateXRP n obs dist' s@(S {ldb = db, seed = g}) =
case M.lookup n db of
Just (DBEntry xd lb _ ob) ->
let Just (xb, dist) = unXRP xd
(x,_) = case obs of
Just yd ->
let Just y = fromDynamic yd
in (y, logDensity dist y)
Nothing -> (xb, lb)
l' = logDensity dist' x
d1 = M.insert n (DBEntry (XRP (x,dist)) l' True ob) db
in (fromDensity x,
s {ldb = d1,
llh2 = updateLogLikelihood l' 0 s,
seed = g})
Nothing ->
let (xnew2, l, g2) = case obs of
Just xdnew ->
let Just xnew = fromDynamic xdnew
in (xnew, logDensity dist' xnew, g)
Nothing ->
let (xnew, g1) = distSample dist' g
in (xnew, logDensity dist' xnew, g1)
d1 = M.insert n (DBEntry (XRP (xnew2, dist')) l True (isJust obs)) db
in (fromDensity xnew2,
s {ldb = d1,
llh2 = updateLogLikelihood l l s,
seed = g2})
updateLogLikelihood :: RandomGen g =>
LL -> LL -> SamplerState g ->
(LL, LL)
updateLogLikelihood llTotal llFresh s =
let (l,lf) = llh2 s in (llTotal+l, llFresh+lf)
factor :: LL -> Measure ()
factor l = Measure $ \ _ -> \ s ->
let (llTotal, llFresh) = llh2 s
in ((), s {llh2 = (llTotal + l, llFresh)})
condition :: Eq b => Measure (a, b) -> b -> Measure a
condition (Measure m) b' = Measure $ \ n ->
let comp a b s | a /= b = s {llh2 = (log 0, 0)}
comp _ _ s = s
in sbind (m n) (\ (a, b) s -> (a, comp b b' s))
bind :: Measure a -> (a -> Measure b) -> Measure b
bind (Measure m) cont = Measure $ \ n ->
sbind (m (0:n)) (\ a -> unMeasure (cont a) (1:n))
conditioned :: Typeable a => Dist a -> Measure a
conditioned dist = Measure $ \ n ->
\s@(S {cnds = cond:conds }) ->
updateXRP n cond dist s{cnds = conds}
unconditioned :: Typeable a => Dist a -> Measure a
unconditioned dist = Measure $ \ n ->
updateXRP n Nothing dist
instance Monad Measure where
return = return_
(>>=) = bind
run :: Measure a -> [Cond] -> IO (a, Database, LL)
run (Measure prog) cds = do
g <- getStdGen
let (v, S d ll [] _) = (prog [0]) (S M.empty (0,0) cds g)
return (v, d, fst ll)
traceUpdate :: RandomGen g => Measure a -> Database -> [Cond] -> g
-> (a, Database, LL, LL, LL, g)
traceUpdate (Measure prog) d cds g = do
-- let d1 = M.map (\ (x, l, _, ob) -> (x, l, False, ob)) d
let d1 = M.map (\ s -> s { vis = False }) d
let (v, S d2 (llTotal, llFresh) [] g1) = (prog [0]) (S d1 (0,0) cds g)
let (d3, stale_d) = M.partition vis d2
let llStale = M.foldl' (\ llStale' s -> llStale' + llhd s) 0 stale_d
(v, d3, llTotal, llFresh, llStale, g1)
initialStep :: Measure a -> [Cond] ->
IO (a, Database,
LL, LL, LL, StdGen)
initialStep prog cds = do
g <- getStdGen
return $ traceUpdate prog M.empty cds g
-- TODO: Make a way of passing user-provided proposal distributions
resample :: RandomGen g => Name -> Database -> Observed -> XRP -> g ->
(Database, LL, LL, LL, g)
resample name db ob (XRP (x, dist)) g =
let (x', g1) = distSample dist g
fwd = logDensity dist x'
rvs = logDensity dist x
l' = fwd
newEntry = DBEntry (XRP (x', dist)) l' True ob
db' = M.insert name newEntry db
in (db', l', fwd, rvs, g1)
transition :: (Typeable a, RandomGen g) => Measure a -> [Cond]
-> a -> Database -> LL -> g -> [a]
transition prog cds v db ll g =
let dbSize = M.size db
-- choose an unconditioned choice
(_, uncondDb) = M.partition observed db
(choice, g1) = randomR (0, (M.size uncondDb) -1) g
(name, (DBEntry xd _ _ ob)) = M.elemAt choice uncondDb
(db', _, fwd, rvs, g2) = resample name db ob xd g1
(v', db2, llTotal, llFresh, llStale, g3) = traceUpdate prog db' cds g2
a = llTotal - ll
+ rvs - fwd
+ log (fromIntegral dbSize) - log (fromIntegral $ M.size db2)
+ llStale - llFresh
(u, g4) = randomR (0 :: Double, 1) g3 in
if (log u < a) then
v' : (transition prog cds v' db2 llTotal g4)
else
v : (transition prog cds v db ll g4)
mcmc :: Typeable a => Measure a -> [Cond] -> IO [a]
mcmc prog cds = do
(v, d, llTotal, _, _, g) <- initialStep prog cds
return $ transition prog cds v d llTotal g
sample :: Typeable a => Measure a -> [Cond] -> IO [(a, Double)]
sample prog cds = do
(v, d, llTotal, _, _, g) <- initialStep prog cds
return $ map (\ x -> (x,1)) (transition prog cds v d llTotal g)
| zaxtax/hakaru-old | Language/Hakaru/Metropolis.hs | bsd-3-clause | 6,619 | 0 | 19 | 1,981 | 2,789 | 1,484 | 1,305 | 152 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE FlexibleContexts #-}
module NetworkSim.LinkLayer
( -- * MAC
module NetworkSim.LinkLayer.MAC
-- * Link-layer exception
, LinkException (..)
-- * Ethernet Frame
, Frame (..)
, Payload ()
, OutFrame
, Destination (..)
, destinationAddr
, InFrame
-- * Hardware Port
, Port ()
, portCount
, newPort
, PortInfo (..)
-- * Network Interface Controller (NIC)
, NIC ()
, newNIC
, address
, portInfo
, connectNICs
, disconnectPort
, sendOnNIC
, receiveOnNIC
, setPromiscuity
, PortConnectHook
, setPortConnectHook
-- * Logging
, module NetworkSim.LinkLayer.Logging
-- * Utilities
, atomically'
) where
import NetworkSim.LinkLayer.MAC
import NetworkSim.LinkLayer.Logging
import qualified Data.ByteString.Lazy as LB
import Control.Concurrent.STM
import Data.Typeable
import Control.Monad.Catch
import Data.Vector (Vector)
import qualified Data.Vector as V
import Control.Monad
import Data.Maybe
import qualified Data.Text as T
import Data.Monoid
import Control.Monad.IO.Class
import Control.Monad.Trans.Control
import Control.Concurrent.Lifted (fork)
import Data.Word
data LinkException
= PortDisconnected MAC PortNum
| PortAlreadyConnected MAC PortNum
| NoFreePort MAC
| ConnectToSelf MAC
deriving (Show, Typeable)
instance Exception LinkException
type Payload = LB.ByteString
-- | A simplified representation of an Ethernet frame, assuming a
-- perfect physical layer.
data Frame a = Frame
{ destination :: !a
, source :: {-# UNPACK #-} !MAC
, payload :: !Payload
} deriving (Show)
-- | An outbound Ethernet frame.
type OutFrame = Frame MAC
data Destination
= Broadcast
| Unicast MAC
deriving (Eq, Show)
-- | Retrieve underlying MAC address of a 'Destination'.
destinationAddr
:: Destination
-> MAC
destinationAddr Broadcast
= broadcastAddr
destinationAddr (Unicast addr)
= addr
-- | An Ethernet frame with parsed destination field.
type InFrame = Frame Destination
data Port = Port
{ mate :: !(TVar (Maybe Port))
, buffer' :: !(TQueue OutFrame)
}
newPort :: STM Port
newPort
= Port <$> newTVar Nothing <*> newTQueue
data PortInfo = PortInfo
{ isConnected :: !Bool
} deriving (Show)
getPortInfo
:: Port
-> STM PortInfo
getPortInfo
= fmap (PortInfo . isJust) . readTVar . mate
-- | First arg: the local NIC being connected. Second arg: the local port being connected. Third arg: the address of the remote NIC.
type PortConnectHook = NIC -> PortNum -> MAC -> STM ()
-- | Network interface controller (NIC).
data NIC = NIC
{ mac :: {-# UNPACK #-} !MAC
, ports :: {-# UNPACK #-} !(Vector Port)
, promiscuity :: !(TVar Bool)
, buffer :: !(TQueue (PortNum, InFrame)) -- ^ Buffer of messages filtered by ports.
, portConnectHook :: !(TVar PortConnectHook) -- ^ Hook guaranteed to be executed atomically after successful 'connectNICs' action.
}
instance Eq NIC where
nic == nic'
= mac nic == mac nic'
deviceName
= "NIC"
newNIC
:: (MonadIO m, MonadBaseControl IO m, MonadLogger m)
=> Word16 -- ^ Number of ports. Pre: >= 1.
-> Bool -- ^ Initial promiscuity setting.
-> m NIC
newNIC n promis = do
mac <- liftIO freshMAC
nic <- atomically' $ NIC mac <$> V.replicateM (fromIntegral n) newPort <*> newTVar promis <*> newTQueue <*> newTVar defaultHook
V.imapM_ (\(fromIntegral -> i) p -> void . fork $ portAction nic i p) $ ports nic
return nic
where
portAction nic i p
= forever $ do
frame <- atomically' $ readTQueue (buffer' p)
let
dest
= destination frame
if
| dest == broadcastAddr ->
atomically' $ writeTQueue (buffer nic) (i, frame { destination = Broadcast })
| dest == mac nic ->
atomically' $ writeTQueue (buffer nic) (i, frame { destination = Unicast dest })
| otherwise -> do
written <- atomically' $ do
isPromiscuous <- readTVar (promiscuity nic)
when isPromiscuous $
writeTQueue (buffer nic) (i, frame { destination = Unicast dest })
return isPromiscuous
when (not written) $
recordWithPort deviceName (mac nic) i $ "Dropping frame destined for " <> (T.pack . show) dest
defaultHook _ _ _
= return ()
-- | Connect two NICs, using the first free port available for
-- each. Returns these ports.
connectNICs
:: (MonadIO m, MonadThrow m, MonadLogger m)
=> NIC
-> NIC
-> m (PortNum, PortNum)
connectNICs nic nic' = do
if nic == nic'
then
throwM $ ConnectToSelf (mac nic)
else do
ports@(portNum, portNum') <- atomically' $ do
(fromIntegral -> portNum, p) <- firstFreePort nic
(fromIntegral -> portNum', p') <- firstFreePort nic'
checkDisconnected nic portNum p
checkDisconnected nic' portNum' p'
writeTVar (mate p) (Just p')
writeTVar (mate p') (Just p)
readTVar (portConnectHook nic) >>= \f -> f nic portNum (address nic')
readTVar (portConnectHook nic') >>= \f -> f nic' portNum' (address nic)
return (portNum, portNum')
announce . T.pack $ "Connected " <> show (mac nic) <> "(" <> show portNum <> ") and " <> show (mac nic') <> "(" <> show portNum' <> ")"
return ports
where
firstFreePort nic = do
free <- V.filterM hasFreePort . V.indexed $ ports nic
if V.length free > 0
then
return $ V.head free
else
throwM $ NoFreePort (mac nic)
where
hasFreePort (_, port)
= isNothing <$> readTVar (mate port)
checkDisconnected
:: NIC
-> PortNum
-> Port
-> STM ()
checkDisconnected nic n p = do
q <- readTVar (mate p)
when (isJust q) $
throwM $ PortAlreadyConnected (mac nic) n
-- | Will throw a 'PortDisconnected' exception if the port requested port
-- is already disconnected.
disconnectPort
:: (MonadIO m, MonadLogger m)
=> NIC
-> PortNum
-> m ()
disconnectPort nic n
= case ports nic V.!? (fromIntegral n) of
Nothing ->
-- TODO: alert user to index out of bounds error?
return ()
Just p -> do
atomically' $ do
mate' <- readTVar (mate p)
case mate' of
Nothing ->
throwM $ PortDisconnected (mac nic) n
Just q -> do
-- __NOTE__: We do not check if the mate is already
-- disconnected.
writeTVar (mate q) Nothing
writeTVar (mate p) Nothing
recordWithPort deviceName (mac nic) n $ "Disconnected port"
-- | Will throw a 'PortDisconnected' exception if you try to send on a
-- disconnected port.
sendOnNIC
:: OutFrame -- ^ The source MAC here is allowed to differ from the NIC's MAC.
-> NIC
-> PortNum
-> STM ()
sendOnNIC frame nic n
= case ports nic V.!? (fromIntegral n) of
Nothing ->
-- TODO: alert user to index out of bounds error?
return ()
Just p -> do
mate' <- readTVar (mate p)
case mate' of
Nothing ->
throwM $ PortDisconnected (mac nic) n
Just q ->
writeTQueue (buffer' q) frame
-- | Wait on all ports of a NIC for the next incoming frame. This is a
-- blocking method. Behaviour is affected by the NIC's promiscuity
-- setting (see 'setPromiscuity').
receiveOnNIC
:: NIC
-> STM (PortNum, InFrame)
receiveOnNIC
= readTQueue . buffer
-- | Toggle promiscuous mode for a 'NIC'. When promiscuous, a NIC will
-- not drop the frames destined for another NIC. This is a useful
-- operating mode for, e.g. switches.
setPromiscuity
:: (MonadIO m, MonadLogger m)
=> NIC
-> Bool
-> m ()
setPromiscuity nic b = do
old <- atomically' $ swapTVar (promiscuity nic) b
when (old /= b) $
if b
then
record deviceName (mac nic) $ "Enabling promiscuity mode"
else
record deviceName (mac nic) $ "Disabling promiscuity mode"
-- | Set a hook guaranteed to be run atomically after successful
-- execution of 'connectNICs'.
setPortConnectHook
:: PortConnectHook
-> NIC
-> STM ()
setPortConnectHook h nic
= writeTVar (portConnectHook nic) h
address
:: NIC
-> MAC
address
= mac
portInfo
:: NIC
-> STM (Vector PortInfo)
portInfo
= V.mapM getPortInfo . ports
-- | @ atomically' = liftIO . atomically @
atomically'
:: MonadIO m
=> STM a
-> m a
atomically'
= liftIO . atomically
portCount
:: NIC
-> Word16
portCount
= fromIntegral . V.length . ports
| prophet-on-that/network-sim | src/NetworkSim/LinkLayer.hs | bsd-3-clause | 8,672 | 0 | 23 | 2,345 | 2,294 | 1,192 | 1,102 | -1 | -1 |
{-# LANGUAGE
OverloadedStrings
, BangPatterns
, ScopedTypeVariables
#-}
module RunTests where
import Control.Exception
import Data.Conduit
import Data.List (foldl')
import Data.Monoid ((<>))
import Data.Conduit.HDBI
import Database.HDBI
import Database.HDBI.SQlite
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
import Test.QuickCheck.Assertions
import qualified Data.Conduit.List as L
import qualified Data.Conduit.Util as U
import qualified Test.QuickCheck.Monadic as M
createTables :: SQliteConnection -> IO ()
createTables c = do
runRaw c "create table values1(val1 integer, val2 integer)"
runRaw c "create table values2(val1 integer, val2 integer)"
runRaw c "create table values3(val1 integer, val2 integer)"
allTests :: SQliteConnection -> Test
allTests c = testGroup "All tests"
[ testProperty "Insert + fold" $ insertFold c
, testProperty "Insert + copy" $ insertCopy c
, testProperty "Insert + copy + sum" $ insertCopySum c
, testProperty "Insert trans fluahAt" $ insertTransFlushAt c
, testProperty "Insert trans flushBy" $ insertTransFlushBy c
]
sumPairs :: (Num a, Num b) => (a, b) -> (a, b) -> (a, b)
sumPairs (!a, !b) (!x, !y) = (a+x, b+y)
insertTransFlushAt :: SQliteConnection -> Positive Int -> [(Integer, Integer)] -> Property
insertTransFlushAt c count vals = M.monadicIO $ do
(Just res, tr) <- M.run $ do
runRaw c "delete from values1"
runResourceT
$ L.sourceList vals
$= (flushAt $ getPositive count)
$$ insertAllTrans c "insert into values1 (val1, val2) values (?,?)"
r <- runFetchOne c "select count(*) from values1" ()
tr <- inTransaction c
return (r, tr)
_ <- M.stop $ res ?== (length vals)
M.stop $ tr ?== False
insertTransFlushBy :: SQliteConnection -> NonEmptyList Integer -> Property
insertTransFlushBy con vals = M.monadicIO $ do
(tr, r) <- M.run $ do
runRaw con "delete from values1"
runResourceT
$ L.sourceList nvals
$= flushBy signFlush
$= L.map (fmap one) -- flush is the functor
$$ insertAllTrans con "insert into values1 (val1) values (?)"
tr <- inTransaction con
Just r <- runFetchOne con "select sum(val1) from values1" ()
return (tr, r)
_ <- M.stop $ tr ?== False
M.stop $ r ?== (sum nvals)
where
nvals = getNonEmpty vals
signFlush a b = (signum a) == (signum b)
insertFold :: SQliteConnection -> [(Integer, Integer)] -> Property
insertFold c vals = M.monadicIO $ do
res <- M.run $ withTransaction c $ do
runRaw c "delete from values1"
runMany c "insert into values1(val1, val2) values (?,?)" vals
runResourceT
$ selectAll c "select val1, val2 from values1" ()
$$ L.fold sumPairs (0 :: Integer, 0 :: Integer)
M.stop $ res ?== (foldl' sumPairs (0, 0) vals)
insertCopy :: SQliteConnection -> [(Integer, Integer)] -> Property
insertCopy c vals = M.monadicIO $ do
res <- M.run $ withTransaction c $ do
runRaw c "delete from values1"
runRaw c "delete from values2"
runResourceT
$ L.sourceList vals
$$ insertAll c "insert into values1(val1, val2) values (?,?)"
runResourceT
$ selectAll c "select val1, val2 from values1" () $= asThisType (undefined :: (Int, Int))
$$ insertAllCount c "insert into values2(val1, val2) values (?,?)"
M.stop $ res == (length vals)
insertCopySum :: SQliteConnection -> [(Integer, Integer)] -> Property
insertCopySum c vals = M.monadicIO $ do
res <- M.run $ withTransaction c $ do
mapM_ (runRaw c . ("delete from " <>)) ["values1",
"values2",
"values3"]
runResourceT
$ L.sourceList vals
$$ insertAll c "insert into values1(val1, val2) values (?,?)"
runResourceT
$ selectAll c "select val1, val2 from values1" () $= asSqlVals
$$ insertAll c "insert into values2(val1, val2) values (?,?)"
runResourceT
$ (U.zip
(selectAll c "select val1, val2 from values1" ())
(selectAll c "select val1, val2 from values2" ()))
$= L.map (\(a, b :: (Integer, Integer)) -> sumPairs a b)
$$ insertAll c "insert into values3(val1, val2) values (?,?)"
runResourceT
$ selectAll c "select val1, val2 from values3" ()
$$ L.fold sumPairs (0 :: Integer, 0 :: Integer)
let (a, b) = foldl' sumPairs (0, 0) vals
M.stop $ (a*2, b*2) ==? res
main :: IO ()
main = bracket (connectSqlite3 ":memory:") disconnect $ \c -> do
createTables c
defaultMain [allTests c]
| s9gf4ult/hdbi-conduit | testsrc/runtests.hs | bsd-3-clause | 4,603 | 0 | 19 | 1,109 | 1,402 | 707 | 695 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
module Real.Types (module Real.Types, Version(..)) where
import GHC.Generics
newtype InstalledPackageId = InstalledPackageId String
deriving (Eq, Ord, Generic)
newtype PackageName = PackageName String
deriving (Eq, Ord, Generic)
data Version = Version [Int] [String]
deriving (Eq, Ord, Generic)
data PackageId = PackageId {
pkgName :: PackageName, -- ^The name of this package, eg. foo
pkgVersion :: Version -- ^the version of this package, eg 1.2
}
deriving (Eq, Ord, Generic)
newtype ModuleName = ModuleName [String]
deriving (Eq, Ord, Generic)
data License =
GPL (Maybe Version)
| AGPL (Maybe Version)
| LGPL (Maybe Version)
| BSD3
| BSD4
| MIT
| Apache (Maybe Version)
| PublicDomain
| AllRightsReserved
| OtherLicense
| UnknownLicense String
deriving (Eq, Generic)
{-
data InstalledPackageInfo = InstalledPackageInfo {
-- these parts are exactly the same as PackageDescription
installedPackageId :: InstalledPackageId,
sourcePackageId :: PackageId,
license :: License,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
homepage :: String,
pkgUrl :: String,
synopsis :: String,
description :: String,
category :: String,
-- these parts are required by an installed package only:
exposed :: Bool,
exposedModules :: [ModuleName],
hiddenModules :: [ModuleName],
trusted :: Bool,
importDirs :: [FilePath], -- contain sources in case of Hugs
libraryDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
extraGHCiLibraries:: [String], -- overrides extraLibraries for GHCi
includeDirs :: [FilePath],
includes :: [String],
depends :: [InstalledPackageId],
hugsOptions :: [String],
ccOptions :: [String],
ldOptions :: [String],
frameworkDirs :: [FilePath],
frameworks :: [String],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath]
}
deriving (Eq, Generic)
-}
data VersionRange
= AnyVersion
| ThisVersion Version -- = version
| LaterVersion Version -- > version (NB. not >=)
| EarlierVersion Version -- < version
| WildcardVersion Version -- == ver.* (same as >= ver && < ver+1)
| UnionVersionRanges VersionRange VersionRange
| IntersectVersionRanges VersionRange VersionRange
| VersionRangeParens VersionRange -- just '(exp)' parentheses syntax
deriving (Eq, Generic)
data Dependency = Dependency PackageName VersionRange
deriving (Eq, Generic)
data CompilerFlavor = GHC | NHC | YHC | Hugs | HBC | Helium | JHC | LHC | UHC
| HaskellSuite String -- string is the id of the actual compiler
| OtherCompiler String
deriving (Eq, Ord, Generic)
data SourceRepo = SourceRepo {
repoKind :: RepoKind,
repoType :: Maybe RepoType,
repoLocation :: Maybe String,
repoModule :: Maybe String,
repoBranch :: Maybe String,
repoTag :: Maybe String,
repoSubdir :: Maybe FilePath
}
deriving (Eq, Generic)
data RepoKind =
RepoHead
| RepoThis
| RepoKindUnknown String
deriving (Eq, Ord, Generic)
data RepoType = Darcs | Git | SVN | CVS
| Mercurial | GnuArch | Bazaar | Monotone
| OtherRepoType String
deriving (Eq, Ord, Generic)
data BuildType
= Simple
| Configure
| Make
| Custom
| UnknownBuildType String
deriving (Eq, Generic)
data Library = Library {
exposedModules :: [ModuleName],
libExposed :: Bool, -- ^ Is the lib to be exposed by default?
libBuildInfo :: BuildInfo
}
deriving (Eq, Generic)
data Executable = Executable {
exeName :: String,
modulePath :: FilePath,
buildInfo :: BuildInfo
}
deriving (Eq, Generic)
data TestSuite = TestSuite {
testName :: String,
testInterface :: TestSuiteInterface,
testBuildInfo :: BuildInfo,
testEnabled :: Bool
}
deriving (Eq, Generic)
data TestType = TestTypeExe Version
| TestTypeLib Version
| TestTypeUnknown String Version
deriving (Eq, Generic)
data TestSuiteInterface =
TestSuiteExeV10 Version FilePath
| TestSuiteLibV09 Version ModuleName
| TestSuiteUnsupported TestType
deriving (Eq, Generic)
data Benchmark = Benchmark {
benchmarkName :: String,
benchmarkInterface :: BenchmarkInterface,
benchmarkBuildInfo :: BuildInfo,
benchmarkEnabled :: Bool
}
deriving (Eq, Generic)
data BenchmarkType = BenchmarkTypeExe Version
| BenchmarkTypeUnknown String Version
deriving (Eq, Generic)
data BenchmarkInterface =
BenchmarkExeV10 Version FilePath
| BenchmarkUnsupported BenchmarkType
deriving (Eq, Generic)
data Language =
Haskell98
| Haskell2010
| UnknownLanguage String
deriving (Eq, Generic)
data Extension =
EnableExtension KnownExtension
| DisableExtension KnownExtension
| UnknownExtension String
deriving (Eq, Generic)
data KnownExtension =
OverlappingInstances
| UndecidableInstances
| IncoherentInstances
| DoRec
| RecursiveDo
| ParallelListComp
| MultiParamTypeClasses
| MonomorphismRestriction
| FunctionalDependencies
| Rank2Types
| RankNTypes
| PolymorphicComponents
| ExistentialQuantification
| ScopedTypeVariables
| PatternSignatures
| ImplicitParams
| FlexibleContexts
| FlexibleInstances
| EmptyDataDecls
| CPP
| KindSignatures
| BangPatterns
| TypeSynonymInstances
| TemplateHaskell
| ForeignFunctionInterface
| Arrows
| Generics
| ImplicitPrelude
| NamedFieldPuns
| PatternGuards
| GeneralizedNewtypeDeriving
| ExtensibleRecords
| RestrictedTypeSynonyms
| HereDocuments
| MagicHash
| TypeFamilies
| StandaloneDeriving
| UnicodeSyntax
| UnliftedFFITypes
| InterruptibleFFI
| CApiFFI
| LiberalTypeSynonyms
| TypeOperators
| RecordWildCards
| RecordPuns
| DisambiguateRecordFields
| TraditionalRecordSyntax
| OverloadedStrings
| GADTs
| GADTSyntax
| MonoPatBinds
| RelaxedPolyRec
| ExtendedDefaultRules
| UnboxedTuples
| DeriveDataTypeable
| DeriveGeneric
| DefaultSignatures
| InstanceSigs
| ConstrainedClassMethods
| PackageImports
| ImpredicativeTypes
| NewQualifiedOperators
| PostfixOperators
| QuasiQuotes
| TransformListComp
| MonadComprehensions
| ViewPatterns
| XmlSyntax
| RegularPatterns
| TupleSections
| GHCForeignImportPrim
| NPlusKPatterns
| DoAndIfThenElse
| MultiWayIf
| LambdaCase
| RebindableSyntax
| ExplicitForAll
| DatatypeContexts
| MonoLocalBinds
| DeriveFunctor
| DeriveTraversable
| DeriveFoldable
| NondecreasingIndentation
| SafeImports
| Safe
| Trustworthy
| Unsafe
| ConstraintKinds
| PolyKinds
| DataKinds
| ParallelArrays
| RoleAnnotations
| OverloadedLists
| EmptyCase
| AutoDeriveTypeable
| NegativeLiterals
| NumDecimals
| NullaryTypeClasses
| ExplicitNamespaces
| AllowAmbiguousTypes
deriving (Eq, Enum, Bounded, Generic)
data BuildInfo = BuildInfo {
buildable :: Bool, -- ^ component is buildable here
buildTools :: [Dependency], -- ^ tools needed to build this bit
cppOptions :: [String], -- ^ options for pre-processing Haskell code
ccOptions :: [String], -- ^ options for C compiler
ldOptions :: [String], -- ^ options for linker
pkgconfigDepends :: [Dependency], -- ^ pkg-config packages that are used
frameworks :: [String], -- ^support frameworks for Mac OS X
cSources :: [FilePath],
hsSourceDirs :: [FilePath], -- ^ where to look for the haskell module Real.hierarchy
otherModules :: [ModuleName], -- ^ non-exposed or non-main modules
defaultLanguage :: Maybe Language,-- ^ language used when not explicitly specified
otherLanguages :: [Language], -- ^ other languages used within the package
defaultExtensions :: [Extension], -- ^ language extensions used by all modules
otherExtensions :: [Extension], -- ^ other language extensions used within the package
oldExtensions :: [Extension], -- ^ the old extensions field, treated same as 'defaultExtensions'
extraLibs :: [String], -- ^ what libraries to link with when compiling a program that uses your package
extraLibDirs :: [String],
includeDirs :: [FilePath], -- ^directories to find .h files
includes :: [FilePath], -- ^ The .h files to be found in includeDirs
installIncludes :: [FilePath], -- ^ .h files to install with the package
options :: [(CompilerFlavor,[String])],
ghcProfOptions :: [String],
ghcSharedOptions :: [String],
customFieldsBI :: [(String,String)], -- ^Custom fields starting
-- with x-, stored in a
-- simple assoc-list.
targetBuildDepends :: [Dependency] -- ^ Dependencies specific to a library or executable target
}
deriving (Eq, Generic)
data PackageDescription = PackageDescription {
-- the following are required by all packages:
package :: PackageId,
license :: License,
licenseFile :: FilePath,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
testedWith :: [(CompilerFlavor,VersionRange)],
homepage :: String,
pkgUrl :: String,
bugReports :: String,
sourceRepos :: [SourceRepo],
synopsis :: String, -- ^A one-line summary of this package
description :: String, -- ^A more verbose description of this package
category :: String,
customFieldsPD :: [(String,String)], -- ^Custom fields starting
-- with x-, stored in a
-- simple assoc-list.
buildDepends :: [Dependency],
-- | The version of the Cabal spec that this package description uses.
-- For historical reasons this is specified with a version range but
-- only ranges of the form @>= v@ make sense. We are in the process of
-- transitioning to specifying just a single version, not a range.
specVersionRaw :: Either Version VersionRange,
buildType :: Maybe BuildType,
-- components
library :: Maybe Library,
executables :: [Executable],
testSuites :: [TestSuite],
benchmarks :: [Benchmark],
dataFiles :: [FilePath],
dataDir :: FilePath,
extraSrcFiles :: [FilePath],
extraTmpFiles :: [FilePath],
extraDocFiles :: [FilePath]
}
deriving (Eq, Generic)
data GenericPackageDescription =
GenericPackageDescription {
packageDescription :: PackageDescription,
genPackageFlags :: [Flag],
condLibrary :: Maybe (CondTree ConfVar [Dependency] Library),
condExecutables :: [(String, CondTree ConfVar [Dependency] Executable)],
condTestSuites :: [(String, CondTree ConfVar [Dependency] TestSuite)],
condBenchmarks :: [(String, CondTree ConfVar [Dependency] Benchmark)]
}
deriving (Eq, Generic)
data OS = Linux | Windows | OSX -- tier 1 desktop OSs
| FreeBSD | OpenBSD | NetBSD -- other free unix OSs
| Solaris | AIX | HPUX | IRIX -- ageing Unix OSs
| HaLVM -- bare metal / VMs / hypervisors
| IOS -- iOS
| OtherOS String
deriving (Eq, Ord, Generic)
data Arch = I386 | X86_64 | PPC | PPC64 | Sparc
| Arm | Mips | SH
| IA64 | S390
| Alpha | Hppa | Rs6000
| M68k | Vax
| OtherArch String
deriving (Eq, Ord, Generic)
data Flag = MkFlag
{ flagName :: FlagName
, flagDescription :: String
, flagDefault :: Bool
, flagManual :: Bool
}
deriving (Eq, Generic)
newtype FlagName = FlagName String
deriving (Eq, Ord, Generic)
type FlagAssignment = [(FlagName, Bool)]
data ConfVar = OS OS
| Arch Arch
| Flag FlagName
| Impl CompilerFlavor VersionRange
deriving (Eq, Generic)
data Condition c = Var c
| Lit Bool
| CNot (Condition c)
| COr (Condition c) (Condition c)
| CAnd (Condition c) (Condition c)
deriving (Eq, Generic)
data CondTree v c a = CondNode
{ condTreeData :: a
, condTreeConstraints :: c
, condTreeComponents :: [( Condition v
, CondTree v c a
, Maybe (CondTree v c a))]
}
deriving (Eq, Generic)
| thoughtpolice/binary-serialise-cbor | bench/Real/Types.hs | bsd-3-clause | 13,470 | 0 | 13 | 4,165 | 2,320 | 1,434 | 886 | 326 | 0 |
module Paths_CipherSolver (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version {versionBranch = [0,1,0,0], versionTags = []}
bindir, libdir, datadir, libexecdir :: FilePath
bindir = "/home/abhi/.cabal/bin"
libdir = "/home/abhi/.cabal/lib/CipherSolver-0.1.0.0/ghc-7.6.3"
datadir = "/home/abhi/.cabal/share/CipherSolver-0.1.0.0"
libexecdir = "/home/abhi/.cabal/libexec"
getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath
getBinDir = catchIO (getEnv "CipherSolver_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "CipherSolver_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "CipherSolver_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "CipherSolver_libexecdir") (\_ -> return libexecdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| abhinav-mehta/CipherSolver | dist/build/autogen/Paths_CipherSolver.hs | bsd-3-clause | 1,174 | 0 | 10 | 167 | 332 | 190 | 142 | 26 | 1 |
{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, Rank2Types #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.LinearAlgebra.Matrix.STBase
-- Copyright : Copyright (c) 2010, Patrick Perry <[email protected]>
-- License : BSD3
-- Maintainer : Patrick Perry <[email protected]>
-- Stability : asinerimental
--
module Numeric.LinearAlgebra.Matrix.STBase
where
import Control.Monad( forM_, when )
import Control.Monad.ST( ST, RealWorld, runST, unsafeInterleaveST,
unsafeIOToST )
import Data.Maybe( fromMaybe )
import Data.Typeable( Typeable )
import Foreign( Ptr, advancePtr, peek, peekElemOff, pokeElemOff,
mallocForeignPtrArray )
import Text.Printf( printf )
import Unsafe.Coerce( unsafeCoerce )
import Numeric.LinearAlgebra.Types
import qualified Foreign.BLAS as BLAS
import Numeric.LinearAlgebra.Matrix.Base hiding ( unsafeWith,
unsafeToForeignPtr, unsafeFromForeignPtr, )
import qualified Numeric.LinearAlgebra.Matrix.Base as M
import Numeric.LinearAlgebra.Vector( STVector, RVector )
import qualified Numeric.LinearAlgebra.Vector as V
-- | Mutable dense matrices in the 'ST' monad.
newtype STMatrix s e = STMatrix { unSTMatrix :: Matrix e }
deriving (Typeable)
-- | Mutable dense matrices in the 'IO' monad.
type IOMatrix = STMatrix RealWorld
-- | A safe way to create and work with a mutable matrix before returning
-- an immutable matrix for later perusal. This function avoids copying
-- the matrix before returning it - it uses 'unsafeFreeze' internally,
-- but this wrapper is a safe interface to that function.
create :: (Storable e) => (forall s . ST s (STMatrix s e)) -> Matrix e
create mx = runST $ mx >>= unsafeFreeze
{-# INLINE create #-}
-- | Converts a mutable matrix to an immutable one by taking a complete
-- copy of it.
freeze :: (RMatrix m, Storable e) => m e -> ST s (Matrix e)
freeze a = do
a' <- newCopy a
unsafeFreeze a'
{-# INLINE freeze #-}
-- | Read-only matrices
class RMatrix m where
-- | Get the dimensions of the matrix (number of rows and columns).
getDim :: (Storable e) => m e -> ST s (Int,Int)
-- | Same as 'withCol' but does not range-check index.
unsafeWithCol :: (Storable e)
=> m e
-> Int
-> (forall v. RVector v => v e -> ST s a)
-> ST s a
-- | Perform an action with a list of views of the matrix columns.
withCols :: (Storable e)
=> m e
-> (forall v . RVector v => [v e] -> ST s a)
-> ST s a
-- | Same as 'withSlice' but does not range-check index.
unsafeWithSlice :: (Storable e)
=> (Int,Int)
-> (Int,Int)
-> m e
-> (forall m'. RMatrix m' => m' e -> ST s a)
-> ST s a
-- | Possibly view a matrix as a vector and perform an action on the
-- view. This only succeeds if the matrix is stored contiguously in
-- memory, i.e. if the matrix contains a single column or the \"lda\"
-- of the matrix is equal to the number of rows.
maybeWithVector :: (Storable e)
=> m e
-> (forall v . RVector v => v e -> ST s a)
-> Maybe (ST s a)
-- | Converts a read-only matrix into an immutable matrix. This simply
-- casts the matrix from one type to the other without copying.
-- Note that because the matrix is possibly not copied, any subsequent
-- modifications made to the read-only version of the matrix may be shared
-- with the immutable version. It is safe to use, therefore, if the
-- read-only version is never modified after the freeze operation.
unsafeFreeze :: (Storable e) => m e -> ST s (Matrix e)
-- | Unsafe cast from a read-only matrix to a mutable matrix.
unsafeThaw :: (Storable e)
=> m e -> ST s (STMatrix s e)
-- | Execute an 'IO' action with a pointer to the first element in the
-- matrix and the leading dimension (lda).
unsafeWith :: (Storable e) => m e -> (Ptr e -> Int -> IO a) -> IO a
instance RMatrix Matrix where
getDim = return . dim
{-# INLINE getDim #-}
unsafeWithCol a j f = f (unsafeCol a j)
{-# INLINE unsafeWithCol #-}
withCols a f = f (cols a)
{-# INLINE withCols #-}
unsafeWithSlice ij mn a f = f (unsafeSlice ij mn a)
{-# INLINE unsafeWithSlice #-}
maybeWithVector a f | isContig a = Just $ f (toVector a)
| otherwise = Nothing
{-# INLINE maybeWithVector #-}
unsafeWith = M.unsafeWith
{-# INLINE unsafeWith #-}
unsafeFreeze = return
{-# INLINE unsafeFreeze #-}
unsafeThaw = return . STMatrix
{-# INLINE unsafeThaw #-}
instance RMatrix (STMatrix s) where
getDim = return . dim . unSTMatrix
{-# INLINE getDim #-}
unsafeWithCol = unsafeWithCol . unSTMatrix
{-# INLINE unsafeWithCol #-}
withCols = withCols . unSTMatrix
{-# INLINE withCols #-}
unsafeWithSlice ij mn = unsafeWithSlice ij mn . unSTMatrix
{-# INLINE unsafeWithSlice #-}
maybeWithVector = maybeWithVector . unSTMatrix
{-# INLINE maybeWithVector #-}
unsafeWith = unsafeWith . unSTMatrix
{-# INLINE unsafeWith #-}
unsafeFreeze = return . unSTMatrix
{-# INLINE unsafeFreeze #-}
unsafeThaw v = return $ cast v
where
cast :: STMatrix s e -> STMatrix s' e
cast = unsafeCoerce
{-# INLINE unsafeThaw #-}
-- | Perform an action with a view of a mutable matrix column
-- (no index checking).
unsafeWithColM :: (Storable e)
=> STMatrix s e
-> Int
-> (STVector s e -> ST s a)
-> ST s a
unsafeWithColM a j f =
unsafeWithCol a j $ \c -> do
mc <- V.unsafeThaw c
f mc
{-# INLINE unsafeWithColM #-}
-- | Perform an action with a list of views of the mutable matrix columns. See
-- also 'withCols'.
withColsM :: (Storable e)
=> STMatrix s e
-> ([STVector s e] -> ST s a)
-> ST s a
withColsM a f =
withCols a $ \cs -> do
mcs <- thawVecs cs
f mcs
where
thawVecs [] = return []
thawVecs (c:cs) = unsafeInterleaveST $ do
mc <- V.unsafeThaw c
mcs <- thawVecs cs
return $ mc:mcs
{-# INLINE withColsM #-}
-- | Possibly view a matrix as a vector and perform an action on the
-- view. This succeeds when the matrix is stored contiguously in memory,
-- i.e. if the matrix contains a single column or the \"lda\" of the matrix
-- is equal to the number of rows. See also 'maybeWithVector'.
maybeWithVectorM :: (Storable e)
=> STMatrix s e
-> (STVector s e -> ST s a)
-> Maybe (ST s a)
maybeWithVectorM a f =
maybeWithVector a $ \v -> do
mv <- V.unsafeThaw v
f mv
{-# INLINE maybeWithVectorM #-}
-- | View a vector as a matrix of the given shape and pass it to
-- the specified function.
withFromVector :: (RVector v, Storable e)
=> (Int,Int)
-> v e
-> (forall m . RMatrix m => m e -> ST s a)
-> ST s a
withFromVector mn@(m,n) v f = do
nv <- V.getDim v
when (nv /= m*n) $ error $
printf ("withFromVector (%d,%d) <vector with dim %d>:"
++ " dimension mismatch") m n nv
iv <- V.unsafeFreeze v
f $ fromVector mn iv
{-# INLINE withFromVector #-}
-- | View a mutable vector as a mutable matrix of the given shape and pass it
-- to the specified function.
withFromVectorM :: (Storable e)
=> (Int,Int)
-> STVector s e
-> (STMatrix s e -> ST s a)
-> ST s a
withFromVectorM mn@(m,n) v f = do
nv <- V.getDim v
when (nv /= m*n) $ error $
printf ("withFromVectorM (%d,%d) <vector with dim %d>:"
++ " dimension mismatch") m n nv
withFromVector mn v $ \a -> do
ma <- unsafeThaw a
f ma
{-# INLINE withFromVectorM #-}
-- | View a vector as a matrix with one column and pass it to
-- the specified function.
withFromCol :: (RVector v, Storable e)
=> v e
-> (forall m . RMatrix m => m e -> ST s a)
-> ST s a
withFromCol v f = do
m <- V.getDim v
withFromVector (m,1) v f
{-# INLINE withFromCol #-}
-- | View a mutable vector as a mutable matrix with one column and pass it to
-- the specified function.
withFromColM :: (Storable e)
=> STVector s e
-> (STMatrix s e -> ST s a)
-> ST s a
withFromColM v f = do
m <- V.getDim v
withFromVectorM (m, 1) v f
{-# INLINE withFromColM #-}
-- | View a vector as a matrix with one row and pass it to
-- the specified function.
withFromRow :: (RVector v, Storable e)
=> v e
-> (forall m . RMatrix m => m e -> ST s a)
-> ST s a
withFromRow v f = do
n <- V.getDim v
withFromVector (1,n) v f
{-# INLINE withFromRow #-}
-- | View a mutable vector as a mutable matrix with one row and pass it to
-- the specified function.
withFromRowM :: (Storable e)
=> STVector s e
-> (STMatrix s e -> ST s a)
-> ST s a
withFromRowM v f = do
n <- V.getDim v
withFromVectorM (1,n) v f
{-# INLINE withFromRowM #-}
-- | Perform an action with a view of a matrix column.
withCol :: (RMatrix m, Storable e)
=> m e
-> Int
-> (forall v . RVector v => v e -> ST s a)
-> ST s a
withCol a j f = do
(m,n) <- getDim a
when (j < 0 || j >= n) $ error $
printf ("withCol <matrix with dim (%d,%d)> %d:"
++ " index out of range") m n j
unsafeWithCol a j f
{-# INLINE withCol #-}
-- | Like 'withCol', but perform the action with a mutable view.
withColM :: (Storable e)
=> STMatrix s e
-> Int
-> (STVector s e -> ST s a)
-> ST s a
withColM a j f = do
(m,n) <- getDim a
when (j < 0 || j >= n) $ error $
printf ("withColM <matrix with dim (%d,%d)> %d:"
++ " index out of range") m n j
unsafeWithColM a j f
{-# INLINE withColM #-}
-- | Create a new matrix of given shape, but do not initialize the elements.
new_ :: (Storable e) => (Int,Int) -> ST s (STMatrix s e)
new_ (m,n)
| m < 0 || n < 0 = error $
printf "new_ (%d,%d): invalid dimensions" m n
| otherwise = unsafeIOToST $ do
f <- mallocForeignPtrArray (m*n)
return $ STMatrix $ M.unsafeFromForeignPtr f 0 (m,n) (max 1 m)
-- | Create a matrix with every element initialized to the same value.
new :: (Storable e) => (Int,Int) -> e -> ST s (STMatrix s e)
new (m,n) e = do
a <- new_ (m,n)
setElems a $ replicate (m*n) e
return a
-- | Creates a new matrix by copying another one.
newCopy :: (RMatrix m, Storable e) => m e -> ST s (STMatrix s e)
newCopy a = do
mn <- getDim a
b <- new_ mn
unsafeCopyTo b a
return b
-- | @copyTo dst src@ replaces the values in @dst@ with those in
-- source. The operands must be the same shape.
copyTo :: (RMatrix m, Storable e) => STMatrix s e -> m e -> ST s ()
copyTo = checkOp2 "copyTo" unsafeCopyTo
{-# INLINE copyTo #-}
-- | Same as 'copyTo' but does not range-check indices.
unsafeCopyTo :: (RMatrix m, Storable e) => STMatrix s e -> m e -> ST s ()
unsafeCopyTo = vectorOp2 V.unsafeCopyTo
{-# INLINE unsafeCopyTo #-}
-- | Get the indices of the elements in the matrix, in column-major order.
getIndices :: (RMatrix m, Storable e) => m e -> ST s [(Int,Int)]
getIndices a = do
(m,n) <- getDim a
return $ [ (i,j) | j <- [ 0..n-1 ], i <- [ 0..m-1 ] ]
-- | Lazily get the elements of the matrix, in column-major order.
getElems :: (RMatrix m, Storable e) => m e -> ST s [e]
getElems a = case maybeWithVector a V.getElems of
Just es -> es
Nothing -> withCols a $ \xs ->
concat `fmap` mapM V.getElems xs
-- | Get the elements of the matrix, in column-major order.
getElems' :: (RMatrix m, Storable e) => m e -> ST s [e]
getElems' a = case maybeWithVector a V.getElems' of
Just es -> es
Nothing -> withCols a $ \xs ->
concat `fmap` mapM V.getElems' xs
-- | Lazily get the association list of the matrix, in column-major order.
getAssocs :: (RMatrix m, Storable e) => m e -> ST s [((Int,Int),e)]
getAssocs a = do
is <- getIndices a
es <- getElems a
return $ zip is es
-- | Get the association list of the matrix, in column-major order.
getAssocs' :: (RMatrix m, Storable e) => m e -> ST s [((Int,Int),e)]
getAssocs' a = do
is <- getIndices a
es <- getElems' a
return $ zip is es
-- | Set all of the values of the matrix from the elements in the list,
-- in column-major order.
setElems :: (Storable e) => STMatrix s e -> [e] -> ST s ()
setElems a es =
case maybeWithVectorM a (`V.setElems` es) of
Just st -> st
Nothing -> do
(m,n) <- getDim a
go m n 0 es
where
go _ n j [] | j == n = return ()
go m n j [] | j < n = error $
printf ("setElems <matrix with dim (%d,%d>"
++ "<list with length %d>: not enough elements)") m n (j*m)
go m n j es' =
let (es1', es2') = splitAt m es'
in do
withColM a j (`V.setElems` es1')
go m n (j+1) es2'
-- | Set the given values in the matrix. If an index is repeated twice,
-- the value is implementation-defined.
setAssocs :: (Storable e) => STMatrix s e -> [((Int,Int),e)] -> ST s ()
setAssocs a ies =
sequence_ [ write a i e | (i,e) <- ies ]
-- | Same as 'setAssocs' but does not range-check indices.
unsafeSetAssocs :: (Storable e) => STMatrix s e -> [((Int,Int),e)] -> ST s ()
unsafeSetAssocs a ies =
sequence_ [ unsafeWrite a i e | (i,e) <- ies ]
-- | Set the specified row of the matrix to the given vector.
setRow :: (RVector v, Storable e)
=> STMatrix s e -> Int -> v e -> ST s ()
setRow a i x = do
(m,n) <- getDim a
nx <- V.getDim x
when (i < 0 || i >= m) $ error $
printf ("setRow <matrix with dim (%d,%d)> %d:"
++ " index out of range") m n i
when (nx /= n) $ error $
printf ("setRow <matrix with dim (%d,%d)> _"
++ " <vector with dim %d>:"
++ " dimension mismatch") m n nx
unsafeSetRow a i x
{-# INLINE setRow #-}
-- | Same as 'setRow' but does not range-check index or check
-- vector dimension.
unsafeSetRow :: (RVector v, Storable e)
=> STMatrix s e -> Int -> v e -> ST s ()
unsafeSetRow a i x = do
jes <- V.getAssocs x
sequence_ [ unsafeWrite a (i,j) e | (j,e) <- jes ]
{-# INLINE unsafeSetRow #-}
-- | Exchange corresponding elements in the given rows.
swapRows :: (BLAS1 e)
=> STMatrix s e -> Int -> Int -> ST s ()
swapRows a i1 i2 = do
(m,n) <- getDim a
when (i1 < 0 || i1 >= m || i2 < 0 || i2 >= m) $ error $
printf ("swapRows <matrix with dim (%d,%d)> %d %d"
++ ": index out of range") m n i1 i2
unsafeSwapRows a i1 i2
-- | Same as 'swapRows' but does not range-check indices.
unsafeSwapRows :: (BLAS1 e)
=> STMatrix s e -> Int -> Int -> ST s ()
unsafeSwapRows a i1 i2 = when (i1 /= i2) $ do
(_,n) <- getDim a
unsafeIOToST $
unsafeWith a $ \pa lda ->
let px = pa `advancePtr` i1
py = pa `advancePtr` i2
incx = lda
incy = lda
in
BLAS.swap n px incx py incy
-- | Exchange corresponding elements in the given columns.
swapCols :: (BLAS1 e)
=> STMatrix s e -> Int -> Int -> ST s ()
swapCols a j1 j2 = do
(m,n) <- getDim a
when (j1 < 0 || j1 >= n || j2 < 0 || j2 >= n) $ error $
printf ("swapCols <matrix with dim (%d,%d)> %d %d"
++ ": index out of range") m n j1 j2
unsafeSwapCols a j1 j2
-- | Same as 'swapCols' but does not range-check indices.
unsafeSwapCols :: (BLAS1 e)
=> STMatrix s e -> Int -> Int -> ST s ()
unsafeSwapCols a j1 j2 = when (j1 /= j2) $ do
(m,_) <- getDim a
unsafeIOToST $
unsafeWith a $ \pa lda ->
let px = pa `advancePtr` (j1*lda)
py = pa `advancePtr` (j2*lda)
incx = 1
incy = 1
in
BLAS.swap m px incx py incy
-- | Copy the specified row of the matrix to the vector.
rowTo :: (RMatrix m, Storable e)
=> STVector s e -> m e -> Int -> ST s ()
rowTo x a i = do
(m,n) <- getDim a
nx <- V.getDim x
when (i < 0 || i >= m) $ error $
printf ("rowTo"
++ " _"
++ " <matrix with dim (%d,%d)>"
++ " %d:"
++ ": index out of range"
) m n i
when (nx /= n) $ error $
printf ("rowTo"
++ " <vector with dim %d>"
++ " <matrix with dim (%d,%d)>"
++ " _"
++ ": dimension mismatch") nx m n
unsafeRowTo x a i
{-# INLINE rowTo #-}
-- | Same as 'rowTo' but does not range-check index or check dimension.
unsafeRowTo :: (RMatrix m, Storable e)
=> STVector s e -> m e -> Int ->ST s ()
unsafeRowTo x a i = do
(_,n) <- getDim a
forM_ [ 0..n-1 ] $ \j -> do
e <- unsafeRead a (i,j)
V.unsafeWrite x j e
{-# INLINE unsafeRowTo #-}
-- | Set the diagonal of the matrix to the given vector.
setDiag :: (RVector v, Storable e)
=> STMatrix s e -> v e -> ST s ()
setDiag a x = do
(m,n) <- getDim a
nx <- V.getDim x
let mn = min m n
when (nx /= mn) $ error $
printf ("setRow <matrix with dim (%d,%d)>"
++ " <vector with dim %d>:"
++ " dimension mismatch") m n nx
unsafeSetDiag a x
{-# INLINE setDiag #-}
-- | Same as 'setDiag' but does not range-check index or check dimension.
unsafeSetDiag :: (RVector v, Storable e)
=> STMatrix s e -> v e -> ST s ()
unsafeSetDiag a x = do
ies <- V.getAssocs x
sequence_ [ unsafeWrite a (i,i) e | (i,e) <- ies ]
{-# INLINE unsafeSetDiag #-}
-- | Copy the diagonal of the matrix to the vector.
diagTo :: (RMatrix m, Storable e)
=> STVector s e -> m e -> ST s ()
diagTo x a = do
nx <- V.getDim x
(m,n) <- getDim a
let mn = min m n
when (nx /= mn) $ error $
printf ("diagTo"
++ " <vector with dim %d>"
++ " <matrix with dim (%d,%d)>"
++ ": dimension mismatch") nx m n
unsafeDiagTo x a
{-# INLINE diagTo #-}
-- | Same as 'diagTo' but does not range-check index or check dimensions.
unsafeDiagTo :: (RMatrix m, Storable e)
=> STVector s e -> m e -> ST s ()
unsafeDiagTo x a = do
(m,n) <- getDim a
let mn = min m n
forM_ [ 0..mn-1 ] $ \i -> do
e <- unsafeRead a (i,i)
V.unsafeWrite x i e
{-# INLINE unsafeDiagTo #-}
-- | Get the element stored at the given index.
read :: (RMatrix m, Storable e) => m e -> (Int,Int) -> ST s e
read a (i,j) = do
(m,n) <- getDim a
when (i < 0 || i >= m || j < 0 || j >= n) $ error $
printf ("read <matrix with dim (%d,%d)> (%d,%d):"
++ " index out of range") m n i j
unsafeRead a (i,j)
{-# INLINE read #-}
-- | Same as 'read' but does not range-check index.
unsafeRead :: (RMatrix m, Storable e) => m e -> (Int,Int) -> ST s e
unsafeRead a (i,j) = unsafeIOToST $
unsafeWith a $ \p lda ->
peekElemOff p (i + j * lda)
{-# INLINE unsafeRead #-}
-- | Set the element stored at the given index.
write :: (Storable e)
=> STMatrix s e -> (Int,Int) -> e -> ST s ()
write a (i,j) e = do
(m,n) <- getDim a
when (i < 0 || i >= m || j < 0 || j >= n) $ error $
printf ("write <matrix with dim (%d,%d)> (%d,%d):"
++ " index out of range") m n i j
unsafeWrite a (i,j) e
{-# INLINE write #-}
-- | Same as 'write' but does not range-check index.
unsafeWrite :: (Storable e)
=> STMatrix s e -> (Int,Int) -> e -> ST s ()
unsafeWrite a (i,j) e = unsafeIOToST $
unsafeWith a $ \p lda ->
pokeElemOff p (i + j * lda) e
{-# INLINE unsafeWrite #-}
-- | Modify the element stored at the given index.
modify :: (Storable e)
=> STMatrix s e -> (Int,Int) -> (e -> e) -> ST s ()
modify a (i,j) f = do
(m,n) <- getDim a
when (i < 0 || i >= m || j < 0 || j >= n) $ error $
printf ("modify <matrix with dim (%d,%d)> (%d,%d):"
++ " index out of range") m n i j
unsafeModify a (i,j) f
{-# INLINE modify #-}
-- | Same as 'modify' but does not range-check index.
unsafeModify :: (Storable e)
=> STMatrix s e -> (Int,Int) -> (e -> e) -> ST s ()
unsafeModify a (i,j) f = unsafeIOToST $
unsafeWith a $ \p lda ->
let o = i + j * lda
in do
e <- peekElemOff p o
pokeElemOff p o $ f e
{-# INLINE unsafeModify #-}
-- | @mapTo dst f src@ replaces @dst@ elementwise with @f(src)@.
mapTo :: (RMatrix m, Storable e, Storable f)
=> STMatrix s f
-> (e -> f)
-> m e
-> ST s ()
mapTo dst f src = (checkOp2 "mapTo _" $ \z x -> unsafeMapTo z f x) dst src
{-# INLINE mapTo #-}
-- | Same as 'mapTo' but does not check dimensions.
unsafeMapTo :: (RMatrix m, Storable e, Storable f)
=> STMatrix s f
-> (e -> f)
-> m e
-> ST s ()
unsafeMapTo dst f src =
fromMaybe colwise $ maybeWithVectorM dst $ \vdst ->
fromMaybe colwise $ maybeWithVector src $ \vsrc ->
V.unsafeMapTo vdst f vsrc
where
colwise = withColsM dst $ \zs ->
withCols src $ \xs ->
sequence_ [ V.unsafeMapTo z f x
| (z,x) <- zip zs xs
]
-- | @zipWithTo dst f x y@ replaces @dst@ elementwise with @f(x, y)@.
zipWithTo :: (RMatrix m1, RMatrix m2, Storable e1, Storable e2, Storable f)
=> STMatrix s f
-> (e1 -> e2 -> f)
-> m1 e1
-> m2 e2
-> ST s ()
zipWithTo dst f x y =
(checkOp3 "zipWithTo _" $ \dst1 x1 y1 -> unsafeZipWithTo dst1 f x1 y1)
dst x y
{-# INLINE zipWithTo #-}
-- | Same as 'zipWithTo' but does not check dimensions.
unsafeZipWithTo :: (RMatrix m1, RMatrix m2, Storable e1, Storable e2, Storable f)
=> STMatrix s f
-> (e1 -> e2 -> f)
-> m1 e1
-> m2 e2
-> ST s ()
unsafeZipWithTo dst f x y =
fromMaybe colwise $ maybeWithVectorM dst $ \vdst ->
fromMaybe colwise $ maybeWithVector x $ \vx ->
fromMaybe colwise $ maybeWithVector y $ \vy ->
V.unsafeZipWithTo vdst f vx vy
where
colwise = withColsM dst $ \vdsts ->
withCols x $ \vxs ->
withCols y $ \vys ->
sequence_ [ V.unsafeZipWithTo vdst f vx vy
| (vdst,vx,vy) <- zip3 vdsts vxs vys
]
-- | Set every element in the matrix to a default value. For
-- standard numeric types (including 'Double', 'Complex Double', and 'Int'),
-- the default value is '0'.
clear :: (Storable e) => STMatrix s e -> ST s ()
clear a = fromMaybe colwise $ maybeWithVectorM a V.clear
where
colwise = withColsM a $ mapM_ V.clear
-- | @withSlice (i,j) (m,n) a@ performs an action with a view of the
-- submatrix of @a@ starting at index @(i,j)@ and having dimension @(m,n)@.
withSlice :: (RMatrix m, Storable e)
=> (Int,Int)
-> (Int,Int)
-> m e
-> (forall m'. RMatrix m' => m' e -> ST s a)
-> ST s a
withSlice ij mn a f = do
ia <- unsafeFreeze a
f $ slice ij mn ia
-- | Like 'withSlice', but perform the action with a mutable view.
withSliceM :: (Storable e)
=> (Int,Int)
-> (Int,Int)
-> STMatrix s e
-> (STMatrix s e -> ST s a)
-> ST s a
withSliceM ij mn a f =
withSlice ij mn a $ \a' -> do
ma <- unsafeThaw a'
f ma
-- | Perform an action with a view gotten from taking the given number of
-- rows from the start of the matrix.
withTakeRows :: (RMatrix m, Storable e)
=> Int
-> m e
-> (forall m'. RMatrix m' => m' e -> ST s a)
-> ST s a
withTakeRows i a f = do
ia <- unsafeFreeze a
f $ takeRows i ia
-- | Like 'withTakeRows', but perform the action with a mutable view.
withTakeRowsM :: (Storable e)
=> Int
-> STMatrix s e
-> (STMatrix s e -> ST s a)
-> ST s a
withTakeRowsM i a f =
withTakeRows i a $ \a' -> do
ma <- unsafeThaw a'
f ma
-- | Perform an action with a view gotten from dropping the given number of
-- rows from the start of the matrix.
withDropRows :: (RMatrix m, Storable e)
=> Int
-> m e
-> (forall m'. RMatrix m' => m' e -> ST s a)
-> ST s a
withDropRows n a f = do
ia <- unsafeFreeze a
f $ dropRows n ia
-- | Like 'withDropRows', but perform the action with a mutable view.
withDropRowsM :: (Storable e)
=> Int
-> STMatrix s e
-> (STMatrix s e -> ST s a)
-> ST s a
withDropRowsM i a f =
withDropRows i a $ \a' -> do
ma <- unsafeThaw a'
f ma
-- | Perform an action with views from splitting the matrix rows at the given
-- index.
withSplitRowsAt :: (RMatrix m, Storable e)
=> Int
-> m e
-> (forall m1 m2. (RMatrix m1, RMatrix m2) => m1 e -> m2 e -> ST s a)
-> ST s a
withSplitRowsAt i a f = do
ia <- unsafeFreeze a
uncurry f $ splitRowsAt i ia
-- | Like 'withSplitRowsAt', but perform the action with a mutable view.
withSplitRowsAtM :: (Storable e)
=> Int
-> STMatrix s e
-> (STMatrix s e -> STMatrix s e -> ST s a)
-> ST s a
withSplitRowsAtM i a f =
withSplitRowsAt i a $ \a1' a2' -> do
ma1 <- unsafeThaw a1'
ma2 <- unsafeThaw a2'
f ma1 ma2
-- | Perform an action with a view gotten from taking the given number of
-- columns from the start of the matrix.
withTakeCols :: (RMatrix m, Storable e)
=> Int
-> m e
-> (forall m'. RMatrix m' => m' e -> ST s a)
-> ST s a
withTakeCols i a f = do
ia <- unsafeFreeze a
f $ takeCols i ia
-- | Like 'withTakeCols', but perform the action with a mutable view.
withTakeColsM :: (Storable e)
=> Int
-> STMatrix s e
-> (STMatrix s e -> ST s a)
-> ST s a
withTakeColsM i a f =
withTakeCols i a $ \a' -> do
ma <- unsafeThaw a'
f ma
-- | Perform an action with a view gotten from dropping the given number of
-- columns from the start of the matrix.
withDropCols :: (RMatrix m, Storable e)
=> Int
-> m e
-> (forall m'. RMatrix m' => m' e -> ST s a)
-> ST s a
withDropCols n a f = do
ia <- unsafeFreeze a
f $ dropCols n ia
-- | Like 'withDropCols', but perform the action with a mutable view.
withDropColsM :: (Storable e)
=> Int
-> STMatrix s e
-> (STMatrix s e -> ST s a)
-> ST s a
withDropColsM i a f =
withDropCols i a $ \a' -> do
ma <- unsafeThaw a'
f ma
-- | Perform an action with views from splitting the matrix columns at the given
-- index.
withSplitColsAt :: (RMatrix m, Storable e)
=> Int
-> m e
-> (forall m1 m2. (RMatrix m1, RMatrix m2) => m1 e -> m2 e -> ST s a)
-> ST s a
withSplitColsAt i a f = do
ia <- unsafeFreeze a
uncurry f $ splitColsAt i ia
-- | Like 'withSplitColsAt', but perform the action with mutable views.
withSplitColsAtM :: (Storable e)
=> Int
-> STMatrix s e
-> (STMatrix s e -> STMatrix s e -> ST s a)
-> ST s a
withSplitColsAtM i a f =
withSplitColsAt i a $ \a1' a2' -> do
ma1 <- unsafeThaw a1'
ma2 <- unsafeThaw a2'
f ma1 ma2
-- | Add a vector to the diagonal of a matrix.
shiftDiagM_ :: (RVector v, BLAS1 e)
=> v e -> STMatrix s e -> ST s ()
shiftDiagM_ s a = do
(m,n) <- getDim a
ns <- V.getDim s
let mn = min m n
when (ns /= mn) $ error $
printf ("shiftDiagM_"
++ " <vector with dim %d>"
++ " <matrix with dim (%d,%d)>"
++ ": dimension mismatch")
ns
m n
shiftDiagWithScaleM_ 1 s a
-- | Add a scaled vector to the diagonal of a matrix.
shiftDiagWithScaleM_ :: (RVector v, BLAS1 e)
=> e -> v e -> STMatrix s e -> ST s ()
shiftDiagWithScaleM_ e s a = do
(m,n) <- getDim a
ns <- V.getDim s
let mn = min m n
when (ns /= mn) $ error $
printf ("shiftDiagWithScaleM_"
++ " _"
++ " <vector with dim %d>"
++ " <matrix with dim (%d,%d)>"
++ ": dimension mismatch")
ns
m n
unsafeIOToST $
V.unsafeWith s $ \ps ->
unsafeWith a $ \pa lda ->
BLAS.axpy mn e ps 1 pa (lda+1)
-- | Add two matrices.
addTo :: (RMatrix m1, RMatrix m2, VNum e)
=> STMatrix s e -> m1 e -> m2 e -> ST s ()
addTo = checkOp3 "addTo" $ vectorOp3 V.addTo
-- | Subtract two matrices.
subTo :: (RMatrix m1, RMatrix m2, VNum e)
=> STMatrix s e -> m1 e -> m2 e -> ST s ()
subTo = checkOp3 "subTo" $ vectorOp3 V.subTo
-- | Conjugate the entries of a matrix.
conjugateTo :: (RMatrix m, VNum e)
=> STMatrix s e -> m e -> ST s ()
conjugateTo = checkOp2 "conjugateTo" $
vectorOp2 V.conjugateTo
-- | Negate the entries of a matrix.
negateTo :: (RMatrix m, VNum e)
=> STMatrix s e -> m e -> ST s ()
negateTo = checkOp2 "negateTo" $
vectorOp2 V.negateTo
-- | Scale the entries of a matrix by the given value.
scaleM_ :: (BLAS1 e)
=> e -> STMatrix s e -> ST s ()
scaleM_ e = vectorOp (V.scaleM_ e)
-- | @addWithScaleM_ alpha x y@ sets @y := alpha * x + y@.
addWithScaleM_ :: (RMatrix m, BLAS1 e)
=> e -> m e -> STMatrix s e -> ST s ()
addWithScaleM_ e = checkOp2 "addWithScaleM_" $
unsafeAddWithScaleM_ e
unsafeAddWithScaleM_ :: (RMatrix m, BLAS1 e)
=> e -> m e -> STMatrix s e -> ST s ()
unsafeAddWithScaleM_ alpha x y =
fromMaybe colwise $ maybeWithVector x $ \vx ->
fromMaybe colwise $ maybeWithVectorM y $ \vy ->
V.unsafeAddWithScaleM_ alpha vx vy
where
colwise = withCols x $ \vxs ->
withColsM y $ \vys ->
sequence_ [ V.unsafeAddWithScaleM_ alpha vx vy
| (vx,vy) <- zip vxs vys ]
-- | Scale the rows of a matrix; @scaleRowsM_ s a@ sets
-- @a := diag(s) * a@.
scaleRowsM_ :: (RVector v, BLAS1 e)
=> v e -> STMatrix s e -> ST s ()
scaleRowsM_ s a = do
(m,n) <- getDim a
ns <- V.getDim s
when (ns /= m) $ error $
printf ("scaleRowsM_"
++ " <vector with dim %d>"
++ " <matrix with dim (%d,%d)>"
++ ": dimension mismatch")
ns
m n
unsafeIOToST $
V.unsafeWith s $ \ps ->
unsafeWith a $ \pa lda ->
go m n lda pa ps 0
where
go m n lda pa ps i | i == m = return ()
| otherwise = do
e <- peek ps
BLAS.scal n e pa lda
go m n lda (pa `advancePtr` 1)
(ps `advancePtr` 1)
(i+1)
-- | Scale the columns of a matrix; @scaleColBysM_ s a@ sets
-- @a := a * diag(s)@.
scaleColsM_ :: (RVector v, BLAS1 e)
=> v e -> STMatrix s e -> ST s ()
scaleColsM_ s a = do
(m,n) <- getDim a
ns <- V.getDim s
when (ns /= n) $ error $
printf ("scaleColsM_"
++ " <vector with dim %d>"
++ " <matrix with dim (%d,%d)>"
++ ": dimension mismatch")
ns
m n
es <- V.getElems s
withColsM a $ \xs ->
sequence_ [ V.scaleM_ e x
| (e,x) <- zip es xs
]
-- | @rank1UpdateM_ alpha x y a@ sets @a := alpha * x * y^H + a@.
rank1UpdateM_ :: (RVector v1, RVector v2, BLAS2 e)
=> e -> v1 e -> v2 e -> STMatrix s e -> ST s ()
rank1UpdateM_ alpha x y a = do
(m,n) <- getDim a
nx <- V.getDim x
ny <- V.getDim y
when (nx /= m || ny /= n) $ error $
printf ("rank1UpdateTo"
++ " _"
++ " <vector with dim %d>"
++ " <vector with dim %d>"
++ ": dimension mismatch"
++ "<matrix with dim (%d,%d)>" )
nx
ny
m n
unsafeIOToST $
V.unsafeWith x $ \px ->
V.unsafeWith y $ \py ->
unsafeWith a $ \pa lda ->
BLAS.gerc m n alpha px 1 py 1 pa lda
-- | @transTo dst a@ sets @dst := trans(a)@.
transTo :: (RMatrix m, BLAS1 e)
=> STMatrix s e
-> m e
-> ST s ()
transTo a' a = do
(ma,na) <- getDim a
(ma',na') <- getDim a'
let (m,n) = (ma,na)
when ((ma,na) /= (na',ma')) $ error $
printf ( "transTo"
++ " <matrix with dim (%d,%d)>"
++ " <matrix with dim (%d,%d)>"
++ ": dimension mismatch"
)
ma' na'
ma na
unsafeIOToST $
unsafeWith a' $ \pa' lda' ->
unsafeWith a $ \pa lda -> let
go j px py | j == n = return ()
| otherwise = do
BLAS.copy m px 1 py lda'
go (j+1) (px `advancePtr` lda) (py `advancePtr` 1)
in go 0 pa pa'
-- | @conjTransTo dst a@ sets @dst := conjugate(trans(a))@.
conjTransTo :: (RMatrix m, BLAS1 e)
=> STMatrix s e
-> m e
-> ST s ()
conjTransTo a' a = do
transTo a' a
conjugateTo a' a'
-- | @mulVectorTo dst transa a x@
-- sets @dst := op(a) * x@, where @op(a)@ is determined by @transa@.
mulVectorTo :: (RMatrix m, RVector v, BLAS2 e)
=> STVector s e
-> Trans -> m e
-> v e
-> ST s ()
mulVectorTo dst = mulVectorWithScaleTo dst 1
-- | @mulVectorWithScaleTo dst alpha transa a x@
-- sets @dst := alpha * op(a) * x@, where @op(a)@ is determined by @transa@.
mulVectorWithScaleTo :: (RMatrix m, RVector v, BLAS2 e)
=> STVector s e
-> e
-> Trans -> m e
-> v e
-> ST s ()
mulVectorWithScaleTo dst alpha t a x =
addMulVectorWithScalesM_ alpha t a x 0 dst
-- | @addMulVectorWithScalesM_ alpha transa a x beta y@
-- sets @y := alpha * op(a) * x + beta * y@, where @op(a)@ is
-- determined by @transa@.
addMulVectorWithScalesM_ :: (RMatrix m, RVector v, BLAS2 e)
=> e
-> Trans -> m e
-> v e
-> e
-> STVector s e
-> ST s ()
addMulVectorWithScalesM_ alpha transa a x beta y = do
(ma,na) <- getDim a
nx <- V.getDim x
ny <- V.getDim y
let (m,n) = (ny,nx)
when ((not . and) [ case transa of NoTrans -> (ma,na) == (m,n)
_ -> (ma,na) == (n,m)
, nx == n
, ny == m
]) $ error $
printf ("addMulVectorWithScalesTo"
++ " _"
++ " %s"
++ " <matrix with dim (%d,%d)>"
++ " <vector with dim %d>"
++ " _"
++ " <vector with dim %d>"
++ ": dimension mismatch")
(show transa)
ma na
nx
ny
unsafeIOToST $
unsafeWith a $ \pa lda ->
V.unsafeWith x $ \px ->
V.unsafeWith y $ \py ->
if n == 0
then BLAS.scal m beta py 1
else BLAS.gemv transa ma na alpha pa lda px 1 beta py 1
-- | @mulMatrixTo dst transa a transb b@
-- sets @dst := op(a) * op(b)@, where @op(a)@ and @op(b)@ are determined
-- by @transa@ and @transb@.
mulMatrixTo :: (RMatrix m1, RMatrix m2, BLAS3 e)
=> STMatrix s e
-> Trans -> m1 e
-> Trans -> m2 e
-> ST s ()
mulMatrixTo dst = mulMatrixWithScaleTo dst 1
-- | @mulMatrixWithScaleTo alpha transa a transb b c@
-- sets @c := alpha * op(a) * op(b)@, where @op(a)@ and @op(b)@ are determined
-- by @transa@ and @transb@.
mulMatrixWithScaleTo :: (RMatrix m1, RMatrix m2, BLAS3 e)
=> STMatrix s e
-> e
-> Trans -> m1 e
-> Trans -> m2 e
-> ST s ()
mulMatrixWithScaleTo dst alpha ta a tb b =
addMulMatrixWithScalesM_ alpha ta a tb b 0 dst
-- | @addMulMatrixWithScalesM_ alpha transa a transb b beta c@
-- sets @c := alpha * op(a) * op(b) + beta * c@, where @op(a)@ and
-- @op(b)@ are determined by @transa@ and @transb@.
addMulMatrixWithScalesM_ :: (RMatrix m1, RMatrix m2, BLAS3 e)
=> e
-> Trans -> m1 e
-> Trans -> m2 e
-> e
-> STMatrix s e
-> ST s ()
addMulMatrixWithScalesM_ alpha transa a transb b beta c = do
(ma,na) <- getDim a
(mb,nb) <- getDim b
(mc,nc) <- getDim c
let (m,n) = (mc,nc)
k = case transa of NoTrans -> na
_ -> ma
when ((not . and) [ case transa of NoTrans -> (ma,na) == (m,k)
_ -> (ma,na) == (k,m)
, case transb of NoTrans -> (mb,nb) == (k,n)
_ -> (mb,nb) == (n,k)
, (mc, nc) == (m,n)
]) $ error $
printf ("addMulMatrixWithScalesM_"
++ " _"
++ " %s <matrix with dim (%d,%d)>"
++ " %s <matrix with dim (%d,%d)>"
++ " _"
++ " <matrix with dim (%d,%d)>"
++ ": dimension mismatch")
(show transa) ma na
(show transb) mb nb
mc nc
unsafeIOToST $
unsafeWith a $ \pa lda ->
unsafeWith b $ \pb ldb ->
unsafeWith c $ \pc ldc ->
BLAS.gemm transa transb m n k alpha pa lda pb ldb beta pc ldc
checkOp2 :: (RMatrix x, RMatrix y, Storable e, Storable f)
=> String
-> (x e -> y f -> ST s a)
-> x e
-> y f
-> ST s a
checkOp2 str f x y = do
(m1,n1) <- getDim x
(m2,n2) <- getDim y
when ((m1,n1) /= (m2,n2)) $ error $
printf ("%s <matrix with dim (%d,%d)> <matrix with dim (%d,%d)>:"
++ " dimension mismatch") str m1 n1 m2 n2
f x y
{-# INLINE checkOp2 #-}
checkOp3 :: (RMatrix x, RMatrix y, RMatrix z, Storable e, Storable f, Storable g)
=> String
-> (x e -> y f -> z g -> ST s a)
-> x e
-> y f
-> z g
-> ST s a
checkOp3 str f x y z = do
(m1,n1) <- getDim x
(m2,n2) <- getDim y
(m3,n3) <- getDim z
when((m1,n1) /= (m2,n2) || (m1,n1) /= (m3,n3)) $ error $
printf ("%s <matrix with dim (%d,%d)> <matrix with dim (%d,%d)>:"
++ " <matrix with dim (%d,%d)> dimension mismatch")
str m1 n1 m2 n2 m3 n3
f x y z
{-# INLINE checkOp3 #-}
vectorOp :: (Storable e)
=> (STVector s e -> ST s ())
-> STMatrix s e -> ST s ()
vectorOp f x =
fromMaybe colwise $ maybeWithVectorM x $ \vx -> f vx
where
colwise = withColsM x $ \vxs ->
sequence_ [ f vx | vx <- vxs ]
vectorOp2 :: (RMatrix m, Storable e, Storable f)
=> (forall v . RVector v => STVector s f -> v e -> ST s ())
-> STMatrix s f -> m e -> ST s ()
vectorOp2 f dst x =
fromMaybe colwise $ maybeWithVectorM dst $ \vdst ->
fromMaybe colwise $ maybeWithVector x $ \vx ->
f vdst vx
where
colwise = withColsM dst $ \vdsts ->
withCols x $ \vxs ->
sequence_ [ f vdst vx | (vdst,vx) <- zip vdsts vxs ]
{-# INLINE vectorOp2 #-}
vectorOp3 :: (RMatrix m1, RMatrix m2, Storable e1, Storable e2, Storable f)
=> (forall v1 v2 . (RVector v1, RVector v2) =>
STVector s f -> v1 e1 -> v2 e2 -> ST s ())
-> STMatrix s f -> m1 e1 -> m2 e2 -> ST s ()
vectorOp3 f dst x y =
fromMaybe colwise $ maybeWithVectorM dst $ \vdst ->
fromMaybe colwise $ maybeWithVector x $ \vx ->
fromMaybe colwise $ maybeWithVector y $ \vy ->
f vdst vx vy
where
colwise = withColsM dst $ \vdsts ->
withCols x $ \vxs ->
withCols y $ \vys ->
sequence_ [ f vdst vx vy
| (vdst,vx,vy) <- zip3 vdsts vxs vys ]
{-# INLINE vectorOp3 #-}
| patperry/hs-linear-algebra | lib/Numeric/LinearAlgebra/Matrix/STBase.hs | bsd-3-clause | 41,765 | 0 | 20 | 15,100 | 12,954 | 6,511 | 6,443 | 938 | 4 |
module Parse.IParser where
import Parse.Primitives (Parser)
import Reporting.Error.Syntax (ParsecError)
type IParser a = Parser ParsecError a
| avh4/elm-format | elm-format-lib/src/Parse/IParser.hs | bsd-3-clause | 145 | 0 | 5 | 19 | 39 | 24 | 15 | 4 | 0 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
module Node.T1w
(T1w(..)
,rules)
where
import Node.Types
import Node.Util (getPath, outdir, showKey)
import Shake.BuildNode
import Util (alignAndCenter)
data T1w =
T1w {t1type :: T1wType
,caseid :: CaseId}
deriving (Show,Generic,Typeable,Eq,Hashable,Binary,NFData,Read)
instance BuildNode T1w where
path n@(T1w{..}) =
case t1type of
T1wGiven -> getPath "t1" caseid
_ -> outdir </> caseid </> showKey n <.> "nrrd"
build out@(T1w{..}) =
case t1type of
T1wGiven -> Nothing
T1wXc ->
Just $
do let t1 = T1w T1wGiven caseid
need t1
alignAndCenter (path t1)
(path out)
rules = rule (buildNode :: T1w -> Maybe (Action [Double]))
| reckbo/ppl | pipeline-lib/Node/T1w.hs | bsd-3-clause | 939 | 0 | 15 | 294 | 286 | 154 | 132 | 30 | 1 |
-- | Tests for automatic deriving of ann method from Annotated type class.
module Language.Java.Paragon.SyntaxSpec (main, spec) where
import Test.Hspec
import Language.Java.Paragon.Annotation
import Language.Java.Paragon.Syntax
-- | To be able to run this module from GHCi.
main :: IO ()
main = hspec spec
-- | Main specification function.
spec :: Spec
spec = do
describe "ann" $ do
it "returns annotation for leaf node" $
ann (Null emptyAnnotation) `shouldBe` emptyAnnotation
it "returns annotation for internal node (1 level)" $
ann (Lit (Int emptyAnnotation 2)) `shouldBe` emptyAnnotation
it "returns annotation for internal node (2 levels)" $ do
let wrongAnnotation = emptyAnnotation { annIsNull = False }
ann (RefType (ClassRefType (ClassType emptyAnnotation (Name wrongAnnotation (Id wrongAnnotation "Object") TypeName Nothing) [])))
`shouldBe` emptyAnnotation
| bvdelft/paragon | test/Language/Java/Paragon/SyntaxSpec.hs | bsd-3-clause | 919 | 0 | 24 | 172 | 217 | 115 | 102 | 17 | 1 |
{-# LANGUAGE QuasiQuotes, TypeFamilies, PackageImports #-}
import Control.Arrow
import "monads-tf" Control.Monad.State
import "monads-tf" Control.Monad.Error
import Data.Maybe
import Data.Char
import System.Environment
import Text.Papillon
type List = [List1]
data List1 = Item String List deriving Show
main :: IO ()
main = do
fn : _ <- getArgs
cnt <- readFile fn
print $ parseList cnt
parseList :: String -> Maybe List
parseList src = case flip runState (0, [-1]) $ runErrorT $ list $ parse src of
(Right (r, _), _) -> Just r
_ -> Nothing
checkState :: String -> Maybe (Int, [Int])
checkState src = case flip runState (0, [-1]) $ runErrorT $ list $ parse src of
(_, s) -> Just s
reset :: State (Int, [Int]) Bool
reset = modify (first $ const 0) >> return True
cntSpace :: State (Int, [Int]) ()
cntSpace = modify $ first (+ 1)
deeper :: State (Int, [Int]) Bool
deeper = do
(n, n0 : ns) <- get
if n > n0 then put (n, n : n0 : ns) >> return True else return False
same :: State (Int, [Int]) Bool
same = do
(n, n0 : _) <- get
return $ n == n0
shallow :: State (Int, [Int]) Bool
shallow = do
(n, n0 : ns) <- get
if n < n0 then put (n, ns) >> return True else return False
[papillon|
monad: State (Int, [Int])
list :: List
= _:countSpace _:dmmy[deeper] l:list1 ls:list1'* _:shllw
{ return $ l : ls }
list1' :: List1
= _:countSpace _:dmmy[same] l:list1 { return l }
list1 :: List1 = '*' ' ' l:line '\n' ls:list?
{ return $ Item l $ fromMaybe [] ls }
line :: String
= l:<isLower>+ { return l }
countSpace :: ()
= _:dmmy[reset] _:(' ' { cntSpace })*
shllw :: ()
= _:dmmy[shallow]
/ !_
dmmy :: () =
|]
| YoshikuniJujo/markdown2svg | tests/testParser.hs | bsd-3-clause | 1,644 | 0 | 12 | 358 | 572 | 308 | 264 | 39 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
module DataLayer
( KeyValue (..)
, insert
, find
)
where
import Control.Monad.Reader
import Control.Monad.State
import Data.Acid
import Data.SafeCopy
import Data.Typeable
import qualified Data.Map as Map
import qualified Data.Text.Lazy as T
type Key = T.Text
type Url = T.Text
data KeyValue = KeyValue !(Map.Map Key Url)
deriving (Typeable, Show)
$(deriveSafeCopy 0 'base ''KeyValue)
insertKey :: Key -> Url -> Update KeyValue ()
insertKey key value = do
KeyValue m <- get
put (KeyValue (Map.insert key value m))
lookupKey :: Key -> Query KeyValue (Maybe Url)
lookupKey key = do
KeyValue m <- ask
return (Map.lookup key m)
$(makeAcidic ''KeyValue ['insertKey, 'lookupKey])
insert :: AcidState KeyValue -> Key -> Url -> IO ()
insert acid key value = update acid (InsertKey key value)
find :: AcidState KeyValue -> Key -> IO (Maybe T.Text)
find acid key = query acid (LookupKey key)
| wavelets/9m | src/DataLayer.hs | bsd-3-clause | 1,050 | 0 | 12 | 191 | 369 | 195 | 174 | 35 | 1 |
module Ribbon where
import Rumpus
-- Devin Chalmers remix
start :: Start
start = do
parentID <- ask
addActiveKnob "Total Speed" (Linear -5 5) 1 setClockSpeed
rotSpeedKnob <- addKnob "Rot Speed" (Linear 0 5) 1
yScaleKnob <- addKnob "YScale" (Linear 0 10) 1
zScaleKnob <- addKnob "ZScale" (Linear 0.1 10) 1
forM_ [0..100] $ \i -> spawnChild $ do
myShape ==> Sphere
myTransformType ==> AbsolutePose
myUpdate ==> do
now <- getEntityClockTime parentID
rotSpeed <- readKnob rotSpeedKnob
yScale <- readKnob yScaleKnob
zScale <- readKnob zScaleKnob
let n = now + (i * 0.5)
y = yScale * tan n/2
x = sin n * 5
setPositionRotationSize
(V3 x y (-10))
(axisAngle (V3 1 0 1) (n*rotSpeed))
(V3 9 0.1 (sin n * zScale))
setColor (colorHSL (n*0.1) 0.8 0.6)
| lukexi/rumpus | pristine/Ribbon/RibbonRemix.hs | bsd-3-clause | 989 | 0 | 20 | 377 | 339 | 162 | 177 | 25 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
module Karamaan.Opaleye.TableColspec where
import Karamaan.Opaleye.Wire (Wire(Wire))
import Karamaan.Opaleye.QueryColspec (QueryColspec(QueryColspec),
runWriterOfQueryColspec,
runPackMapOfQueryColspec,
MWriter(Writer),
PackMap(PackMap))
import Control.Applicative (Applicative, pure, (<*>))
import Data.Profunctor.Product.Default (Default, def)
import Data.Profunctor (Profunctor, dimap, lmap, rmap)
import Data.Profunctor.Product (ProductProfunctor, empty, (***!),
defaultEmpty, defaultProfunctorProduct)
-- TODO: this happens to have the same implementation as QueryColspec, but I
-- don't want to suggest that one derives from the other. Perhaps make this
-- clearer by introducing another type from which they both inherit their
-- implementation.
newtype TableColspecP a b = TableColspecP (QueryColspec a b)
-- TODO: we don't actually need TableColspec anymore. It's just a partially
-- applied TableColspecP. We should unpick its usage from makeTable replacing
-- it with TableColspecP, and then delete its definition.
newtype TableColspec b = TableColspec (TableColspecP () b)
tableColspecOfTableColspecP :: TableColspecP a b -> a -> TableColspec b
tableColspecOfTableColspecP q a = TableColspec (lmap (const a) q)
instance Functor (TableColspecP a) where
fmap f (TableColspecP c) = TableColspecP (fmap f c)
instance Applicative (TableColspecP a) where
pure = TableColspecP . pure
TableColspecP f <*> TableColspecP x = TableColspecP (f <*> x)
instance Functor TableColspec where
fmap f (TableColspec c) = TableColspec (rmap f c)
instance Applicative TableColspec where
pure = TableColspec . pure
TableColspec f <*> TableColspec x = TableColspec (f <*> x)
instance Profunctor TableColspecP where
dimap f g (TableColspecP q) = TableColspecP (dimap f g q)
instance ProductProfunctor TableColspecP where
empty = defaultEmpty
(***!) = defaultProfunctorProduct
instance Default TableColspecP (Wire a) (Wire a) where
def = TableColspecP def
runWriterOfColspec :: TableColspec a -> [String]
runWriterOfColspec (TableColspec (TableColspecP c)) =
runWriterOfQueryColspec c ()
runPackMapOfColspec :: TableColspec a -> (String -> String) -> a
runPackMapOfColspec (TableColspec (TableColspecP c)) f =
runPackMapOfQueryColspec c f ()
-- TODO: this implementation is verbose
colspec :: [String] -> ((String -> String) -> a) -> TableColspec a
colspec w p = TableColspec
(TableColspecP
(QueryColspec (Writer (const w)) (PackMap (\f () -> p f))))
col :: String -> TableColspec (Wire a)
col s = colspec [s] (\f -> Wire (f s))
newtype WireMaker a b = WireMaker (a -> b)
runWireMaker :: WireMaker a b -> a -> b
runWireMaker (WireMaker f) = f
wireCol :: WireMaker String (Wire a)
wireCol = WireMaker Wire
instance Functor (WireMaker a) where
fmap f (WireMaker g) = WireMaker (fmap f g)
instance Applicative (WireMaker a) where
pure = WireMaker . pure
WireMaker f <*> WireMaker x = WireMaker (f <*> x)
instance Profunctor WireMaker where
dimap f g (WireMaker q) = WireMaker (dimap f g q)
instance ProductProfunctor WireMaker where
empty = defaultEmpty
(***!) = defaultProfunctorProduct
instance Default WireMaker String (Wire a) where
def = WireMaker Wire
| dbp/karamaan-opaleye | Karamaan/Opaleye/TableColspec.hs | bsd-3-clause | 3,476 | 0 | 14 | 718 | 978 | 522 | 456 | 63 | 1 |
module Math.Simplicial.NeighborhoodGraph where
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector as BV
import qualified Math.VectorSpaces.Metric as Met
import qualified Math.Simplicial.LandmarkSelection as LS
import qualified Math.Misc.Matrix as Mat
import qualified Math.VectorSpaces.DistanceMatrix as DMat
import Math.Simplicial.PreScale
import Math.Cloud.Cloud
import Data.List
import Misc.Misc
data NeighborhoodGraph = C
Int -- Number of nodes.
Double -- Maximum scale.
DMat.RealDistanceMatrix -- Edge weights.
DMat.BooleanDistanceMatrix -- Edge table.
exact :: (Met.Metric a) => Cloud a -> PreScale -> NeighborhoodGraph
exact _ (ConditionFactor _) = error "Exact neighborhood graphs only available with absolute maximum scale."
exact c (Absolute scale) = C n scale ws es
where
c' = BV.fromList c
n = BV.length c'
ws = DMat.generate n (\ (i,j) -> Met.distance (c' BV.! i) (c' BV.! j))
es = DMat.map (<= scale) ws
-- | Follows de Silva, Carlsson: Topological estimation using witness complexes.
lazyWitness :: (Met.Metric a) => LS.LandmarkSelection a -> Int -> PreScale -> NeighborhoodGraph
lazyWitness ls nu preScale = C nl scale weights edges
where
scale = case preScale of
Absolute s -> s
ConditionFactor c -> c * (UV.maximum (UV.generate nw (Mat.rowMinimum d)))
witnesses = LS.witnesses ls
landmarks = LS.landmarks ls
d = LS.witnessToLandmarkDistances ls
m = if nu <= 0
then UV.replicate nw 0.0
else UV.generate nw (\i -> smallest' nu (UV.toList (d `Mat.row` i)))
nl = LS.numLandmarks ls
nw = LS.numWitnesses ls
weights = DMat.generate nl weight
edges = DMat.map (<= scale) weights
weight :: (Int, Int) -> Double
weight (i, j) = UV.minimum (UV.generate nw (witnessWeight (i,j)))
witnessWeight :: (Int, Int) -> Int -> Double
witnessWeight (i, j) k = max 0 (dMax - m UV.! k)
where
dMax = max (d Mat.! (k,i)) (d Mat.! (k,j))
weight :: NeighborhoodGraph -> Int -> Int -> Double
weight (C _ _ ws _) i j = ws DMat.? (i, j)
edge :: NeighborhoodGraph -> Int -> Int -> Bool
edge (C _ _ _ es) i j = es DMat.? (i, j)
weight' :: NeighborhoodGraph -> (Int, Int) -> Double
weight' g = uncurry (weight g)
numVertices :: NeighborhoodGraph -> Int
numVertices (C n _ _ _) = n
vertices :: NeighborhoodGraph -> [Int]
vertices g = [0..(numVertices g - 1)]
edges :: NeighborhoodGraph -> [(Int, Int)]
edges g = go (vertices g)
where
go [] = []
go (i:is) = zip (repeat i) (filter (edge g i) is) ++ go is
scale :: NeighborhoodGraph -> Double
scale (C _ s _ _) = s
| michiexile/hplex | pershom/src/Math/Simplicial/NeighborhoodGraph.hs | bsd-3-clause | 2,787 | 0 | 17 | 724 | 1,004 | 546 | 458 | 59 | 3 |
{-# LANGUAGE CPP, GADTs #-}
-----------------------------------------------------------------------------
--
-- Pretty-printing of Cmm as C, suitable for feeding gcc
--
-- (c) The University of Glasgow 2004-2006
--
-- Print Cmm as real C, for -fvia-C
--
-- See wiki:Commentary/Compiler/Backends/PprC
--
-- This is simpler than the old PprAbsC, because Cmm is "macro-expanded"
-- relative to the old AbstractC, and many oddities/decorations have
-- disappeared from the data type.
--
-- This code generator is only supported in unregisterised mode.
--
-----------------------------------------------------------------------------
module PprC (
writeCs,
pprStringInCStyle
) where
#include "HsVersions.h"
-- Cmm stuff
import BlockId
import CLabel
import ForeignCall
import Cmm hiding (pprBBlock)
import PprCmm ()
import Hoopl
import CmmUtils
import CmmSwitch
-- Utils
import CPrim
import DynFlags
import FastString
import Outputable
import Platform
import UniqSet
import Unique
import Util
-- The rest
import Control.Monad.ST
import Data.Bits
import Data.Char
import Data.List
import Data.Map (Map)
import Data.Word
import System.IO
import qualified Data.Map as Map
import Control.Monad (liftM, ap)
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative (Applicative(..))
#endif
import qualified Data.Array.Unsafe as U ( castSTUArray )
import Data.Array.ST
-- --------------------------------------------------------------------------
-- Top level
pprCs :: DynFlags -> [RawCmmGroup] -> SDoc
pprCs dflags cmms
= pprCode CStyle (vcat $ map (\c -> split_marker $$ pprC c) cmms)
where
split_marker
| gopt Opt_SplitObjs dflags = text "__STG_SPLIT_MARKER"
| otherwise = empty
writeCs :: DynFlags -> Handle -> [RawCmmGroup] -> IO ()
writeCs dflags handle cmms
= printForC dflags handle (pprCs dflags cmms)
-- --------------------------------------------------------------------------
-- Now do some real work
--
-- for fun, we could call cmmToCmm over the tops...
--
pprC :: RawCmmGroup -> SDoc
pprC tops = vcat $ intersperse blankLine $ map pprTop tops
--
-- top level procs
--
pprTop :: RawCmmDecl -> SDoc
pprTop (CmmProc infos clbl _ graph) =
(case mapLookup (g_entry graph) infos of
Nothing -> empty
Just (Statics info_clbl info_dat) -> pprDataExterns info_dat $$
pprWordArray info_clbl info_dat) $$
(vcat [
blankLine,
extern_decls,
(if (externallyVisibleCLabel clbl)
then mkFN_ else mkIF_) (ppr clbl) <+> lbrace,
nest 8 temp_decls,
vcat (map pprBBlock blocks),
rbrace ]
)
where
blocks = toBlockListEntryFirst graph
(temp_decls, extern_decls) = pprTempAndExternDecls blocks
-- Chunks of static data.
-- We only handle (a) arrays of word-sized things and (b) strings.
pprTop (CmmData _section (Statics lbl [CmmString str])) =
hcat [
pprLocalness lbl, text "char ", ppr lbl,
text "[] = ", pprStringInCStyle str, semi
]
pprTop (CmmData _section (Statics lbl [CmmUninitialised size])) =
hcat [
pprLocalness lbl, text "char ", ppr lbl,
brackets (int size), semi
]
pprTop (CmmData _section (Statics lbl lits)) =
pprDataExterns lits $$
pprWordArray lbl lits
-- --------------------------------------------------------------------------
-- BasicBlocks are self-contained entities: they always end in a jump.
--
-- Like nativeGen/AsmCodeGen, we could probably reorder blocks to turn
-- as many jumps as possible into fall throughs.
--
pprBBlock :: CmmBlock -> SDoc
pprBBlock block =
nest 4 (pprBlockId (entryLabel block) <> colon) $$
nest 8 (vcat (map pprStmt (blockToList nodes)) $$ pprStmt last)
where
(_, nodes, last) = blockSplit block
-- --------------------------------------------------------------------------
-- Info tables. Just arrays of words.
-- See codeGen/ClosureInfo, and nativeGen/PprMach
pprWordArray :: CLabel -> [CmmStatic] -> SDoc
pprWordArray lbl ds
= sdocWithDynFlags $ \dflags ->
hcat [ pprLocalness lbl, text "StgWord"
, space, ppr lbl, text "[]"
-- See Note [StgWord alignment]
, pprAlignment (wordWidth dflags)
, text "= {" ]
$$ nest 8 (commafy (pprStatics dflags ds))
$$ text "};"
pprAlignment :: Width -> SDoc
pprAlignment words =
text "__attribute__((aligned(" <> int (widthInBytes words) <> text ")))"
-- Note [StgWord alignment]
-- C codegen builds static closures as StgWord C arrays (pprWordArray).
-- Their real C type is 'StgClosure'. Macros like UNTAG_CLOSURE assume
-- pointers to 'StgClosure' are aligned at pointer size boundary:
-- 4 byte boundary on 32 systems
-- and 8 bytes on 64-bit systems
-- see TAG_MASK and TAG_BITS definition and usage.
--
-- It's a reasonable assumption also known as natural alignment.
-- Although some architectures have different alignment rules.
-- One of known exceptions is m68k (Trac #11395, comment:16) where:
-- __alignof__(StgWord) == 2, sizeof(StgWord) == 4
--
-- Thus we explicitly increase alignment by using
-- __attribute__((aligned(4)))
-- declaration.
--
-- has to be static, if it isn't globally visible
--
pprLocalness :: CLabel -> SDoc
pprLocalness lbl | not $ externallyVisibleCLabel lbl = text "static "
| otherwise = empty
-- --------------------------------------------------------------------------
-- Statements.
--
pprStmt :: CmmNode e x -> SDoc
pprStmt stmt =
sdocWithDynFlags $ \dflags ->
case stmt of
CmmEntry{} -> empty
CmmComment _ -> empty -- (hang (text "/*") 3 (ftext s)) $$ ptext (sLit "*/")
-- XXX if the string contains "*/", we need to fix it
-- XXX we probably want to emit these comments when
-- some debugging option is on. They can get quite
-- large.
CmmTick _ -> empty
CmmUnwind{} -> empty
CmmAssign dest src -> pprAssign dflags dest src
CmmStore dest src
| typeWidth rep == W64 && wordWidth dflags /= W64
-> (if isFloatType rep then text "ASSIGN_DBL"
else ptext (sLit ("ASSIGN_Word64"))) <>
parens (mkP_ <> pprExpr1 dest <> comma <> pprExpr src) <> semi
| otherwise
-> hsep [ pprExpr (CmmLoad dest rep), equals, pprExpr src <> semi ]
where
rep = cmmExprType dflags src
CmmUnsafeForeignCall target@(ForeignTarget fn conv) results args ->
fnCall
where
(res_hints, arg_hints) = foreignTargetHints target
hresults = zip results res_hints
hargs = zip args arg_hints
ForeignConvention cconv _ _ ret = conv
cast_fn = parens (cCast (pprCFunType (char '*') cconv hresults hargs) fn)
-- See wiki:Commentary/Compiler/Backends/PprC#Prototypes
fnCall =
case fn of
CmmLit (CmmLabel lbl)
| StdCallConv <- cconv ->
pprCall (ppr lbl) cconv hresults hargs
-- stdcall functions must be declared with
-- a function type, otherwise the C compiler
-- doesn't add the @n suffix to the label. We
-- can't add the @n suffix ourselves, because
-- it isn't valid C.
| CmmNeverReturns <- ret ->
pprCall cast_fn cconv hresults hargs <> semi
| not (isMathFun lbl) ->
pprForeignCall (ppr lbl) cconv hresults hargs
_ ->
pprCall cast_fn cconv hresults hargs <> semi
-- for a dynamic call, no declaration is necessary.
CmmUnsafeForeignCall (PrimTarget MO_Touch) _results _args -> empty
CmmUnsafeForeignCall (PrimTarget (MO_Prefetch_Data _)) _results _args -> empty
CmmUnsafeForeignCall target@(PrimTarget op) results args ->
fn_call
where
cconv = CCallConv
fn = pprCallishMachOp_for_C op
(res_hints, arg_hints) = foreignTargetHints target
hresults = zip results res_hints
hargs = zip args arg_hints
fn_call
-- The mem primops carry an extra alignment arg.
-- We could maybe emit an alignment directive using this info.
-- We also need to cast mem primops to prevent conflicts with GCC
-- builtins (see bug #5967).
| Just _align <- machOpMemcpyishAlign op
= (text ";EFF_(" <> fn <> char ')' <> semi) $$
pprForeignCall fn cconv hresults hargs
| otherwise
= pprCall fn cconv hresults hargs
CmmBranch ident -> pprBranch ident
CmmCondBranch expr yes no _ -> pprCondBranch expr yes no
CmmCall { cml_target = expr } -> mkJMP_ (pprExpr expr) <> semi
CmmSwitch arg ids -> sdocWithDynFlags $ \dflags ->
pprSwitch dflags arg ids
_other -> pprPanic "PprC.pprStmt" (ppr stmt)
type Hinted a = (a, ForeignHint)
pprForeignCall :: SDoc -> CCallConv -> [Hinted CmmFormal] -> [Hinted CmmActual]
-> SDoc
pprForeignCall fn cconv results args = fn_call
where
fn_call = braces (
pprCFunType (char '*' <> text "ghcFunPtr") cconv results args <> semi
$$ text "ghcFunPtr" <+> equals <+> cast_fn <> semi
$$ pprCall (text "ghcFunPtr") cconv results args <> semi
)
cast_fn = parens (parens (pprCFunType (char '*') cconv results args) <> fn)
pprCFunType :: SDoc -> CCallConv -> [Hinted CmmFormal] -> [Hinted CmmActual] -> SDoc
pprCFunType ppr_fn cconv ress args
= sdocWithDynFlags $ \dflags ->
let res_type [] = text "void"
res_type [(one, hint)] = machRepHintCType (localRegType one) hint
res_type _ = panic "pprCFunType: only void or 1 return value supported"
arg_type (expr, hint) = machRepHintCType (cmmExprType dflags expr) hint
in res_type ress <+>
parens (ccallConvAttribute cconv <> ppr_fn) <>
parens (commafy (map arg_type args))
-- ---------------------------------------------------------------------
-- unconditional branches
pprBranch :: BlockId -> SDoc
pprBranch ident = text "goto" <+> pprBlockId ident <> semi
-- ---------------------------------------------------------------------
-- conditional branches to local labels
pprCondBranch :: CmmExpr -> BlockId -> BlockId -> SDoc
pprCondBranch expr yes no
= hsep [ text "if" , parens(pprExpr expr) ,
text "goto", pprBlockId yes <> semi,
text "else goto", pprBlockId no <> semi ]
-- ---------------------------------------------------------------------
-- a local table branch
--
-- we find the fall-through cases
--
pprSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> SDoc
pprSwitch dflags e ids
= (hang (text "switch" <+> parens ( pprExpr e ) <+> lbrace)
4 (vcat ( map caseify pairs ) $$ def)) $$ rbrace
where
(pairs, mbdef) = switchTargetsFallThrough ids
-- fall through case
caseify (ix:ixs, ident) = vcat (map do_fallthrough ixs) $$ final_branch ix
where
do_fallthrough ix =
hsep [ text "case" , pprHexVal ix (wordWidth dflags) <> colon ,
text "/* fall through */" ]
final_branch ix =
hsep [ text "case" , pprHexVal ix (wordWidth dflags) <> colon ,
text "goto" , (pprBlockId ident) <> semi ]
caseify (_ , _ ) = panic "pprSwitch: switch with no cases!"
def | Just l <- mbdef = text "default: goto" <+> pprBlockId l <> semi
| otherwise = empty
-- ---------------------------------------------------------------------
-- Expressions.
--
-- C Types: the invariant is that the C expression generated by
--
-- pprExpr e
--
-- has a type in C which is also given by
--
-- machRepCType (cmmExprType e)
--
-- (similar invariants apply to the rest of the pretty printer).
pprExpr :: CmmExpr -> SDoc
pprExpr e = case e of
CmmLit lit -> pprLit lit
CmmLoad e ty -> sdocWithDynFlags $ \dflags -> pprLoad dflags e ty
CmmReg reg -> pprCastReg reg
CmmRegOff reg 0 -> pprCastReg reg
CmmRegOff reg i
| i < 0 && negate_ok -> pprRegOff (char '-') (-i)
| otherwise -> pprRegOff (char '+') i
where
pprRegOff op i' = pprCastReg reg <> op <> int i'
negate_ok = negate (fromIntegral i :: Integer) <
fromIntegral (maxBound::Int)
-- overflow is undefined; see #7620
CmmMachOp mop args -> pprMachOpApp mop args
CmmStackSlot _ _ -> panic "pprExpr: CmmStackSlot not supported!"
pprLoad :: DynFlags -> CmmExpr -> CmmType -> SDoc
pprLoad dflags e ty
| width == W64, wordWidth dflags /= W64
= (if isFloatType ty then text "PK_DBL"
else text "PK_Word64")
<> parens (mkP_ <> pprExpr1 e)
| otherwise
= case e of
CmmReg r | isPtrReg r && width == wordWidth dflags && not (isFloatType ty)
-> char '*' <> pprAsPtrReg r
CmmRegOff r 0 | isPtrReg r && width == wordWidth dflags && not (isFloatType ty)
-> char '*' <> pprAsPtrReg r
CmmRegOff r off | isPtrReg r && width == wordWidth dflags
, off `rem` wORD_SIZE dflags == 0 && not (isFloatType ty)
-- ToDo: check that the offset is a word multiple?
-- (For tagging to work, I had to avoid unaligned loads. --ARY)
-> pprAsPtrReg r <> brackets (ppr (off `shiftR` wordShift dflags))
_other -> cLoad e ty
where
width = typeWidth ty
pprExpr1 :: CmmExpr -> SDoc
pprExpr1 (CmmLit lit) = pprLit1 lit
pprExpr1 e@(CmmReg _reg) = pprExpr e
pprExpr1 other = parens (pprExpr other)
-- --------------------------------------------------------------------------
-- MachOp applications
pprMachOpApp :: MachOp -> [CmmExpr] -> SDoc
pprMachOpApp op args
| isMulMayOfloOp op
= text "mulIntMayOflo" <> parens (commafy (map pprExpr args))
where isMulMayOfloOp (MO_U_MulMayOflo _) = True
isMulMayOfloOp (MO_S_MulMayOflo _) = True
isMulMayOfloOp _ = False
pprMachOpApp mop args
| Just ty <- machOpNeedsCast mop
= ty <> parens (pprMachOpApp' mop args)
| otherwise
= pprMachOpApp' mop args
-- Comparisons in C have type 'int', but we want type W_ (this is what
-- resultRepOfMachOp says). The other C operations inherit their type
-- from their operands, so no casting is required.
machOpNeedsCast :: MachOp -> Maybe SDoc
machOpNeedsCast mop
| isComparisonMachOp mop = Just mkW_
| otherwise = Nothing
pprMachOpApp' :: MachOp -> [CmmExpr] -> SDoc
pprMachOpApp' mop args
= case args of
-- dyadic
[x,y] -> pprArg x <+> pprMachOp_for_C mop <+> pprArg y
-- unary
[x] -> pprMachOp_for_C mop <> parens (pprArg x)
_ -> panic "PprC.pprMachOp : machop with wrong number of args"
where
-- Cast needed for signed integer ops
pprArg e | signedOp mop = sdocWithDynFlags $ \dflags ->
cCast (machRep_S_CType (typeWidth (cmmExprType dflags e))) e
| needsFCasts mop = sdocWithDynFlags $ \dflags ->
cCast (machRep_F_CType (typeWidth (cmmExprType dflags e))) e
| otherwise = pprExpr1 e
needsFCasts (MO_F_Eq _) = False
needsFCasts (MO_F_Ne _) = False
needsFCasts (MO_F_Neg _) = True
needsFCasts (MO_F_Quot _) = True
needsFCasts mop = floatComparison mop
-- --------------------------------------------------------------------------
-- Literals
pprLit :: CmmLit -> SDoc
pprLit lit = case lit of
CmmInt i rep -> pprHexVal i rep
CmmFloat f w -> parens (machRep_F_CType w) <> str
where d = fromRational f :: Double
str | isInfinite d && d < 0 = text "-INFINITY"
| isInfinite d = text "INFINITY"
| isNaN d = text "NAN"
| otherwise = text (show d)
-- these constants come from <math.h>
-- see #1861
CmmVec {} -> panic "PprC printing vector literal"
CmmBlock bid -> mkW_ <> pprCLabelAddr (infoTblLbl bid)
CmmHighStackMark -> panic "PprC printing high stack mark"
CmmLabel clbl -> mkW_ <> pprCLabelAddr clbl
CmmLabelOff clbl i -> mkW_ <> pprCLabelAddr clbl <> char '+' <> int i
CmmLabelDiffOff clbl1 _ i
-- WARNING:
-- * the lit must occur in the info table clbl2
-- * clbl1 must be an SRT, a slow entry point or a large bitmap
-> mkW_ <> pprCLabelAddr clbl1 <> char '+' <> int i
where
pprCLabelAddr lbl = char '&' <> ppr lbl
pprLit1 :: CmmLit -> SDoc
pprLit1 lit@(CmmLabelOff _ _) = parens (pprLit lit)
pprLit1 lit@(CmmLabelDiffOff _ _ _) = parens (pprLit lit)
pprLit1 lit@(CmmFloat _ _) = parens (pprLit lit)
pprLit1 other = pprLit other
-- ---------------------------------------------------------------------------
-- Static data
pprStatics :: DynFlags -> [CmmStatic] -> [SDoc]
pprStatics _ [] = []
pprStatics dflags (CmmStaticLit (CmmFloat f W32) : rest)
-- floats are padded to a word by padLitToWord, see #1852
| wORD_SIZE dflags == 8, CmmStaticLit (CmmInt 0 W32) : rest' <- rest
= pprLit1 (floatToWord dflags f) : pprStatics dflags rest'
| wORD_SIZE dflags == 4
= pprLit1 (floatToWord dflags f) : pprStatics dflags rest
| otherwise
= pprPanic "pprStatics: float" (vcat (map ppr' rest))
where ppr' (CmmStaticLit l) = sdocWithDynFlags $ \dflags ->
ppr (cmmLitType dflags l)
ppr' _other = text "bad static!"
pprStatics dflags (CmmStaticLit (CmmFloat f W64) : rest)
= map pprLit1 (doubleToWords dflags f) ++ pprStatics dflags rest
pprStatics dflags (CmmStaticLit (CmmInt i W64) : rest)
| wordWidth dflags == W32
= if wORDS_BIGENDIAN dflags
then pprStatics dflags (CmmStaticLit (CmmInt q W32) :
CmmStaticLit (CmmInt r W32) : rest)
else pprStatics dflags (CmmStaticLit (CmmInt r W32) :
CmmStaticLit (CmmInt q W32) : rest)
where r = i .&. 0xffffffff
q = i `shiftR` 32
pprStatics dflags (CmmStaticLit (CmmInt _ w) : _)
| w /= wordWidth dflags
= panic "pprStatics: cannot emit a non-word-sized static literal"
pprStatics dflags (CmmStaticLit lit : rest)
= pprLit1 lit : pprStatics dflags rest
pprStatics _ (other : _)
= pprPanic "pprWord" (pprStatic other)
pprStatic :: CmmStatic -> SDoc
pprStatic s = case s of
CmmStaticLit lit -> nest 4 (pprLit lit)
CmmUninitialised i -> nest 4 (mkC_ <> brackets (int i))
-- these should be inlined, like the old .hc
CmmString s' -> nest 4 (mkW_ <> parens(pprStringInCStyle s'))
-- ---------------------------------------------------------------------------
-- Block Ids
pprBlockId :: BlockId -> SDoc
pprBlockId b = char '_' <> ppr (getUnique b)
-- --------------------------------------------------------------------------
-- Print a MachOp in a way suitable for emitting via C.
--
pprMachOp_for_C :: MachOp -> SDoc
pprMachOp_for_C mop = case mop of
-- Integer operations
MO_Add _ -> char '+'
MO_Sub _ -> char '-'
MO_Eq _ -> text "=="
MO_Ne _ -> text "!="
MO_Mul _ -> char '*'
MO_S_Quot _ -> char '/'
MO_S_Rem _ -> char '%'
MO_S_Neg _ -> char '-'
MO_U_Quot _ -> char '/'
MO_U_Rem _ -> char '%'
-- & Floating-point operations
MO_F_Add _ -> char '+'
MO_F_Sub _ -> char '-'
MO_F_Neg _ -> char '-'
MO_F_Mul _ -> char '*'
MO_F_Quot _ -> char '/'
-- Signed comparisons
MO_S_Ge _ -> text ">="
MO_S_Le _ -> text "<="
MO_S_Gt _ -> char '>'
MO_S_Lt _ -> char '<'
-- & Unsigned comparisons
MO_U_Ge _ -> text ">="
MO_U_Le _ -> text "<="
MO_U_Gt _ -> char '>'
MO_U_Lt _ -> char '<'
-- & Floating-point comparisons
MO_F_Eq _ -> text "=="
MO_F_Ne _ -> text "!="
MO_F_Ge _ -> text ">="
MO_F_Le _ -> text "<="
MO_F_Gt _ -> char '>'
MO_F_Lt _ -> char '<'
-- Bitwise operations. Not all of these may be supported at all
-- sizes, and only integral MachReps are valid.
MO_And _ -> char '&'
MO_Or _ -> char '|'
MO_Xor _ -> char '^'
MO_Not _ -> char '~'
MO_Shl _ -> text "<<"
MO_U_Shr _ -> text ">>" -- unsigned shift right
MO_S_Shr _ -> text ">>" -- signed shift right
-- Conversions. Some of these will be NOPs, but never those that convert
-- between ints and floats.
-- Floating-point conversions use the signed variant.
-- We won't know to generate (void*) casts here, but maybe from
-- context elsewhere
-- noop casts
MO_UU_Conv from to | from == to -> empty
MO_UU_Conv _from to -> parens (machRep_U_CType to)
MO_SS_Conv from to | from == to -> empty
MO_SS_Conv _from to -> parens (machRep_S_CType to)
MO_FF_Conv from to | from == to -> empty
MO_FF_Conv _from to -> parens (machRep_F_CType to)
MO_SF_Conv _from to -> parens (machRep_F_CType to)
MO_FS_Conv _from to -> parens (machRep_S_CType to)
MO_S_MulMayOflo _ -> pprTrace "offending mop:"
(text "MO_S_MulMayOflo")
(panic $ "PprC.pprMachOp_for_C: MO_S_MulMayOflo"
++ " should have been handled earlier!")
MO_U_MulMayOflo _ -> pprTrace "offending mop:"
(text "MO_U_MulMayOflo")
(panic $ "PprC.pprMachOp_for_C: MO_U_MulMayOflo"
++ " should have been handled earlier!")
MO_V_Insert {} -> pprTrace "offending mop:"
(text "MO_V_Insert")
(panic $ "PprC.pprMachOp_for_C: MO_V_Insert"
++ " should have been handled earlier!")
MO_V_Extract {} -> pprTrace "offending mop:"
(text "MO_V_Extract")
(panic $ "PprC.pprMachOp_for_C: MO_V_Extract"
++ " should have been handled earlier!")
MO_V_Add {} -> pprTrace "offending mop:"
(text "MO_V_Add")
(panic $ "PprC.pprMachOp_for_C: MO_V_Add"
++ " should have been handled earlier!")
MO_V_Sub {} -> pprTrace "offending mop:"
(text "MO_V_Sub")
(panic $ "PprC.pprMachOp_for_C: MO_V_Sub"
++ " should have been handled earlier!")
MO_V_Mul {} -> pprTrace "offending mop:"
(text "MO_V_Mul")
(panic $ "PprC.pprMachOp_for_C: MO_V_Mul"
++ " should have been handled earlier!")
MO_VS_Quot {} -> pprTrace "offending mop:"
(text "MO_VS_Quot")
(panic $ "PprC.pprMachOp_for_C: MO_VS_Quot"
++ " should have been handled earlier!")
MO_VS_Rem {} -> pprTrace "offending mop:"
(text "MO_VS_Rem")
(panic $ "PprC.pprMachOp_for_C: MO_VS_Rem"
++ " should have been handled earlier!")
MO_VS_Neg {} -> pprTrace "offending mop:"
(text "MO_VS_Neg")
(panic $ "PprC.pprMachOp_for_C: MO_VS_Neg"
++ " should have been handled earlier!")
MO_VU_Quot {} -> pprTrace "offending mop:"
(text "MO_VU_Quot")
(panic $ "PprC.pprMachOp_for_C: MO_VU_Quot"
++ " should have been handled earlier!")
MO_VU_Rem {} -> pprTrace "offending mop:"
(text "MO_VU_Rem")
(panic $ "PprC.pprMachOp_for_C: MO_VU_Rem"
++ " should have been handled earlier!")
MO_VF_Insert {} -> pprTrace "offending mop:"
(text "MO_VF_Insert")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Insert"
++ " should have been handled earlier!")
MO_VF_Extract {} -> pprTrace "offending mop:"
(text "MO_VF_Extract")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Extract"
++ " should have been handled earlier!")
MO_VF_Add {} -> pprTrace "offending mop:"
(text "MO_VF_Add")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Add"
++ " should have been handled earlier!")
MO_VF_Sub {} -> pprTrace "offending mop:"
(text "MO_VF_Sub")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Sub"
++ " should have been handled earlier!")
MO_VF_Neg {} -> pprTrace "offending mop:"
(text "MO_VF_Neg")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Neg"
++ " should have been handled earlier!")
MO_VF_Mul {} -> pprTrace "offending mop:"
(text "MO_VF_Mul")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Mul"
++ " should have been handled earlier!")
MO_VF_Quot {} -> pprTrace "offending mop:"
(text "MO_VF_Quot")
(panic $ "PprC.pprMachOp_for_C: MO_VF_Quot"
++ " should have been handled earlier!")
signedOp :: MachOp -> Bool -- Argument type(s) are signed ints
signedOp (MO_S_Quot _) = True
signedOp (MO_S_Rem _) = True
signedOp (MO_S_Neg _) = True
signedOp (MO_S_Ge _) = True
signedOp (MO_S_Le _) = True
signedOp (MO_S_Gt _) = True
signedOp (MO_S_Lt _) = True
signedOp (MO_S_Shr _) = True
signedOp (MO_SS_Conv _ _) = True
signedOp (MO_SF_Conv _ _) = True
signedOp _ = False
floatComparison :: MachOp -> Bool -- comparison between float args
floatComparison (MO_F_Eq _) = True
floatComparison (MO_F_Ne _) = True
floatComparison (MO_F_Ge _) = True
floatComparison (MO_F_Le _) = True
floatComparison (MO_F_Gt _) = True
floatComparison (MO_F_Lt _) = True
floatComparison _ = False
-- ---------------------------------------------------------------------
-- tend to be implemented by foreign calls
pprCallishMachOp_for_C :: CallishMachOp -> SDoc
pprCallishMachOp_for_C mop
= case mop of
MO_F64_Pwr -> text "pow"
MO_F64_Sin -> text "sin"
MO_F64_Cos -> text "cos"
MO_F64_Tan -> text "tan"
MO_F64_Sinh -> text "sinh"
MO_F64_Cosh -> text "cosh"
MO_F64_Tanh -> text "tanh"
MO_F64_Asin -> text "asin"
MO_F64_Acos -> text "acos"
MO_F64_Atan -> text "atan"
MO_F64_Log -> text "log"
MO_F64_Exp -> text "exp"
MO_F64_Sqrt -> text "sqrt"
MO_F32_Pwr -> text "powf"
MO_F32_Sin -> text "sinf"
MO_F32_Cos -> text "cosf"
MO_F32_Tan -> text "tanf"
MO_F32_Sinh -> text "sinhf"
MO_F32_Cosh -> text "coshf"
MO_F32_Tanh -> text "tanhf"
MO_F32_Asin -> text "asinf"
MO_F32_Acos -> text "acosf"
MO_F32_Atan -> text "atanf"
MO_F32_Log -> text "logf"
MO_F32_Exp -> text "expf"
MO_F32_Sqrt -> text "sqrtf"
MO_WriteBarrier -> text "write_barrier"
MO_Memcpy _ -> text "memcpy"
MO_Memset _ -> text "memset"
MO_Memmove _ -> text "memmove"
(MO_BSwap w) -> ptext (sLit $ bSwapLabel w)
(MO_PopCnt w) -> ptext (sLit $ popCntLabel w)
(MO_Clz w) -> ptext (sLit $ clzLabel w)
(MO_Ctz w) -> ptext (sLit $ ctzLabel w)
(MO_AtomicRMW w amop) -> ptext (sLit $ atomicRMWLabel w amop)
(MO_Cmpxchg w) -> ptext (sLit $ cmpxchgLabel w)
(MO_AtomicRead w) -> ptext (sLit $ atomicReadLabel w)
(MO_AtomicWrite w) -> ptext (sLit $ atomicWriteLabel w)
(MO_UF_Conv w) -> ptext (sLit $ word2FloatLabel w)
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_SubWordC {} -> unsupported
MO_AddIntC {} -> unsupported
MO_SubIntC {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _ ) -> unsupported
--- we could support prefetch via "__builtin_prefetch"
--- Not adding it for now
where unsupported = panic ("pprCallishMachOp_for_C: " ++ show mop
++ " not supported!")
-- ---------------------------------------------------------------------
-- Useful #defines
--
mkJMP_, mkFN_, mkIF_ :: SDoc -> SDoc
mkJMP_ i = text "JMP_" <> parens i
mkFN_ i = text "FN_" <> parens i -- externally visible function
mkIF_ i = text "IF_" <> parens i -- locally visible
-- from includes/Stg.h
--
mkC_,mkW_,mkP_ :: SDoc
mkC_ = text "(C_)" -- StgChar
mkW_ = text "(W_)" -- StgWord
mkP_ = text "(P_)" -- StgWord*
-- ---------------------------------------------------------------------
--
-- Assignments
--
-- Generating assignments is what we're all about, here
--
pprAssign :: DynFlags -> CmmReg -> CmmExpr -> SDoc
-- dest is a reg, rhs is a reg
pprAssign _ r1 (CmmReg r2)
| isPtrReg r1 && isPtrReg r2
= hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, semi ]
-- dest is a reg, rhs is a CmmRegOff
pprAssign dflags r1 (CmmRegOff r2 off)
| isPtrReg r1 && isPtrReg r2 && (off `rem` wORD_SIZE dflags == 0)
= hcat [ pprAsPtrReg r1, equals, pprAsPtrReg r2, op, int off', semi ]
where
off1 = off `shiftR` wordShift dflags
(op,off') | off >= 0 = (char '+', off1)
| otherwise = (char '-', -off1)
-- dest is a reg, rhs is anything.
-- We can't cast the lvalue, so we have to cast the rhs if necessary. Casting
-- the lvalue elicits a warning from new GCC versions (3.4+).
pprAssign _ r1 r2
| isFixedPtrReg r1 = mkAssign (mkP_ <> pprExpr1 r2)
| Just ty <- strangeRegType r1 = mkAssign (parens ty <> pprExpr1 r2)
| otherwise = mkAssign (pprExpr r2)
where mkAssign x = if r1 == CmmGlobal BaseReg
then text "ASSIGN_BaseReg" <> parens x <> semi
else pprReg r1 <> text " = " <> x <> semi
-- ---------------------------------------------------------------------
-- Registers
pprCastReg :: CmmReg -> SDoc
pprCastReg reg
| isStrangeTypeReg reg = mkW_ <> pprReg reg
| otherwise = pprReg reg
-- True if (pprReg reg) will give an expression with type StgPtr. We
-- need to take care with pointer arithmetic on registers with type
-- StgPtr.
isFixedPtrReg :: CmmReg -> Bool
isFixedPtrReg (CmmLocal _) = False
isFixedPtrReg (CmmGlobal r) = isFixedPtrGlobalReg r
-- True if (pprAsPtrReg reg) will give an expression with type StgPtr
-- JD: THIS IS HORRIBLE AND SHOULD BE RENAMED, AT THE VERY LEAST.
-- THE GARBAGE WITH THE VNonGcPtr HELPS MATCH THE OLD CODE GENERATOR'S OUTPUT;
-- I'M NOT SURE IF IT SHOULD REALLY STAY THAT WAY.
isPtrReg :: CmmReg -> Bool
isPtrReg (CmmLocal _) = False
isPtrReg (CmmGlobal (VanillaReg _ VGcPtr)) = True -- if we print via pprAsPtrReg
isPtrReg (CmmGlobal (VanillaReg _ VNonGcPtr)) = False -- if we print via pprAsPtrReg
isPtrReg (CmmGlobal reg) = isFixedPtrGlobalReg reg
-- True if this global reg has type StgPtr
isFixedPtrGlobalReg :: GlobalReg -> Bool
isFixedPtrGlobalReg Sp = True
isFixedPtrGlobalReg Hp = True
isFixedPtrGlobalReg HpLim = True
isFixedPtrGlobalReg SpLim = True
isFixedPtrGlobalReg _ = False
-- True if in C this register doesn't have the type given by
-- (machRepCType (cmmRegType reg)), so it has to be cast.
isStrangeTypeReg :: CmmReg -> Bool
isStrangeTypeReg (CmmLocal _) = False
isStrangeTypeReg (CmmGlobal g) = isStrangeTypeGlobal g
isStrangeTypeGlobal :: GlobalReg -> Bool
isStrangeTypeGlobal CCCS = True
isStrangeTypeGlobal CurrentTSO = True
isStrangeTypeGlobal CurrentNursery = True
isStrangeTypeGlobal BaseReg = True
isStrangeTypeGlobal r = isFixedPtrGlobalReg r
strangeRegType :: CmmReg -> Maybe SDoc
strangeRegType (CmmGlobal CCCS) = Just (text "struct CostCentreStack_ *")
strangeRegType (CmmGlobal CurrentTSO) = Just (text "struct StgTSO_ *")
strangeRegType (CmmGlobal CurrentNursery) = Just (text "struct bdescr_ *")
strangeRegType (CmmGlobal BaseReg) = Just (text "struct StgRegTable_ *")
strangeRegType _ = Nothing
-- pprReg just prints the register name.
--
pprReg :: CmmReg -> SDoc
pprReg r = case r of
CmmLocal local -> pprLocalReg local
CmmGlobal global -> pprGlobalReg global
pprAsPtrReg :: CmmReg -> SDoc
pprAsPtrReg (CmmGlobal (VanillaReg n gcp))
= WARN( gcp /= VGcPtr, ppr n ) char 'R' <> int n <> text ".p"
pprAsPtrReg other_reg = pprReg other_reg
pprGlobalReg :: GlobalReg -> SDoc
pprGlobalReg gr = case gr of
VanillaReg n _ -> char 'R' <> int n <> text ".w"
-- pprGlobalReg prints a VanillaReg as a .w regardless
-- Example: R1.w = R1.w & (-0x8UL);
-- JMP_(*R1.p);
FloatReg n -> char 'F' <> int n
DoubleReg n -> char 'D' <> int n
LongReg n -> char 'L' <> int n
Sp -> text "Sp"
SpLim -> text "SpLim"
Hp -> text "Hp"
HpLim -> text "HpLim"
CCCS -> text "CCCS"
CurrentTSO -> text "CurrentTSO"
CurrentNursery -> text "CurrentNursery"
HpAlloc -> text "HpAlloc"
BaseReg -> text "BaseReg"
EagerBlackholeInfo -> text "stg_EAGER_BLACKHOLE_info"
GCEnter1 -> text "stg_gc_enter_1"
GCFun -> text "stg_gc_fun"
other -> panic $ "pprGlobalReg: Unsupported register: " ++ show other
pprLocalReg :: LocalReg -> SDoc
pprLocalReg (LocalReg uniq _) = char '_' <> ppr uniq
-- -----------------------------------------------------------------------------
-- Foreign Calls
pprCall :: SDoc -> CCallConv -> [Hinted CmmFormal] -> [Hinted CmmActual] -> SDoc
pprCall ppr_fn cconv results args
| not (is_cishCC cconv)
= panic $ "pprCall: unknown calling convention"
| otherwise
=
ppr_assign results (ppr_fn <> parens (commafy (map pprArg args))) <> semi
where
ppr_assign [] rhs = rhs
ppr_assign [(one,hint)] rhs
= pprLocalReg one <> text " = "
<> pprUnHint hint (localRegType one) <> rhs
ppr_assign _other _rhs = panic "pprCall: multiple results"
pprArg (expr, AddrHint)
= cCast (text "void *") expr
-- see comment by machRepHintCType below
pprArg (expr, SignedHint)
= sdocWithDynFlags $ \dflags ->
cCast (machRep_S_CType $ typeWidth $ cmmExprType dflags expr) expr
pprArg (expr, _other)
= pprExpr expr
pprUnHint AddrHint rep = parens (machRepCType rep)
pprUnHint SignedHint rep = parens (machRepCType rep)
pprUnHint _ _ = empty
-- Currently we only have these two calling conventions, but this might
-- change in the future...
is_cishCC :: CCallConv -> Bool
is_cishCC CCallConv = True
is_cishCC CApiConv = True
is_cishCC StdCallConv = True
is_cishCC PrimCallConv = False
is_cishCC JavaScriptCallConv = False
-- ---------------------------------------------------------------------
-- Find and print local and external declarations for a list of
-- Cmm statements.
--
pprTempAndExternDecls :: [CmmBlock] -> (SDoc{-temps-}, SDoc{-externs-})
pprTempAndExternDecls stmts
= (vcat (map pprTempDecl (uniqSetToList temps)),
vcat (map (pprExternDecl False{-ToDo-}) (Map.keys lbls)))
where (temps, lbls) = runTE (mapM_ te_BB stmts)
pprDataExterns :: [CmmStatic] -> SDoc
pprDataExterns statics
= vcat (map (pprExternDecl False{-ToDo-}) (Map.keys lbls))
where (_, lbls) = runTE (mapM_ te_Static statics)
pprTempDecl :: LocalReg -> SDoc
pprTempDecl l@(LocalReg _ rep)
= hcat [ machRepCType rep, space, pprLocalReg l, semi ]
pprExternDecl :: Bool -> CLabel -> SDoc
pprExternDecl _in_srt lbl
-- do not print anything for "known external" things
| not (needsCDecl lbl) = empty
| Just sz <- foreignLabelStdcallInfo lbl = stdcall_decl sz
| otherwise =
hcat [ visibility, label_type lbl,
lparen, ppr lbl, text ");" ]
where
label_type lbl | isForeignLabel lbl && isCFunctionLabel lbl = text "FF_"
| isCFunctionLabel lbl = text "F_"
| otherwise = text "I_"
visibility
| externallyVisibleCLabel lbl = char 'E'
| otherwise = char 'I'
-- If the label we want to refer to is a stdcall function (on Windows) then
-- we must generate an appropriate prototype for it, so that the C compiler will
-- add the @n suffix to the label (#2276)
stdcall_decl sz = sdocWithDynFlags $ \dflags ->
text "extern __attribute__((stdcall)) void " <> ppr lbl
<> parens (commafy (replicate (sz `quot` wORD_SIZE dflags) (machRep_U_CType (wordWidth dflags))))
<> semi
type TEState = (UniqSet LocalReg, Map CLabel ())
newtype TE a = TE { unTE :: TEState -> (a, TEState) }
instance Functor TE where
fmap = liftM
instance Applicative TE where
pure a = TE $ \s -> (a, s)
(<*>) = ap
instance Monad TE where
TE m >>= k = TE $ \s -> case m s of (a, s') -> unTE (k a) s'
return = pure
te_lbl :: CLabel -> TE ()
te_lbl lbl = TE $ \(temps,lbls) -> ((), (temps, Map.insert lbl () lbls))
te_temp :: LocalReg -> TE ()
te_temp r = TE $ \(temps,lbls) -> ((), (addOneToUniqSet temps r, lbls))
runTE :: TE () -> TEState
runTE (TE m) = snd (m (emptyUniqSet, Map.empty))
te_Static :: CmmStatic -> TE ()
te_Static (CmmStaticLit lit) = te_Lit lit
te_Static _ = return ()
te_BB :: CmmBlock -> TE ()
te_BB block = mapM_ te_Stmt (blockToList mid) >> te_Stmt last
where (_, mid, last) = blockSplit block
te_Lit :: CmmLit -> TE ()
te_Lit (CmmLabel l) = te_lbl l
te_Lit (CmmLabelOff l _) = te_lbl l
te_Lit (CmmLabelDiffOff l1 _ _) = te_lbl l1
te_Lit _ = return ()
te_Stmt :: CmmNode e x -> TE ()
te_Stmt (CmmAssign r e) = te_Reg r >> te_Expr e
te_Stmt (CmmStore l r) = te_Expr l >> te_Expr r
te_Stmt (CmmUnsafeForeignCall target rs es)
= do te_Target target
mapM_ te_temp rs
mapM_ te_Expr es
te_Stmt (CmmCondBranch e _ _ _) = te_Expr e
te_Stmt (CmmSwitch e _) = te_Expr e
te_Stmt (CmmCall { cml_target = e }) = te_Expr e
te_Stmt _ = return ()
te_Target :: ForeignTarget -> TE ()
te_Target (ForeignTarget e _) = te_Expr e
te_Target (PrimTarget{}) = return ()
te_Expr :: CmmExpr -> TE ()
te_Expr (CmmLit lit) = te_Lit lit
te_Expr (CmmLoad e _) = te_Expr e
te_Expr (CmmReg r) = te_Reg r
te_Expr (CmmMachOp _ es) = mapM_ te_Expr es
te_Expr (CmmRegOff r _) = te_Reg r
te_Expr (CmmStackSlot _ _) = panic "te_Expr: CmmStackSlot not supported!"
te_Reg :: CmmReg -> TE ()
te_Reg (CmmLocal l) = te_temp l
te_Reg _ = return ()
-- ---------------------------------------------------------------------
-- C types for MachReps
cCast :: SDoc -> CmmExpr -> SDoc
cCast ty expr = parens ty <> pprExpr1 expr
cLoad :: CmmExpr -> CmmType -> SDoc
cLoad expr rep
= sdocWithPlatform $ \platform ->
if bewareLoadStoreAlignment (platformArch platform)
then let decl = machRepCType rep <+> text "x" <> semi
struct = text "struct" <+> braces (decl)
packed_attr = text "__attribute__((packed))"
cast = parens (struct <+> packed_attr <> char '*')
in parens (cast <+> pprExpr1 expr) <> text "->x"
else char '*' <> parens (cCast (machRepPtrCType rep) expr)
where -- On these platforms, unaligned loads are known to cause problems
bewareLoadStoreAlignment ArchAlpha = True
bewareLoadStoreAlignment ArchMipseb = True
bewareLoadStoreAlignment ArchMipsel = True
bewareLoadStoreAlignment (ArchARM {}) = True
bewareLoadStoreAlignment ArchARM64 = True
-- Pessimistically assume that they will also cause problems
-- on unknown arches
bewareLoadStoreAlignment ArchUnknown = True
bewareLoadStoreAlignment _ = False
isCmmWordType :: DynFlags -> CmmType -> Bool
-- True of GcPtrReg/NonGcReg of native word size
isCmmWordType dflags ty = not (isFloatType ty)
&& typeWidth ty == wordWidth dflags
-- This is for finding the types of foreign call arguments. For a pointer
-- argument, we always cast the argument to (void *), to avoid warnings from
-- the C compiler.
machRepHintCType :: CmmType -> ForeignHint -> SDoc
machRepHintCType _ AddrHint = text "void *"
machRepHintCType rep SignedHint = machRep_S_CType (typeWidth rep)
machRepHintCType rep _other = machRepCType rep
machRepPtrCType :: CmmType -> SDoc
machRepPtrCType r
= sdocWithDynFlags $ \dflags ->
if isCmmWordType dflags r then text "P_"
else machRepCType r <> char '*'
machRepCType :: CmmType -> SDoc
machRepCType ty | isFloatType ty = machRep_F_CType w
| otherwise = machRep_U_CType w
where
w = typeWidth ty
machRep_F_CType :: Width -> SDoc
machRep_F_CType W32 = text "StgFloat" -- ToDo: correct?
machRep_F_CType W64 = text "StgDouble"
machRep_F_CType _ = panic "machRep_F_CType"
machRep_U_CType :: Width -> SDoc
machRep_U_CType w
= sdocWithDynFlags $ \dflags ->
case w of
_ | w == wordWidth dflags -> text "W_"
W8 -> text "StgWord8"
W16 -> text "StgWord16"
W32 -> text "StgWord32"
W64 -> text "StgWord64"
_ -> panic "machRep_U_CType"
machRep_S_CType :: Width -> SDoc
machRep_S_CType w
= sdocWithDynFlags $ \dflags ->
case w of
_ | w == wordWidth dflags -> text "I_"
W8 -> text "StgInt8"
W16 -> text "StgInt16"
W32 -> text "StgInt32"
W64 -> text "StgInt64"
_ -> panic "machRep_S_CType"
-- ---------------------------------------------------------------------
-- print strings as valid C strings
pprStringInCStyle :: [Word8] -> SDoc
pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
-- ---------------------------------------------------------------------------
-- Initialising static objects with floating-point numbers. We can't
-- just emit the floating point number, because C will cast it to an int
-- by rounding it. We want the actual bit-representation of the float.
--
-- Consider a concrete C example:
-- double d = 2.5e-10;
-- float f = 2.5e-10f;
--
-- int * i2 = &d; printf ("i2: %08X %08X\n", i2[0], i2[1]);
-- long long * l = &d; printf (" l: %016llX\n", l[0]);
-- int * i = &f; printf (" i: %08X\n", i[0]);
-- Result on 64-bit LE (x86_64):
-- i2: E826D695 3DF12E0B
-- l: 3DF12E0BE826D695
-- i: 2F89705F
-- Result on 32-bit BE (m68k):
-- i2: 3DF12E0B E826D695
-- l: 3DF12E0BE826D695
-- i: 2F89705F
--
-- The trick here is to notice that binary representation does not
-- change much: only Word32 values get swapped on LE hosts / targets.
-- This is a hack to turn the floating point numbers into ints that we
-- can safely initialise to static locations.
castFloatToWord32Array :: STUArray s Int Float -> ST s (STUArray s Int Word32)
castFloatToWord32Array = U.castSTUArray
castDoubleToWord64Array :: STUArray s Int Double -> ST s (STUArray s Int Word64)
castDoubleToWord64Array = U.castSTUArray
floatToWord :: DynFlags -> Rational -> CmmLit
floatToWord dflags r
= runST (do
arr <- newArray_ ((0::Int),0)
writeArray arr 0 (fromRational r)
arr' <- castFloatToWord32Array arr
w32 <- readArray arr' 0
return (CmmInt (toInteger w32 `shiftL` wo) (wordWidth dflags))
)
where wo | wordWidth dflags == W64
, wORDS_BIGENDIAN dflags = 32
| otherwise = 0
doubleToWords :: DynFlags -> Rational -> [CmmLit]
doubleToWords dflags r
= runST (do
arr <- newArray_ ((0::Int),1)
writeArray arr 0 (fromRational r)
arr' <- castDoubleToWord64Array arr
w64 <- readArray arr' 0
return (pprWord64 w64)
)
where targetWidth = wordWidth dflags
targetBE = wORDS_BIGENDIAN dflags
pprWord64 w64
| targetWidth == W64 =
[ CmmInt (toInteger w64) targetWidth ]
| targetWidth == W32 =
[ CmmInt (toInteger targetW1) targetWidth
, CmmInt (toInteger targetW2) targetWidth
]
| otherwise = panic "doubleToWords.pprWord64"
where (targetW1, targetW2)
| targetBE = (wHi, wLo)
| otherwise = (wLo, wHi)
wHi = w64 `shiftR` 32
wLo = w64 .&. 0xFFFFffff
-- ---------------------------------------------------------------------------
-- Utils
wordShift :: DynFlags -> Int
wordShift dflags = widthInLog (wordWidth dflags)
commafy :: [SDoc] -> SDoc
commafy xs = hsep $ punctuate comma xs
-- Print in C hex format: 0x13fa
pprHexVal :: Integer -> Width -> SDoc
pprHexVal w rep
| w < 0 = parens (char '-' <>
text "0x" <> intToDoc (-w) <> repsuffix rep)
| otherwise = text "0x" <> intToDoc w <> repsuffix rep
where
-- type suffix for literals:
-- Integer literals are unsigned in Cmm/C. We explicitly cast to
-- signed values for doing signed operations, but at all other
-- times values are unsigned. This also helps eliminate occasional
-- warnings about integer overflow from gcc.
repsuffix W64 = sdocWithDynFlags $ \dflags ->
if cINT_SIZE dflags == 8 then char 'U'
else if cLONG_SIZE dflags == 8 then text "UL"
else if cLONG_LONG_SIZE dflags == 8 then text "ULL"
else panic "pprHexVal: Can't find a 64-bit type"
repsuffix _ = char 'U'
intToDoc :: Integer -> SDoc
intToDoc i = case truncInt i of
0 -> char '0'
v -> go v
-- We need to truncate value as Cmm backend does not drop
-- redundant bits to ease handling of negative values.
-- Thus the following Cmm code on 64-bit arch, like amd64:
-- CInt v;
-- v = {something};
-- if (v == %lobits32(-1)) { ...
-- leads to the following C code:
-- StgWord64 v = (StgWord32)({something});
-- if (v == 0xFFFFffffFFFFffffU) { ...
-- Such code is incorrect as it promotes both operands to StgWord64
-- and the whole condition is always false.
truncInt :: Integer -> Integer
truncInt i =
case rep of
W8 -> i `rem` (2^(8 :: Int))
W16 -> i `rem` (2^(16 :: Int))
W32 -> i `rem` (2^(32 :: Int))
W64 -> i `rem` (2^(64 :: Int))
_ -> panic ("pprHexVal/truncInt: C backend can't encode "
++ show rep ++ " literals")
go 0 = empty
go w' = go q <> dig
where
(q,r) = w' `quotRem` 16
dig | r < 10 = char (chr (fromInteger r + ord '0'))
| otherwise = char (chr (fromInteger r - 10 + ord 'a'))
| GaloisInc/halvm-ghc | compiler/cmm/PprC.hs | bsd-3-clause | 48,991 | 0 | 20 | 14,987 | 11,918 | 5,927 | 5,991 | 834 | 63 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ImplicitParams #-}
{-# Language OverloadedStrings #-}
{-# OPTIONS_GHC -Wall -fno-warn-unused-top-binds #-}
import qualified Data.ByteString as BS
import qualified Data.ByteString.UTF8 as BS8
import Data.Char (isSpace)
import Data.List (dropWhileEnd, isPrefixOf)
import Data.Maybe (catMaybes)
import System.Directory (listDirectory, doesDirectoryExist, doesFileExist, removeFile)
import System.Exit (ExitCode(..))
import System.FilePath
((<.>), (</>), takeBaseName, takeExtension, replaceExtension, takeFileName, takeDirectory)
import System.IO (IOMode(..), Handle, withFile, hClose, hGetContents, hGetLine, openFile)
import System.IO.Temp (withSystemTempFile)
import System.Environment (setEnv)
import qualified System.Process as Proc
import Test.Tasty (defaultMain, testGroup, TestTree)
import Test.Tasty.HUnit (Assertion, testCaseSteps, assertBool, assertFailure)
import Test.Tasty.Golden (findByExtension)
import Test.Tasty.Golden.Advanced (goldenTest)
import Test.Tasty.ExpectedFailure (expectFailBecause)
import qualified Mir.Language as Mir
import qualified Mir.Compositional as Mir
import qualified Mir.Cryptol as Mir
import qualified Crux as Crux
import qualified Crux.Config.Common as Crux
import qualified Data.AIG.Interface as AIG
import qualified Config
import qualified Config.Schema as Config
type OracleTest = FilePath -> String -> (String -> IO ()) -> Assertion
-- Don't show any debug output when testing (SAWInterface)
debugLevel :: Int
debugLevel = 0
-- | Check whether an input file is expected to fail based on a comment in the first line.
expectedFail :: FilePath -> IO (Maybe String)
expectedFail fn =
withFile fn ReadMode $ \h ->
do firstLine <- hGetLine h
return $
if failMarker `isPrefixOf` firstLine
then Just (drop (length failMarker) firstLine)
else Nothing
where failMarker = "// FAIL: "
-- TODO: remove this - copy-pasted from Crux/Options.hs for compatibility with
-- old mainline crucible
defaultCruxOptions :: Crux.CruxOptions
defaultCruxOptions = case res of
Left x -> error $ "failed to compute default crux options: " ++ show x
Right x -> x
where
ss = Crux.cfgFile Crux.cruxOptions
res = Config.loadValue (Config.sectionsSpec "crux" ss) (Config.Sections () [])
data RunCruxMode = RcmConcrete | RcmSymbolic | RcmCoverage
deriving (Show, Eq)
runCrux :: FilePath -> Handle -> RunCruxMode -> IO ()
runCrux rustFile outHandle mode = Mir.withMirLogging $ do
-- goalTimeout is bumped from 60 to 180 because scalar.rs symbolic
-- verification runs close to the timeout, causing flaky results
-- (especially in CI).
let quiet = True
let outOpts = (Crux.outputOptions defaultCruxOptions)
{ Crux.simVerbose = 0
, Crux.quietMode = quiet
}
let options = (defaultCruxOptions { Crux.outputOptions = outOpts,
Crux.inputFiles = [rustFile],
Crux.globalTimeout = Just 180,
Crux.goalTimeout = Just 180,
Crux.solver = "z3",
Crux.checkPathSat = (mode == RcmCoverage),
Crux.outDir = case mode of
RcmCoverage -> getOutputDir rustFile
_ -> "",
Crux.branchCoverage = (mode == RcmCoverage) } ,
Mir.defaultMirOptions { Mir.printResultOnly = (mode == RcmConcrete),
Mir.defaultRlibsDir = "../deps/crucible/crux-mir/rlibs" })
let ?outputConfig = Crux.mkOutputConfig (outHandle, False) (outHandle, False)
Mir.mirLoggingToSayWhat (Just $ Crux.outputOptions $ fst options)
setEnv "CRYPTOLPATH" "."
_exitCode <- Mir.runTestsWithExtraOverrides overrides options
return ()
where
overrides :: Mir.BindExtraOverridesFn
overrides = Mir.compositionalOverrides `Mir.orOverride` Mir.cryptolOverrides
getOutputDir :: FilePath -> FilePath
getOutputDir rustFile = takeDirectory rustFile </> "out"
cruxOracleTest :: FilePath -> String -> (String -> IO ()) -> Assertion
cruxOracleTest dir name step = do
step "Compiling and running oracle program"
oracleOut <- compileAndRun dir name >>= \case
Nothing -> assertFailure "failed to compile and run"
Just out -> return out
let orOut = dropWhileEnd isSpace oracleOut
step ("Oracle output: " ++ orOut)
let rustFile = dir </> name <.> "rs"
cruxOut <- withSystemTempFile name $ \tempName h -> do
runCrux rustFile h RcmConcrete
hClose h
h' <- openFile tempName ReadMode
out <- hGetContents h'
length out `seq` hClose h'
return $ dropWhileEnd isSpace out
step ("Crux output: " ++ cruxOut ++ "\n")
assertBool "crux doesn't match oracle" (orOut == cruxOut)
symbTest :: FilePath -> IO TestTree
symbTest dir =
do exists <- doesDirectoryExist dir
rustFiles <- if exists then findByExtension [".rs"] dir else return []
return $
testGroup "Output testing"
[ doGoldenTest (takeBaseName rustFile) goodFile outFile $
withFile outFile WriteMode $ \h ->
runCrux rustFile h RcmSymbolic
| rustFile <- rustFiles
-- Skip hidden files, such as editor swap files
, not $ "." `isPrefixOf` takeFileName rustFile
, let goodFile = replaceExtension rustFile ".good"
, let outFile = replaceExtension rustFile ".out"
]
coverageTests :: FilePath -> IO TestTree
coverageTests dir = do
exists <- doesDirectoryExist dir
rustFiles <- if exists then findByExtension [".rs"] dir else return []
return $ testGroup "Output testing"
[ doGoldenTest rustFile goodFile outFile (doTest rustFile outFile)
| rustFile <- rustFiles
-- Skip hidden files, such as editor swap files
, not $ "." `isPrefixOf` takeFileName rustFile
, let goodFile = replaceExtension rustFile ".good"
, let outFile = replaceExtension rustFile ".out"
]
where
doTest rustFile outFile = do
let logFile = replaceExtension rustFile ".crux.log"
withFile logFile WriteMode $ \h -> runCrux rustFile h RcmCoverage
let reportDir = getOutputDir rustFile </> takeBaseName rustFile
reportFiles <- findByExtension [".js"] reportDir
out <- Proc.readProcess "cargo"
(["run", "--manifest-path", "report-coverage/Cargo.toml", "--quiet",
"--", "--no-color"] ++ reportFiles) ""
writeFile outFile out
doGoldenTest :: FilePath -> FilePath -> FilePath -> IO () -> TestTree
doGoldenTest rustFile goodFile outFile act = goldenTest (takeBaseName rustFile)
(BS.readFile goodFile)
(act >> BS.readFile outFile)
(\good out -> return $ if good == out then Nothing else
Just $ "files " ++ goodFile ++ " and " ++ outFile ++ " differ; " ++
goodFile ++ " contains:\n" ++ BS8.toString out)
(\out -> BS.writeFile goodFile out)
main :: IO ()
main = defaultMain =<< suite
suite :: IO TestTree
suite = do
let ?debug = 0 :: Int
let ?assertFalseOnError = True
let ?printCrucible = False
trees <- sequence
[ testGroup "crux concrete" <$> sequence [ testDir cruxOracleTest "test/conc_eval/" ]
, testGroup "crux symbolic" <$> sequence [ symbTest "test/symb_eval" ]
, testGroup "crux coverage" <$> sequence [ coverageTests "test/coverage" ]
]
return $ testGroup "crux-mir" trees
-- For newSAWCoreBackend
proxy :: AIG.Proxy AIG.BasicLit AIG.BasicGraph
proxy = AIG.basicProxy
-- | Compile using 'rustc' and run executable
compileAndRun :: FilePath -> String -> IO (Maybe String)
compileAndRun dir name = do
(ec, _, err) <- Proc.readProcessWithExitCode "rustc"
[dir </> name <.> "rs", "--cfg", "with_main"
, "--extern", "byteorder=rlibs_native/libbyteorder.rlib"
, "--extern", "bytes=rlibs_native/libbytes.rlib"] ""
case ec of
ExitFailure _ -> do
putStrLn $ "rustc compilation failed for " ++ name
putStrLn "error output:"
putStrLn err
return Nothing
ExitSuccess -> do
let execFile = "." </> name
(ec', out, _) <- Proc.readProcessWithExitCode execFile [] ""
doesFileExist execFile >>= \case
True -> removeFile execFile
False -> return ()
case ec' of
ExitFailure _ -> do
putStrLn $ "non-zero exit code for test executable " ++ name
return Nothing
ExitSuccess -> return $ Just out
testDir :: OracleTest -> FilePath -> IO TestTree
testDir oracleTest dir = do
let gen f | "." `isPrefixOf` takeBaseName f = return Nothing
gen f | takeExtension f == ".rs" = do
shouldFail <- expectedFail (dir </> f)
case shouldFail of
Nothing -> return (Just (testCaseSteps name (oracleTest dir name)))
Just why -> return (Just (expectFailBecause why (testCaseSteps name (oracleTest dir name))))
where name = takeBaseName f
gen f = doesDirectoryExist (dir </> f) >>= \case
False -> return Nothing
True -> Just <$> testDir oracleTest (dir </> f)
exists <- doesDirectoryExist dir
fs <- if exists then listDirectory dir else return []
tcs <- mapM gen fs
return (testGroup (takeBaseName dir) (catMaybes tcs))
| GaloisInc/saw-script | crux-mir-comp/test/Test.hs | bsd-3-clause | 9,682 | 3 | 24 | 2,580 | 2,523 | 1,300 | 1,223 | 189 | 6 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Lib
( mainFunc,
module ClassyPrelude,
module Haskakafka
) where
import Common
import Config
import Fortune
import Kansha
import Threading
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens
import GHC.IO.Handle hiding (hGetLine)
import System.Command
import System.IO (hReady)
import ClassyPrelude
import Haskakafka
startRink :: Text -> IO (Maybe (Handle, Handle))
startRink rinkPath = do
let rinkCmd = rinkPath ++ " -"
(hInM, hOutM, _, _) <- createProcess (shell $ unpack rinkCmd)
{ std_out = CreatePipe, std_in = CreatePipe }
return $ do
hIn <- hInM
hOut <- hOutM
return (hIn, hOut)
readHandleUntilNotReady :: Handle -> IO Text
readHandleUntilNotReady hIn =
let readOutput handle results = do
handleReady <- hReady handle
case handleReady of
False -> return (unlines results)
True -> do
line <- hGetLine handle
readOutput handle (mappend results [line])
in
readOutput hIn []
runRinkCmd :: (Handle, Handle) -> Text -> IO Text
runRinkCmd (hIn, hOut) cmdStr = do
let newCmdStr = ((replaceSeqStrictText ">" ">") . (replaceSeqStrictText "<" "<")) cmdStr
hPutStrLn hIn newCmdStr
hFlush hIn
--readHandleUntilNotReady hOut
hGetLine hOut
rinkCmdLooper :: (Handle, Handle) -> TChan SlackMessage -> TChan Text -> IO ()
rinkCmdLooper (hIn, hOut) cmdQueue outQueue = do
cmd <- atomically $ readTChan cmdQueue
let rawInput = message cmd
case (tailMay $ words rawInput) of
Nothing -> rinkCmdLooper (hIn, hOut) cmdQueue outQueue
Just others -> do
output <- runRinkCmd (hIn, hOut) (unwords others)
let outputStripped = stripSuffix "\n" output
case outputStripped of
Nothing -> atomically $ writeTChan outQueue $ slackPayloadWithChannel (channel cmd) output
Just stripped -> atomically $ writeTChan outQueue $ slackPayloadWithChannel (channel cmd) stripped
rinkCmdLooper (hIn, hOut) cmdQueue outQueue
consumer :: TChan Text -> Kafka -> KafkaTopic -> IO ()
consumer queue kafka topic = do
messageE <- consumeMessage topic 0 10000
case messageE of
Left (KafkaResponseError _) -> return ()
Left err -> do
putStrLn $ "Kafka error: " ++ tshow err
Right msg -> do
let writeQueue = writeTChan queue
atomically $ (writeQueue . asText . decodeUtf8 . asByteString . messagePayload) msg
consumer queue kafka topic
producer :: TChan Text -> Kafka -> KafkaTopic -> IO ()
producer queue kafka topic = do
msg <- atomically $ readTChan queue
putStrLn $ "producer: " ++ msg
produceMessage topic KafkaUnassignedPartition (KafkaProduceMessage $ encodeUtf8 msg)
producer queue kafka topic
echoEmitter :: SlackMessage -> IO Text
echoEmitter msg = do
return $ slackPayloadWithChannel (channel msg) "Hollo!"
papikaEmitter :: SlackMessage -> IO Text
papikaEmitter msg = return $ slackPayloadWithChannel (channel msg) "Cocona!"
kafkaProducerThread :: Text -> Text -> TChan Text -> IO ()
kafkaProducerThread brokerString topicName producerQueue = do
withKafkaProducer [] [] (unpack brokerString) (unpack topicName) (producer producerQueue)
return ()
kafkaConsumerThread :: Text -> Text -> TChan Text -> IO ()
kafkaConsumerThread brokerString topicName consumerQueue = do
withKafkaConsumer [] [("offset.store.method", "file")] (unpack brokerString) (unpack topicName) 0 (KafkaOffsetStored) (consumer consumerQueue)
return ()
emitterThread :: (TChan SlackMessage -> TChan Text -> STM ()) -> TChan SlackMessage -> TChan Text -> IO ()
emitterThread emitter inQueue outQueue = do
atomically $ emitter inQueue outQueue
emitterThread emitter inQueue outQueue
rinkThread :: Text -> TChan SlackMessage -> TChan Text -> IO ()
rinkThread rinkPath inputQueue outputQueue = do
handlesM <- startRink rinkPath
case handlesM of
Nothing -> do
putStrLn "Error opening up rink"
return ()
Just (hIn, hOut) -> do
hSetBinaryMode hIn False
hSetBinaryMode hOut False
rinkCmdLooper (hIn, hOut) inputQueue outputQueue
mainFunc :: FilePath -> IO ()
mainFunc configPath = do
botConfigE <- getBotConfig configPath
case botConfigE of
Left err -> do
hPutStrLn stderr $ asText "Could not parse config, using defaults"
hPutStrLn stderr $ tshow err
Right _ -> return ()
putStrLn "Starting Kokona"
consumerQueue <- newTChanIO
producerQueue <- newTChanIO
let (brokerString, consumerTopicString, producerTopicString, rinkPathStr) =
case botConfigE of
Left _ -> ("localhost:9092", "consumer", "producer", "rink")
Right cfg -> (
(brokerAddr cfg), (consumerTopic cfg), (producerTopic cfg), (rinkPath cfg)
)
let holloAcceptor = startMessageAcceptor "!hollo"
let calcAcceptor = startMessageAcceptor "!calc"
let dhggsAcceptor = startMessageAcceptor "dhggs"
let fortuneAcceptor = startMessageAcceptor "!fortune"
let papikaAcceptor = textInMessageAcceptor "papika"
let cmdThreadWithQueue = botCommandThread consumerQueue producerQueue
cmdThreadWithQueue holloAcceptor (loopProcessor echoEmitter)
cmdThreadWithQueue calcAcceptor (rinkThread rinkPathStr)
cmdThreadWithQueue dhggsAcceptor (loopProcessor kanshaEmitter)
cmdThreadWithQueue fortuneAcceptor (loopProcessor fortuneEmitter)
-- cmdThreadWithQueue papikaAcceptor (loopProcessor papikaEmitter)
producerTId <- fork (kafkaProducerThread brokerString producerTopicString producerQueue)
kafkaConsumerThread brokerString consumerTopicString consumerQueue
putStrLn $ tshow producerTId
| Koshroy/kokona | src/Lib.hs | bsd-3-clause | 5,671 | 0 | 19 | 1,128 | 1,735 | 829 | 906 | 131 | 3 |
data DT = DT Integer deriving Show
newtype NT = NT Integer deriving Show
checkDT :: DT -> String
checkDT (DT _) = "OK!"
checkNT :: NT -> String
checkNT (NT _) = "OK!"
| YoshikuniJujo/funpaala | samples/26_type_class/newtypeDiff.hs | bsd-3-clause | 170 | 0 | 7 | 37 | 70 | 38 | 32 | 6 | 1 |
{-# LANGUAGE BangPatterns, MultiParamTypeClasses #-}
{-# OPTIONS -fno-warn-orphans #-}
module Data.Digest.Groestl384 (
groestl384,
Groestl384Digest (..),
GroestlCtx,
Hash(..),
hash,
hash',
printAsHex
) where
import Data.Int (Int64)
import Data.Word (Word64)
import qualified Data.ByteString.Lazy as L (ByteString)
import Data.Vector.Unboxed (Vector, fromList)
import Control.Monad (foldM, liftM)
import Control.Monad.ST (runST)
import Crypto.Classes
import Data.Tagged
import Data.Serialize
import Prelude hiding (truncate)
import Data.Digest.GroestlMutable
groestl384 :: Int64 -> L.ByteString -> L.ByteString
groestl384 dataBitLen
| dataBitLen < 0 = error "The data length can not be less than 0"
| otherwise = truncate G384 . outputTransform 1024 . compress . parse
where parse = parseMessage dataBitLen 1024
compress xs = runST $ foldM (fM 1024) h0_384 xs
---------------------- Crypto-api instance -------------
instance Hash GroestlCtx Groestl384Digest where
outputLength = Tagged 384
blockLength = Tagged 1024
initialCtx = groestlInit G384 1024 h0_384
updateCtx = groestlUpdate
finalize ctx = Digest . groestlFinalize ctx
data Groestl384Digest = Digest L.ByteString
deriving (Eq,Ord)
instance Show Groestl384Digest where
show (Digest h) = printAsHex h
instance Serialize Groestl384Digest where
put (Digest bs) = put bs
get = liftM Digest get
------------------------------------------- Initial vector -------------------------------------
h0_384 :: Vector Word64
h0_384 = fromList [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x0180]
| hakoja/SHA3 | Data/Digest/Groestl384.hs | bsd-3-clause | 1,720 | 0 | 10 | 380 | 450 | 253 | 197 | 42 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
-- | 'Lucid.HtmlT' inspired monad for creating 'ReactElement's
module Glazier.React.Markup
( Markup
, ReactMarkup(..)
, BranchParam(..)
, LeafParam(..)
, fromMarkup
, toElements
, toElement
, elementMarkup
, textMarkup
, leafMarkup
, branchMarkup
) where
import Control.Monad.Environ
import qualified Data.DList as DL
import Glazier.React.ReactElement
import JS.Data
type Markup = DL.DList ReactMarkup
-- | The parameters required to create a branch ReactElement with children
data BranchParam = BranchParam
JSVal
[(JSString, JSVal)]
[ReactMarkup]
-- | The parameters required to create a leaf ReactElement (no children)
data LeafParam = LeafParam
JSVal
[(JSString, JSVal)]
data ReactMarkup
= ElementMarkup ReactElement
| TextMarkup JSString
| BranchMarkup BranchParam
| LeafMarkup LeafParam
-- | Create 'ReactElement's from a 'ReactMarkup'
fromMarkup :: ReactMarkup -> IO ReactElement
fromMarkup (BranchMarkup (BranchParam n props xs)) = do
xs' <- sequenceA $ fromMarkup <$> xs
mkBranchElement n props xs'
fromMarkup (LeafMarkup (LeafParam n props)) =
mkLeafElement n props
fromMarkup (TextMarkup str) = pure $ rawTextElement str
fromMarkup (ElementMarkup e) = pure e
-------------------------------------------------
-- | Convert the ReactMlt to [ReactElement]
toElements :: [ReactMarkup] -> IO [ReactElement]
toElements xs = sequenceA $ fromMarkup <$> xs
-- | 'Glazier.React.ReactDOM.renderDOM' only allows a single top most element.
-- Provide a handly function to wrap a list of ReactElements inside a 'div' if required.
-- If there is only one element in the list, then nothing is changed.
toElement :: [ReactMarkup] -> IO ReactElement
toElement xs = toElements xs >>= mkCombinedElements
-------------------------------------------------
-- | To use an exisitng ReactElement
elementMarkup :: MonadPut' Markup m => ReactElement -> m ()
elementMarkup e = modifyEnv' @Markup (`DL.snoc` ElementMarkup e)
-- | For raw text content
textMarkup :: MonadPut' Markup m => JSString -> m ()
textMarkup n = modifyEnv' @Markup (`DL.snoc` TextMarkup n)
-- | For the contentless elements: eg 'br_'.
-- Memonic: lf for leaf.
-- Duplicate listeners with the same key will be combined, but it is a silent error
-- if the same key is used across listeners and props.
-- "If an attribute/prop is duplicated the last one defined wins."
-- https://www.reactenlightenment.com/react-nodes/4.4.html
leafMarkup :: MonadPut' Markup m
=> JSVal
-> [(JSString, JSVal)]
-> m ()
leafMarkup n props = modifyEnv' @Markup (`DL.snoc` LeafMarkup (LeafParam n props))
-- | For the contentful elements: eg 'div_'.
-- Memonic: bh for branch.
-- Duplicate listeners with the same key will be combined, but it is a silent error
-- if the same key is used across listeners and props.
-- "If an attribute/prop is duplicated the last one defined wins."
-- https://www.reactenlightenment.com/react-nodes/4.4.html
branchMarkup :: MonadPut' Markup m
=> JSVal
-> [(JSString, JSVal)]
-> m a
-> m a
branchMarkup n props child = do
-- save state
s <- getEnv' @Markup
-- run children with mempty
putEnv' @Markup mempty
a <- child
child' <- getEnv' @Markup
-- restore state
putEnv' @Markup s
-- append the children markup
modifyEnv' @Markup (`DL.snoc` BranchMarkup (BranchParam n props (DL.toList child')))
pure a
-- -- Given a mapping function, apply it to children of the markup
-- modifyMarkup :: MonadState (DL.DList ReactMarkup) m
-- => (DL.DList ReactMarkup -> DL.DList ReactMarkup)
-- -> m a -> m a
-- modifyMarkup f = withMarkup (\childs' ms -> ms `DL.append` f childs')
-- -- Given a mapping function, apply it to all child BranchMarkup or LeafMarkup (if possible)
-- -- Does not recurse into decendants.
-- overSurfaceProperties ::
-- ((DL.DList JE.Property) -> (DL.DList JE.Property))
-- -> (DL.DList ReactMarkup -> DL.DList ReactMarkup)
-- overSurfaceProperties f childs = DL.fromList $ case DL.toList childs of
-- LeafMarkup (LeafParam j ps) : bs ->
-- LeafMarkup (LeafParam j (f ps)) : bs
-- BranchMarkup (BranchParam j ps as) : bs ->
-- BranchMarkup (BranchParam j (f ps) as) : bs
-- bs -> bs
-- -- Given a mapping function, apply it to all child BranchMarkup or LeafMarkup (if possible)
-- -- Recurse into decendants.
-- overAllProperties ::
-- ((DL.DList JE.Property) -> (DL.DList JE.Property))
-- -> (DL.DList ReactMarkup -> DL.DList ReactMarkup)
-- overAllProperties f childs = DL.fromList $ case DL.toList childs of
-- LeafMarkup (LeafParam j ps) : bs ->
-- LeafMarkup (LeafParam j (f ps)) : bs
-- BranchMarkup (BranchParam j ps as) : bs ->
-- BranchMarkup (BranchParam j (f ps) (overAllProperties f as)) : bs
-- bs -> bs
| louispan/glazier-react | src/Glazier/React/Markup.hs | bsd-3-clause | 5,135 | 0 | 14 | 1,002 | 731 | 415 | 316 | 71 | 1 |
{-|
Haskelm test suite
For the moment, just contains some basic tests
This file also serves as an example of how to
translate Elm from different sources
-}
{-# LANGUAGE TemplateHaskell, QuasiQuotes, MultiWayIf #-}
import Language.Elm.TH
import Data.List (intercalate)
import Control.Monad
-- | Similarly, we can load a module from a file
elmString = $(translateToElm
(defaultOptions {moduleName="Foo"})
("tests/files/module1.hs" ) )
-- | We can now access the elm strings we declared
main = do
putStrLn "Generated elm strings:"
mapM_ putStrLn [elmString]
writeFile "src/Test.elm" elmString
return ()
| JoeyEremondi/haskelm-old | tests/Main.hs | bsd-3-clause | 622 | 0 | 10 | 108 | 92 | 49 | 43 | 12 | 1 |
-- |
-- Module: Data.Float.BinString
-- License: BSD-style
-- Maintainer: [email protected]
--
--
-- This module contains functions for formatting and parsing floating point
-- values as C99 printf/scanf functions with format string @%a@ do.
--
-- The format is [-]0x/h.hhhhh/p±/ddd/, where /h.hhhhh/ is significand
-- as a hexadecimal floating-point number and /±ddd/ is exponent as a
-- decimal number. Significand has as many digits as needed to exactly
-- represent the value, fractional part may be ommitted.
--
-- Infinity and NaN values are represented as @±inf@ and @nan@ accordingly.
--
-- For example, @(π ∷ Double) = 0x1.921fb54442d18p+1@ (/exactly/).
--
-- This assertion holds (assuming NaN ≡ NaN)
--
-- prop> ∀x. Just x ≡ readFloat (showFloat x)
--
-- Floating point radix is assumed to be 2.
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Data.Float.BinString (readFloat,showFloat,floatBuilder,
readFloatStr,showFloatStr) where
import qualified Numeric as Numeric
import Data.List.Split
import Data.Char
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder
import Data.Text.Lazy.Builder.Int (decimal)
import Data.Attoparsec.Text hiding (take,signed,decimal)
import Control.Applicative ((<**>),(<|>),many)
import Data.Monoid
--- Printing
-- | Format a value. Will provide enough digits to reconstruct the value exactly.
showFloat :: RealFloat a => a -> Text
showFloat = toStrict . toLazyText . floatBuilder
-- | A 'Builder' for a value
floatBuilder :: RealFloat a => a -> Builder
floatBuilder x | isNaN x = fromText "nan"
| isInfinite x = sign <> fromText "inf"
| otherwise = sign <> fromText "0x"
<> singleton (intToDigit d0)
<> fromString [ '.' | length digs > 1 ]
<> fromString [ intToDigit x | x <- dtail]
<> singleton 'p'
<> singleton (if ep>=0 then '+' else '-')
<> decimal (abs ep)
where (digs,ep) = floatToHexDigits $ abs x
(d0:dtail) = digs
sign = fromString [ '-' | x < 0 ]
-- | Given a number, returns list of its mantissa digits and the
-- exponent as a pair. E.g. as π = 0x1.921fb54442d18p+1
--
-- >>> floatToHexDigits pi
-- ([1,9,2,1,15,11,5,4,4,4,2,13,1,8],1)
floatToHexDigits :: RealFloat a => a -> ([Int], Int)
floatToHexDigits x = (,ep') $ d0 : map to16 chunked
where ((d0:ds),ep) = Numeric.floatToDigits 2 x
ep' | x == 0 = ep
| otherwise = ep-1
chunked = map (take 4 . (++ repeat 0)) . chunksOf 4 $ ds
to16 = foldl1 (\a b -> 2*a+b)
{-# DEPRECATED showFloatStr "use showFloat" #-}
showFloatStr :: RealFloat a => a -> String
showFloatStr = T.unpack . showFloat
--- Parsing
data Sign = Pos | Neg deriving Show
data ParsedFloat = Inf Sign | NaN | Float Sign String Sign String
deriving Show
signed Pos x = x
signed Neg x = -x
-- | Parse a value from 'Text'.
readFloat :: RealFloat a => Text -> Maybe a
readFloat s = either (const Nothing) (Just . decode) pd
where pd = parseOnly parser s
parser = do r <- try parserPeculiar <|> parserNormal
endOfInput
return r
decode :: (Eq a, Fractional a) => ParsedFloat -> a
decode (Float sgn digs exp_sgn exp_digs) = signif * 2^^expon
where signif = signed sgn v / 16^^(length digs - 1)
[(v,_)] = Numeric.readHex digs
expon = signed exp_sgn $ read exp_digs
decode NaN = 0/0
decode (Inf sgn) = signed sgn $ 1/0
-- | Parse nans and infs
parserPeculiar = do sgn <- optSign
(string "nan" >> return NaN) <|> (string "inf" >> return (Inf sgn))
parserPeculiar' = optSign <**> ((string "nan" >> return (const NaN))
<|> (string "inf" >> return Inf))
-- | Parse vanilla numbers
parserNormal = do positive <- optSign
string "0x"
digit0 <- hexDigit
restDigits <- option [] $ char '.' >> many hexDigit
char 'p'
positiveExp <- optSign
expDigits <- many digit
return $ Float positive (digit0:restDigits) positiveExp expDigits
hexDigit = satisfy isHexDigit
optSign = option Pos $ (char '+' >> return Pos) <|> (char '-' >> return Neg)
{-# DEPRECATED readFloatStr "use readFloat" #-}
readFloatStr :: RealFloat a => String -> Maybe a
readFloatStr = readFloat . T.pack
| llelf/float-binstring | Data/Float/BinString.hs | bsd-3-clause | 4,694 | 0 | 15 | 1,320 | 1,196 | 634 | 562 | 76 | 2 |
{-# LANGUAGE CPP, BangPatterns #-}
{-#LANGUAGE RankNTypes, OverloadedStrings, ScopedTypeVariables #-}
-- | This library emulates "Data.ByteString.Lazy.Char8" but includes a monadic element
-- and thus at certain points uses a `Stream`/`FreeT` type in place of lists.
-- See the documentation for @Data.ByteString.Streaming@ and the examples of
-- of use to implement simple shell operations <https://gist.github.com/michaelt/6c6843e6dd8030e95d58 here>. Examples of use
-- with @http-client@, @attoparsec@, @aeson@, @zlib@ etc. can be found in the
-- 'streaming-utils' library.
module Data.ByteString.Streaming.Char8 (
-- * The @ByteString@ type
ByteString
-- * Introducing and eliminating 'ByteString's
, empty -- empty :: ByteString m ()
, pack -- pack :: Monad m => String -> ByteString m ()
, unpack
, string
, unlines
, unwords
, singleton -- singleton :: Monad m => Char -> ByteString m ()
, fromChunks -- fromChunks :: Monad m => Stream (Of ByteString) m r -> ByteString m r
, fromLazy -- fromLazy :: Monad m => ByteString -> ByteString m ()
, fromStrict -- fromStrict :: ByteString -> ByteString m ()
, toChunks -- toChunks :: Monad m => ByteString m r -> Stream (Of ByteString) m r
, toLazy -- toLazy :: Monad m => ByteString m () -> m ByteString
, toLazy_
, toStrict -- toStrict :: Monad m => ByteString m () -> m ByteString
, toStrict_
, effects
, copy
, drained
, mwrap
-- * Transforming ByteStrings
, map -- map :: Monad m => (Char -> Char) -> ByteString m r -> ByteString m r
, intercalate -- intercalate :: Monad m => ByteString m () -> Stream (ByteString m) m r -> ByteString m r
, intersperse -- intersperse :: Monad m => Char -> ByteString m r -> ByteString m r
-- * Basic interface
, cons -- cons :: Monad m => Char -> ByteString m r -> ByteString m r
, cons' -- cons' :: Char -> ByteString m r -> ByteString m r
, snoc
, append -- append :: Monad m => ByteString m r -> ByteString m s -> ByteString m s
, filter -- filter :: (Char -> Bool) -> ByteString m r -> ByteString m r
, head -- head :: Monad m => ByteString m r -> m Char
, head_ -- head' :: Monad m => ByteString m r -> m (Of Char r)
, last -- last :: Monad m => ByteString m r -> m Char
, last_ -- last' :: Monad m => ByteString m r -> m (Of Char r)
, null -- null :: Monad m => ByteString m r -> m Bool
, null_
, testNull
, nulls -- null' :: Monad m => ByteString m r -> m (Of Bool r)
, uncons -- uncons :: Monad m => ByteString m r -> m (Either r (Char, ByteString m r))
, nextChar
-- * Substrings
-- ** Breaking strings
, break -- break :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m (ByteString m r)
, drop -- drop :: Monad m => GHC.Int.Int64 -> ByteString m r -> ByteString m r
, dropWhile
, group -- group :: Monad m => ByteString m r -> Stream (ByteString m) m r
, groupBy
, span -- span :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m (ByteString m r)
, splitAt -- splitAt :: Monad m => GHC.Int.Int64 -> ByteString m r -> ByteString m (ByteString m r)
, splitWith -- splitWith :: Monad m => (Char -> Bool) -> ByteString m r -> Stream (ByteString m) m r
, take -- take :: Monad m => GHC.Int.Int64 -> ByteString m r -> ByteString m ()
, takeWhile -- takeWhile :: (Char -> Bool) -> ByteString m r -> ByteString m ()
-- ** Breaking into many substrings
, split -- split :: Monad m => Char -> ByteString m r -> Stream (ByteString m) m r
, lines
, words
, denull
-- ** Special folds
, concat -- concat :: Monad m => Stream (ByteString m) m r -> ByteString m r
-- * Builders
, toStreamingByteString
, toStreamingByteStringWith
, toBuilder
, concatBuilders
-- * Building ByteStrings
-- ** Infinite ByteStrings
, repeat -- repeat :: Char -> ByteString m ()
, iterate -- iterate :: (Char -> Char) -> Char -> ByteString m ()
, cycle -- cycle :: Monad m => ByteString m r -> ByteString m s
-- ** Unfolding ByteStrings
, unfoldr -- unfoldr :: (a -> Maybe (Char, a)) -> a -> ByteString m ()
, unfoldM -- unfold :: (a -> Either r (Char, a)) -> a -> ByteString m r
, reread
-- * Folds, including support for `Control.Foldl`
-- , foldr -- foldr :: Monad m => (Char -> a -> a) -> a -> ByteString m () -> m a
, fold -- fold :: Monad m => (x -> Char -> x) -> x -> (x -> b) -> ByteString m () -> m b
, fold_ -- fold' :: Monad m => (x -> Char -> x) -> x -> (x -> b) -> ByteString m r -> m (b, r)
, length
, length_
, count
, count_
, readInt
-- * I\/O with 'ByteString's
-- ** Standard input and output
, getContents -- getContents :: ByteString IO ()
, stdin -- stdin :: ByteString IO ()
, stdout -- stdout :: ByteString IO r -> IO r
, interact -- interact :: (ByteString IO () -> ByteString IO r) -> IO r
, putStr
, putStrLn
-- ** Files
, readFile -- readFile :: FilePath -> ByteString IO ()
, writeFile -- writeFile :: FilePath -> ByteString IO r -> IO r
, appendFile -- appendFile :: FilePath -> ByteString IO r -> IO r
-- ** I\/O with Handles
, fromHandle -- fromHandle :: Handle -> ByteString IO ()
, toHandle -- toHandle :: Handle -> ByteString IO r -> IO r
, hGet -- hGet :: Handle -> Int -> ByteString IO ()
, hGetContents -- hGetContents :: Handle -> ByteString IO ()
, hGetContentsN -- hGetContentsN :: Int -> Handle -> ByteString IO ()
, hGetN -- hGetN :: Int -> Handle -> Int -> ByteString IO ()
, hGetNonBlocking -- hGetNonBlocking :: Handle -> Int -> ByteString IO ()
, hGetNonBlockingN -- hGetNonBlockingN :: Int -> Handle -> Int -> ByteString IO ()
, hPut -- hPut :: Handle -> ByteString IO r -> IO r
-- , hPutNonBlocking -- hPutNonBlocking :: Handle -> ByteString IO r -> ByteString IO r
-- * Simple chunkwise operations
, unconsChunk
, nextChunk
, chunk
, foldrChunks
, foldlChunks
, chunkFold
, chunkFoldM
, chunkMap
, chunkMapM
, chunkMapM_
-- * Etc.
-- , zipWithStream -- zipWithStream :: Monad m => (forall x. a -> ByteString m x -> ByteString m x) -> [a] -> Stream (ByteString m) m r -> Stream (ByteString m) m r
, distribute -- distribute :: ByteString (t m) a -> t (ByteString m) a
, materialize
, dematerialize
) where
import Prelude hiding
(reverse,head,tail,last,init,null,length,map,words, lines,foldl,foldr, unwords, unlines
,concat,any,take,drop,splitAt,takeWhile,dropWhile,span,break,elem,filter,maximum
,minimum,all,concatMap,foldl1,foldr1,scanl, scanl1, scanr, scanr1
,repeat, cycle, interact, iterate,readFile,writeFile,appendFile,replicate
,getContents,getLine,putStr,putStrLn ,zip,zipWith,unzip,notElem)
import qualified Prelude
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as B
import Data.ByteString.Internal (c2w,w2c)
import qualified Data.ByteString.Unsafe as B
import qualified Data.ByteString.Char8 as Char8
import Streaming hiding (concats, unfold, distribute, mwrap)
import Streaming.Internal (Stream (..))
import qualified Streaming.Prelude as S
import qualified Streaming as S
import qualified Data.ByteString.Streaming as R
import Data.ByteString.Streaming.Internal
import Data.ByteString.Streaming
(fromLazy, toLazy, toLazy_, nextChunk, unconsChunk,
fromChunks, toChunks, fromStrict, toStrict, toStrict_,
concat, distribute, effects, drained, mwrap, toStreamingByteStringWith,
toStreamingByteString, toBuilder, concatBuilders,
empty, null, nulls, null_, testNull, length, length_, append, cycle,
take, drop, splitAt, intercalate, group, denull,
appendFile, stdout, stdin, fromHandle, toHandle,
hGetContents, hGetContentsN, hGet, hGetN, hPut,
getContents, hGetNonBlocking,
hGetNonBlockingN, readFile, writeFile, interact,
chunkFold, chunkFoldM, chunkMap, chunkMapM)
-- hPutNonBlocking,
import Control.Monad (liftM)
import System.IO (Handle,openBinaryFile,IOMode(..)
,hClose)
import qualified System.IO as IO
import System.IO.Unsafe
import Control.Exception (bracket)
import Data.Char (isDigit)
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Ptr
import Foreign.Storable
import Data.Functor.Compose
import Data.Functor.Sum
import qualified Data.List as L
unpack :: Monad m => ByteString m r -> Stream (Of Char) m r
unpack bs = case bs of
Empty r -> Return r
Go m -> Effect (liftM unpack m)
Chunk c cs -> unpackAppendCharsLazy c (unpack cs)
where
unpackAppendCharsLazy :: B.ByteString -> Stream (Of Char) m r -> Stream (Of Char) m r
unpackAppendCharsLazy (B.PS fp off len) xs
| len <= 100 = unpackAppendCharsStrict (B.PS fp off len) xs
| otherwise = unpackAppendCharsStrict (B.PS fp off 100) remainder
where
remainder = unpackAppendCharsLazy (B.PS fp (off+100) (len-100)) xs
unpackAppendCharsStrict :: B.ByteString -> Stream (Of Char) m r -> Stream (Of Char) m r
unpackAppendCharsStrict (B.PS fp off len) xs =
inlinePerformIO $ withForeignPtr fp $ \base -> do
loop (base `plusPtr` (off-1)) (base `plusPtr` (off-1+len)) xs
where
loop !sentinal !p acc
| p == sentinal = return acc
| otherwise = do x <- peek p
loop sentinal (p `plusPtr` (-1)) (Step (B.w2c x :> acc))
{-# INLINABLE unpack#-}
-- | /O(n)/ Convert a stream of separate characters into a packed byte stream.
pack :: Monad m => Stream (Of Char) m r -> ByteString m r
pack = fromChunks
. mapped (liftM (\(str :> r) -> Char8.pack str :> r) . S.toList)
. chunksOf 32
{-# INLINABLE pack #-}
-- | /O(1)/ Cons a 'Char' onto a byte stream.
cons :: Monad m => Char -> ByteString m r -> ByteString m r
cons c = R.cons (c2w c)
{-# INLINE cons #-}
-- | /O(1)/ Yield a 'Char' as a minimal 'ByteString'
singleton :: Monad m => Char -> ByteString m ()
singleton = R.singleton . c2w
{-# INLINE singleton #-}
-- | /O(1)/ Unlike 'cons', 'cons\'' is
-- strict in the ByteString that we are consing onto. More precisely, it forces
-- the head and the first chunk. It does this because, for space efficiency, it
-- may coalesce the new byte onto the first \'chunk\' rather than starting a
-- new \'chunk\'.
--
-- So that means you can't use a lazy recursive contruction like this:
--
-- > let xs = cons\' c xs in xs
--
-- You can however use 'cons', as well as 'repeat' and 'cycle', to build
-- infinite lazy ByteStrings.
--
cons' :: Char -> ByteString m r -> ByteString m r
cons' c (Chunk bs bss) | B.length bs < 16 = Chunk (B.cons (c2w c) bs) bss
cons' c cs = Chunk (B.singleton (c2w c)) cs
{-# INLINE cons' #-}
--
-- | /O(n\/c)/ Append a byte to the end of a 'ByteString'
snoc :: Monad m => ByteString m r -> Char -> ByteString m r
snoc cs = R.snoc cs . c2w
{-# INLINE snoc #-}
-- | /O(1)/ Extract the first element of a ByteString, which must be non-empty.
head_ :: Monad m => ByteString m r -> m Char
head_ = liftM (w2c) . R.head_
{-# INLINE head_ #-}
-- | /O(1)/ Extract the first element of a ByteString, which may be non-empty
head :: Monad m => ByteString m r -> m (Of (Maybe Char) r)
head = liftM (\(m:>r) -> fmap w2c m :> r) . R.head
{-# INLINE head #-}
-- | /O(n\/c)/ Extract the last element of a ByteString, which must be finite
-- and non-empty.
last_ :: Monad m => ByteString m r -> m Char
last_ = liftM (w2c) . R.last_
{-# INLINE last_ #-}
last :: Monad m => ByteString m r -> m (Of (Maybe Char) r)
last = liftM (\(m:>r) -> fmap (w2c) m :> r) . R.last
{-# INLINE last #-}
groupBy :: Monad m => (Char -> Char -> Bool) -> ByteString m r -> Stream (ByteString m) m r
groupBy rel = R.groupBy (\w w' -> rel (w2c w) (w2c w'))
{-#INLINE groupBy #-}
-- | /O(1)/ Extract the head and tail of a ByteString, returning Nothing
-- if it is empty.
uncons :: Monad m => ByteString m r -> m (Either r (Char, ByteString m r))
uncons (Empty r) = return (Left r)
uncons (Chunk c cs)
= return $ Right (w2c (B.unsafeHead c)
, if B.length c == 1
then cs
else Chunk (B.unsafeTail c) cs )
uncons (Go m) = m >>= uncons
{-# INLINABLE uncons #-}
-- ---------------------------------------------------------------------
-- Transformations
-- | /O(n)/ 'map' @f xs@ is the ByteString obtained by applying @f@ to each
-- element of @xs@.
map :: Monad m => (Char -> Char) -> ByteString m r -> ByteString m r
map f = R.map (c2w . f . w2c)
{-# INLINE map #-}
--
-- -- | /O(n)/ 'reverse' @xs@ returns the elements of @xs@ in reverse order.
-- reverse :: ByteString -> ByteString
-- reverse cs0 = rev Empty cs0
-- where rev a Empty = a
-- rev a (Chunk c cs) = rev (Chunk (B.reverse c) a) cs
-- {-# INLINE reverse #-}
--
-- -- | The 'intersperse' function takes a 'Word8' and a 'ByteString' and
-- -- \`intersperses\' that byte between the elements of the 'ByteString'.
-- -- It is analogous to the intersperse function on Streams.
intersperse :: Monad m => Char -> ByteString m r -> ByteString m r
intersperse c = R.intersperse (c2w c)
{-#INLINE intersperse #-}
-- -- | The 'transpose' function transposes the rows and columns of its
-- -- 'ByteString' argument.
-- transpose :: [ByteString] -> [ByteString]
-- transpose css = L.map (\ss -> Chunk (B.pack ss) Empty)
-- (L.transpose (L.map unpack css))
-- --TODO: make this fast
--
-- -- ---------------------------------------------------------------------
-- -- Reducing 'ByteString's
fold_ :: Monad m => (x -> Char -> x) -> x -> (x -> b) -> ByteString m () -> m b
fold_ step begin done p0 = loop p0 begin
where
loop p !x = case p of
Chunk bs bss -> loop bss $! Char8.foldl' step x bs
Go m -> m >>= \p' -> loop p' x
Empty _ -> return (done x)
{-# INLINABLE fold_ #-}
fold :: Monad m => (x -> Char -> x) -> x -> (x -> b) -> ByteString m r -> m (Of b r)
fold step begin done p0 = loop p0 begin
where
loop p !x = case p of
Chunk bs bss -> loop bss $! Char8.foldl' step x bs
Go m -> m >>= \p' -> loop p' x
Empty r -> return (done x :> r)
{-# INLINABLE fold #-}
-- ---------------------------------------------------------------------
-- Unfolds and replicates
-- | @'iterate' f x@ returns an infinite ByteString of repeated applications
-- of @f@ to @x@:
-- > iterate f x == [x, f x, f (f x), ...]
iterate :: (Char -> Char) -> Char -> ByteString m r
iterate f c = R.iterate (c2w . f . w2c) (c2w c)
{-#INLINE iterate #-}
-- | @'repeat' x@ is an infinite ByteString, with @x@ the value of every
-- element.
--
repeat :: Char -> ByteString m r
repeat = R.repeat . c2w
{-#INLINE repeat #-}
-- -- | /O(n)/ @'replicate' n x@ is a ByteString of length @n@ with @x@
-- -- the value of every element.
-- --
-- replicate :: Int64 -> Word8 -> ByteString
-- replicate n w
-- | n <= 0 = Empty
-- | n < fromIntegral smallChunkSize = Chunk (B.replicate (fromIntegral n) w) Empty
-- | r == 0 = cs -- preserve invariant
-- | otherwise = Chunk (B.unsafeTake (fromIntegral r) c) cs
-- where
-- c = B.replicate smallChunkSize w
-- cs = nChunks q
-- (q, r) = quotRem n (fromIntegral smallChunkSize)
-- nChunks 0 = Empty
-- nChunks m = Chunk c (nChunks (m-1))
-- | 'cycle' ties a finite ByteString into a circular one, or equivalently,
-- the infinite repetition of the original ByteString.
--
-- | /O(n)/ The 'unfoldr' function is analogous to the Stream \'unfoldr\'.
-- 'unfoldr' builds a ByteString from a seed value. The function takes
-- the element and returns 'Nothing' if it is done producing the
-- ByteString or returns 'Just' @(a,b)@, in which case, @a@ is a
-- prepending to the ByteString and @b@ is used as the next element in a
-- recursive call.
unfoldM :: Monad m => (a -> Maybe (Char, a)) -> a -> ByteString m ()
unfoldM f = R.unfoldM go where
go a = case f a of
Nothing -> Nothing
Just (c,a) -> Just (c2w c, a)
{-#INLINE unfoldM #-}
unfoldr :: (a -> Either r (Char, a)) -> a -> ByteString m r
unfoldr step = R.unfoldr (either Left (\(c,a) -> Right (c2w c,a)) . step)
{-#INLINE unfoldr #-}
-- ---------------------------------------------------------------------
-- | 'takeWhile', applied to a predicate @p@ and a ByteString @xs@,
-- returns the longest prefix (possibly empty) of @xs@ of elements that
-- satisfy @p@.
takeWhile :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m ()
takeWhile f = R.takeWhile (f . w2c)
{-#INLINE takeWhile #-}
-- | 'dropWhile' @p xs@ returns the suffix remaining after 'takeWhile' @p xs@.
dropWhile :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m r
dropWhile f = R.dropWhile (f . w2c)
{-#INLINE dropWhile #-}
{- | 'break' @p@ is equivalent to @'span' ('not' . p)@.
-}
break :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m (ByteString m r)
break f = R.break (f . w2c)
{-#INLINE break #-}
--
-- | 'span' @p xs@ breaks the ByteString into two segments. It is
-- equivalent to @('takeWhile' p xs, 'dropWhile' p xs)@
span :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m (ByteString m r)
span p = break (not . p)
{-#INLINE span #-}
-- -- | /O(n)/ Splits a 'ByteString' into components delimited by
-- -- separators, where the predicate returns True for a separator element.
-- -- The resulting components do not contain the separators. Two adjacent
-- -- separators result in an empty component in the output. eg.
-- --
-- -- > splitWith (=='a') "aabbaca" == ["","","bb","c",""]
-- -- > splitWith (=='a') [] == []
-- --
splitWith :: Monad m => (Char -> Bool) -> ByteString m r -> Stream (ByteString m) m r
splitWith f = R.splitWith (f . w2c)
{-# INLINE splitWith #-}
{- | /O(n)/ Break a 'ByteString' into pieces separated by the byte
argument, consuming the delimiter. I.e.
> split '\n' "a\nb\nd\ne" == ["a","b","d","e"]
> split 'a' "aXaXaXa" == ["","X","X","X",""]
> split 'x' "x" == ["",""]
and
> intercalate [c] . split c == id
> split == splitWith . (==)
As for all splitting functions in this library, this function does
not copy the substrings, it just constructs new 'ByteStrings' that
are slices of the original.
>>> Q.stdout $ Q.unlines $ Q.split 'n' "banana peel"
ba
a
a peel
-}
split :: Monad m => Char -> ByteString m r -> Stream (ByteString m) m r
split c = R.split (c2w c)
{-# INLINE split #-}
-- -- ---------------------------------------------------------------------
-- -- Searching ByteStrings
--
-- -- | /O(n)/ 'elem' is the 'ByteString' membership predicate.
-- elem :: Word8 -> ByteString -> Bool
-- elem w cs = case elemIndex w cs of Nothing -> False ; _ -> True
--
-- -- | /O(n)/ 'notElem' is the inverse of 'elem'
-- notElem :: Word8 -> ByteString -> Bool
-- notElem w cs = not (elem w cs)
-- | /O(n)/ 'filter', applied to a predicate and a ByteString,
-- returns a ByteString containing those characters that satisfy the
-- predicate.
filter :: Monad m => (Char -> Bool) -> ByteString m r -> ByteString m r
filter p = R.filter (p . w2c)
{-# INLINE filter #-}
{- | 'lines' turns a ByteString into a connected stream of ByteStrings at
divide at newline characters. The resulting strings do not contain newlines.
This is the genuinely streaming 'lines' which only breaks chunks, and
thus never increases the use of memory.
Because 'ByteString's are usually read in binary mode, with no line
ending conversion, this function recognizes both @\\n@ and @\\r\\n@
endings (regardless of the current platform).
-}
lines :: forall m r . Monad m => ByteString m r -> Stream (ByteString m) m r
lines text0 = loop1 text0
where
loop1 :: ByteString m r -> Stream (ByteString m) m r
loop1 text =
case text of
Empty r -> Return r
Go m -> Effect $ liftM loop1 m
Chunk c cs
| B.null c -> loop1 cs
| otherwise -> Step (loop2 text)
loop2 :: ByteString m r -> ByteString m (Stream (ByteString m) m r)
loop2 text =
case text of
Empty r -> Empty (Return r)
Go m -> Go $ liftM loop2 m
Chunk c cs ->
case B.elemIndex 10 c of
Nothing -> Chunk c (loop2 cs)
Just i ->
let prefixLength =
if i >= 1 && B.unsafeIndex c (i-1) == 13 -- \r\n (dos)
then i-1
else i
rest =
if B.length c > i+1
then Chunk (B.drop (i+1) c) cs
else cs
in Chunk (B.unsafeTake prefixLength c) (Empty (loop1 rest))
{-#INLINABLE lines #-}
-- | The 'unlines' function restores line breaks between layers.
--
-- Note that this is not a perfect inverse of 'lines':
--
-- * @'lines' . 'unlines'@ can produce more strings than there were if some of
-- the \"lines\" had embedded newlines.
--
-- * @'unlines' . 'lines'@ will replace @\\r\\n@ with @\\n@.
unlines :: Monad m => Stream (ByteString m) m r -> ByteString m r
unlines = loop where
loop str = case str of
Return r -> Empty r
Step bstr -> do
st <- bstr
let bs = unlines st
case bs of
Chunk "" (Empty r) -> Empty r
Chunk "\n" (Empty r) -> bs
_ -> cons' '\n' bs
Effect m -> Go (liftM unlines m)
{-#INLINABLE unlines #-}
-- | 'words' breaks a byte stream up into a succession of byte streams
-- corresponding to words, breaking Chars representing white space. This is
-- the genuinely streaming 'words'. A function that returns individual
-- strict bytestrings would concatenate even infinitely
-- long words like @cycle "y"@ in memory. It is best for the user who
-- has reflected on her materials to write `mapped toStrict . words` or the like,
-- if strict bytestrings are needed.
words :: Monad m => ByteString m r -> Stream (ByteString m) m r
words = filtered . R.splitWith B.isSpaceWord8
where
filtered stream = case stream of
Return r -> Return r
Effect m -> Effect (liftM filtered m)
Step bs -> Effect $ bs_loop bs
bs_loop bs = case bs of
Empty r -> return $ filtered r
Go m -> m >>= bs_loop
Chunk b bs' -> if B.null b
then bs_loop bs'
else return $ Step $ Chunk b (fmap filtered bs')
{-# INLINABLE words #-}
-- | The 'unwords' function is analogous to the 'unlines' function, on words.
unwords :: Monad m => Stream (ByteString m) m r -> ByteString m r
unwords = intercalate (singleton ' ')
{-# INLINE unwords #-}
string :: String -> ByteString m ()
string = chunk . B.pack . Prelude.map B.c2w
{-# INLINE string #-}
count_ :: Monad m => Char -> ByteString m r -> m Int
count_ c = R.count_ (c2w c)
{-# INLINE count_ #-}
count :: Monad m => Char -> ByteString m r -> m (Of Int r)
count c = R.count (c2w c)
{-# INLINE count #-}
nextChar :: Monad m => ByteString m r -> m (Either r (Char, ByteString m r))
nextChar b = do
e <- R.nextByte b
case e of
Left r -> return $! Left r
Right (w,bs) -> return $! Right (w2c w, bs)
putStr :: MonadIO m => ByteString m r -> m r
putStr = hPut IO.stdout
{-#INLINE putStr #-}
putStrLn :: MonadIO m => ByteString m r -> m r
putStrLn bs = hPut IO.stdout (snoc bs '\n')
{-#INLINE putStrLn #-}
-- , head'
-- , last
-- , last'
-- , length
-- , length'
-- , null
-- , null'
-- , count
-- , count'
{-| This will read positive or negative Ints that require 18 or fewer characters.
-}
readInt :: Monad m => ByteString m r -> m (Compose (Of (Maybe Int)) (ByteString m) r)
readInt = go . toStrict . splitAt 18 where
go m = do
(bs :> rest) <- m
case Char8.readInt bs of
Nothing -> return (Compose (Nothing :> (chunk bs >> rest)))
Just (n,more) -> if B.null more
then do
e <- uncons rest
return $ case e of
Left r -> Compose (Just n :> return r)
Right (c,rest') -> if isDigit c
then Compose (Nothing :> (chunk bs >> cons' c rest'))
else Compose (Just n :> (chunk more >> cons' c rest'))
else return (Compose (Just n :> (chunk more >> rest)))
{-#INLINABLE readInt #-}
-- uncons :: Monad m => ByteString m r -> m (Either r (Char, ByteString m r))
| michaelt/streaming-bytestring | Data/ByteString/Streaming/Char8.hs | bsd-3-clause | 25,121 | 0 | 25 | 6,699 | 5,038 | 2,736 | 2,302 | 350 | 8 |
{-# LANGUAGE ScopedTypeVariables #-}
-- | Utilities for interleaving transition operators and running Markov chains.
module Math.Probably.MCMC (
-- * Strategies
module Strategy
-- * Interleaving
, interleave
, polyInterleave
, frequency
, oneOfRandomly
-- * Other
, ezMC
, trace
) where
import Control.Applicative
import Control.Monad
import Control.Monad.State.Strict
import Math.Probably.Sampler
import Math.Probably.Types
import Strategy.Hamiltonian as Strategy
import Strategy.MALA as Strategy
import Strategy.Metropolis as Strategy
import Strategy.NUTS as Strategy
import Strategy.NUTSDualAveraging as Strategy
import Strategy.Slice as Strategy
-- | Interleave a list of transitions together.
--
-- > interleave [metropolis Nothing, mala Nothing]
-- -- :: Transition Double
interleave :: [Transition a] -> Transition a
interleave = foldl1 (>>)
-- | Select a transition operator from a list uniformly at random.
oneOfRandomly :: [Transition a] -> Transition a
oneOfRandomly ts = do
j <- lift $ oneOf [0..(length ts - 1)]
ts !! j
-- | Select a transition operator from a list according to supplied
-- frequencies. Mimics the similar function from QuickCheck.
--
-- > frequency [(9, continuousSlice Nothing), (1, nutsDualAveraging Nothing)]
-- -- probably a slice transition
frequency :: [(Int, Transition a)] -> Transition a
frequency xs = lift (oneOf [1..tot]) >>= (`pick` xs) where
tot = sum . map fst $ xs
pick n ((k, v):vs)
| n <= k = v
| otherwise = pick (n - k) vs
pick _ [] = error "frequency: empty list"
-- | Heterogeneous type interleaving.
polyInterleave :: Transition t1 -> Transition t2 -> Transition (t1,t2)
polyInterleave tr1 tr2 = do
Chain current0 target val0 (tun1, tun2) <- get
let chain1 = Chain current0 target val0 tun1
Chain current1 target1 val1 tun1next <- lift $ execStateT tr1 chain1
let chain2 = Chain current1 target1 val1 tun2
(ret, Chain current2 target2 val2 tun2next) <- lift $ runStateT tr2 chain2
put $ Chain current2 target2 val2 (tun1next, tun2next)
return ret
-- | Construct a transition from a supplied function.
ezMC :: (Chain t -> Prob (Chain t)) -> Transition t
ezMC f = get >>= lift . f >>= put >> gets parameterSpacePosition
-- | Run a Markov Chain.
trace :: Int -> Transition t -> Chain t -> Prob (Prob Parameters)
trace n t o = Samples <$> replicateM n t `evalStateT` o
| glutamate/probably-baysig | src/Math/Probably/MCMC.hs | bsd-3-clause | 2,457 | 0 | 13 | 511 | 650 | 349 | 301 | 46 | 2 |
{-# LANGUAGE MultiParamTypeClasses
, FlexibleInstances
, ViewPatterns
, TupleSections
#-}
module Spire.Canonical.Evaluator
(lookupValAndType , lookupType , sub , sub2 , elim , app , app2)
where
import Unbound.LocallyNameless hiding ( Spine )
import Spire.Canonical.Types
import Spire.Surface.PrettyPrinter
import Control.Applicative ((<$>) , (<*>))
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
----------------------------------------------------------------------
instance SubstM SpireM Value Spine
instance SubstM SpireM Value Elim
instance SubstM SpireM Value Value where
substHookM (VNeut nm fs) = Just f
where
f nm' e = do
fs' <- substM nm' e fs
let head = if nm == nm' then e else vVar nm
elims head fs'
substHookM _ = Nothing
----------------------------------------------------------------------
sub :: Bind Nom Value -> Value -> SpireM Value
sub b x = do
(nm , f) <- unbind b
substM nm x f
elimB :: Bind Nom Value -> Elim -> SpireM (Bind Nom Value)
elimB bnd_f g = do
(nm , f) <- unbind bnd_f
bind nm <$> elim f g
subCompose :: Bind Nom Value -> (Value -> Value) -> SpireM (Bind Nom Value)
subCompose bnd_f g = do
(nm , f) <- unbind bnd_f
bind nm <$> substM nm (g (vVar nm)) f
sub2 :: Bind Nom2 Value -> (Value , Value) -> SpireM Value
sub2 b (x1 , x2) = do
((nm1 , nm2) , f) <- unbind b
substsM [(nm1 , x1) , (nm2 , x2)] f
sub3 :: Bind Nom3 Value -> (Value , Value , Value) -> SpireM Value
sub3 b (x1 , x2 , x3) = do
((nm1 , nm2 , nm3) , f) <- unbind b
substsM [(nm1 , x1) , (nm2 , x2) , (nm3 , x3)] f
app :: Value -> Value -> SpireM Value
app f x = elim f (EApp x)
app2 :: Value -> Value -> Value -> SpireM Value
app2 f x y = elims f (Pipe (Pipe Id (EApp x)) (EApp y))
----------------------------------------------------------------------
elim :: Value -> Elim -> SpireM Value
elim (VNeut nm fs) f = return $ VNeut nm (Pipe fs f)
elim (VLam f) (EApp a) = f `sub` a
elim _ (EApp _) = throwError "Ill-typed evaluation of function application"
elim VTT (EElimUnit _P ptt) = return ptt
elim _ (EElimUnit _P ptt) = throwError "Ill-typed evaluation of elimUnit"
elim VTrue (EElimBool _P pt _) = return pt
elim VFalse (EElimBool _P _ pf) = return pf
elim _ (EElimBool _P _ _) = throwError "Ill-typed evaluation of elimBool"
elim (VPair a b) (EElimPair _A _B _P ppair) = do
ppair `sub2` (a , b)
elim _ (EElimPair _A _B _P ppair) =
throwError "Ill-typed evaluation of elimPair"
elim VRefl (EElimEq _A x _P prefl y) =
return prefl
elim _ (EElimEq _A x _P prefl y) =
throwError "Ill-typed evaluation of elimEq"
elim VNil (EElimEnum _P pn _) =
return pn
elim (VCons x xs) (EElimEnum _P pn pc) = do
ih <- xs `elim` EElimEnum _P pn pc
pc `sub3` (x , xs , ih)
elim _ (EElimEnum _P _ _) =
throwError "Ill-typed evaluation of elimEnum"
elim VEmp (EElimTel _P pemp pext) =
return pemp
elim (VExt _A bnd_B) (EElimTel _P pemp pext) = do
(nm_a , _B) <- unbind bnd_B
ih <- elim _B (EElimTel _P pemp pext)
pext `sub3` (_A , VLam (bind nm_a _B) , VLam (bind nm_a ih))
elim _ (EElimTel _P pemp pext) =
throwError "Ill-typed evaluation of elimTel"
elim (VEnd i) (EElimDesc _I _P pend prec parg) =
pend `sub` i
elim (VRec i _D) (EElimDesc _I _P pend prec parg) = do
ih <- _D `elim` EElimDesc _I _P pend prec parg
prec `sub3` (i , _D , ih)
elim (VArg _A bnd_B) (EElimDesc _I _P pend prec parg) = do
(nm_a , _B) <- unbind bnd_B
ih <- elim _B (EElimDesc _I _P pend prec parg)
parg `sub3` (_A , VLam (bind nm_a _B) , VLam (bind nm_a ih))
elim _ (EElimDesc _I _P pend prec parg) =
throwError "Ill-typed evaluation of elimDesc"
elim (VInit xs) (EInd l _P _I _D p _M m i) = do
let _X = vBind "i" (VFix l _P _I _D p)
let ih = rBind2 "i" "x" $ \ j x -> rInd l _P _I _D p _M m (vVar j) x
ihs <- _D `elim` EProve _I _X _M ih i xs
m `sub3` (i , xs , ihs)
elim _ (EInd l _P _I _D p _M m i) =
throwError "Ill-typed evaluation of ind"
elim (VEnd j) (EFunc _I _X i) =
return $ VEq _I j _I i
elim (VRec j _D) (EFunc _I _X i) =
vProd <$> _X `sub` j <*> _D `elim` EFunc _I _X i
elim (VArg _A _B) (EFunc _I _X i) =
VSg _A <$> _B `elimB` EFunc _I _X i
elim _ (EFunc _I _X i) =
throwError "Ill-typed evaluation of Func"
elim (VEnd j) (EHyps _I _X _M i q) =
return $ VUnit
elim (VRec j _D) (EHyps _I _X _M i xxs) = do
_A <- _X `sub` j
_B <- _D `elim` EFunc _I _X i
(x , xs) <- (,) <$> freshR "x" <*> freshR "xs"
ppair <- vProd <$> _M `sub2` (j , vVar x) <*> _D `elim` EHyps _I _X _M i (vVar xs)
xxs `elim` EElimPair _A (kBind _B) (kBind VType) (bind2 x xs ppair)
elim (VArg _A bnd_B) (EHyps _I _X _M i axs) = do
(a , _B) <- unbind bnd_B
_B' <- _B `elim` EFunc _I _X i
xs <- freshR "xs"
ppair <- _B `elim` EHyps _I _X _M i (vVar xs)
axs `elim` EElimPair _A (bind a _B') (kBind VType) (bind2 a xs ppair)
elim _D (EHyps _I _X _M i xs) =
throwError $
"Ill-typed evaluation of Hyps:" ++
"\nDescription:\n" ++ prettyPrint _D ++
"\nPair:\n" ++ prettyPrint xs
elim (VEnd j) (EProve _I _X _M m i q) =
return $ VTT
elim (VRec j _D) (EProve _I _X _M m i xxs) = do
_A <- _X `sub` j
_B <- _D `elim` EFunc _I _X i
(nm_xxs , x , xs) <- (,,) <$> freshR "xxs" <*> freshR "x" <*> freshR "xs"
_M' <- VRec j _D `elim` EHyps _I _X _M i (vVar nm_xxs)
ppair <- VPair <$> m `sub2` (j , vVar x) <*> _D `elim` EProve _I _X _M m i (vVar xs)
xxs `elim` EElimPair _A (kBind _B) (bind nm_xxs _M') (bind2 x xs ppair)
elim (VArg _A _B) (EProve _I _X _M m i axs) = do
(nm_axs , a , xs) <- (,,) <$> freshR "axs" <*> freshR "a" <*> freshR "xs"
_Ba <- _B `sub` vVar a
_B' <- _Ba `elim` (EFunc _I _X i)
_M' <- VArg _A _B `elim` EHyps _I _X _M i (vVar nm_axs)
ppair <- _Ba `elim` EProve _I _X _M m i (vVar xs)
axs `elim` EElimPair _A (bind a _B') (bind nm_axs _M') (bind2 a xs ppair)
elim _ (EProve _I _X _M m i xs) =
throwError "Ill-typed evaluation of prove"
elim VNil (EBranches _P) =
return VUnit
elim (VCons l _E) (EBranches _P) = do
_P' <- _P `subCompose` VThere
vProd <$> _P `sub` VHere <*> _E `elim` EBranches _P'
elim _ (EBranches _P) =
throwError "Ill-typed evaluation of Branches"
elim VHere (ECase (VCons l _E) _P ccs) = do
_Pthere <- _P `subCompose` VThere
_A <- _P `sub` VHere
_B <- _E `elim` EBranches _Pthere
let _M = _A
c <- freshR "c"
let ppair = vVar c
ccs `elim` EElimPair _A (kBind _B) (kBind _M) (bind2 c wildcardR ppair)
elim (VThere t) (ECase (VCons l _E) _P ccs) = do
_Pthere <- _P `subCompose` VThere
_A <- _P `sub` VHere
_B <- _E `elim` EBranches _Pthere
_M <- _P `sub` (VThere t)
cs <- freshR "cs"
ppair <- t `elim` ECase _E _Pthere (vVar cs)
ccs `elim` EElimPair _A (kBind _B) (kBind _M) (bind2 wildcardR cs ppair)
elim _ (ECase _E _P ccs) =
throwError "Ill-typed evaluation of case"
elims :: Value -> Spine -> SpireM Value
elims x Id = return x
elims x (Pipe fs f) = do
x' <- elims x fs
elim x' f
----------------------------------------------------------------------
-- Exported lookup functions.
lookupValAndType :: Nom -> SpireM (Value , Type)
lookupValAndType nm = do
ctx <- asks ctx
lookupCtx nm ctx
lookupType :: Nom -> SpireM Type
lookupType nm = snd <$> lookupValAndType nm
----------------------------------------------------------------------
-- Non-exported lookup functions.
lookupCtx :: Nom -> Tel -> SpireM (Value , Type)
lookupCtx nm (Extend (unrebind -> ((x , Embed _A) , xs))) =
if nm == x
then return (vVar nm , _A)
else lookupCtx nm xs
lookupCtx nm Empty = do
env <- asks env
lookupEnv nm env
lookupEnv :: Nom -> Env -> SpireM (Value , Type)
lookupEnv nm (VDef x a _A : xs) =
if nm == x
then return (a , _A)
else lookupEnv nm xs
lookupEnv nm [] = do
env <- asks env
ctx <- asks ctx
uCtx <- gets unifierCtx
throwError $
"Variable not in context or environment!\n" ++
"Referenced variable:\n" ++ prettyPrintError nm ++ "\n" ++
"\nCurrent context:\n" ++ prettyPrintError ctx ++ "\n"
-- "\nCurrent environment:\n" ++ prettyPrintError env ++ "\n" ++
----------------------------------------------------------------------
| spire/spire | src/Spire/Canonical/Evaluator.hs | bsd-3-clause | 8,446 | 0 | 14 | 2,149 | 3,735 | 1,886 | 1,849 | 198 | 2 |
{-# LANGUAGE FlexibleContexts
#-}
module OpSem where
import AST
import Errors
import qualified Control.Monad.Except as M
import qualified Control.Monad.IO.Class as M
-- (Recursion magic happens here)
import qualified Data.Functor.Foldable as Rec
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
import qualified Data.List as List
paramsUnique :: ParamList -> Bool
paramsUnique p = p == List.nub p -- uuuugly
executeProg :: (M.MonadIO m, M.MonadError Error m)
=> Program -> Env -> m Env
executeProg = Rec.fold executeDefList . reverse
where executeDefList :: (M.MonadIO m, M.MonadError Error m)
=> Rec.ListF Definition (Env -> m Env) -> Env -> m Env
executeDefList Rec.Nil env = return env
executeDefList (Rec.Cons def prevDefs) env =
execute def =<< prevDefs env
-- definitions are executed
execute :: (M.MonadIO m, M.MonadError Error m)
=> Definition -> Env -> m Env
execute (Global x e) env =
do (v, Env glob func param) <- evaluate e env
let glob' = Map.insert x v glob
return $ Env glob' func param
execute (Function f paramList e) (Env glob func param) =
do if paramsUnique paramList then return ()
else M.throwError $ ErrorString "nonunique paramater names"
let func' = Map.insert f (UserFunc paramList e) func
return $ Env glob func' param
-- expressions are evaluated
evaluate :: (M.MonadIO m, M.MonadError Error m)
=> Expr -> Env -> m (Value, Env)
evaluate = Rec.fold evaluateF
evaluateF :: (M.MonadIO m, M.MonadError Error m)
=> ExprF (Env -> m (Value, Env)) -> Env -> m (Value, Env)
evaluateF (IfF p eT eF) env =
do (b, env') <- p env
if b /= 0
then eT env'
else eF env'
evaluateF (WhileF p e) env0 =
let evalLoop env =
do (b, env') <- p env
if b == 0
then return env'
else do (_, env'') <- e env'
evalLoop env''
in fmap (\env1 -> (0, env1)) (evalLoop env0)
evaluateF (BlockF []) env =
return (0, env)
evaluateF (BlockF es) env0 =
let evalBlock [e] env = e env
evalBlock (e:es) env =
do (_, env') <- e env
evalBlock es env'
in evalBlock es env0
evaluateF (PrintF e) env =
do (v, env') <- e env
M.liftIO $ print v
return (v, env')
evaluateF (LocalF x e) env0 =
do (v, Env glob func param) <- e env0
let param' = Map.insert x v param
return (v, Env glob func param')
evaluateF (SetF x e) env0 =
do (v, Env glob func param) <- e env0
let result
| x `Map.member` param =
let param' = Map.adjust (const v) x param
in return (v, Env glob func param')
| x `Map.member` glob =
let glob' = Map.adjust (const v) x glob
in return (v, Env glob' func param)
| otherwise =
M.throwError . ErrorString $ "undefined var " ++ x ++ " is Set"
result
evaluateF (ApplyF fName argList) env0@(Env glob func param)
| Just function <- Map.lookup fName func =
do let evalArgs [] env = return ([], env)
evalArgs (arg:args) env =
do (v, env') <- arg env
(vs, env'') <- evalArgs args env'
return (v:vs, env'')
(args, env'@(Env glob' _ param')) <- evalArgs argList env0
case function of
BuiltinFunc f ->
case f args of
Nothing -> M.throwError . ErrorString
$ "wrong number of args to " ++ fName
Just n -> return (n, env')
UserFunc argNames e ->
do let argMap = Map.fromList $ zip argNames args
(v, Env globFinal _ _) <- evaluate e (Env glob' func argMap)
return (v, Env globFinal func param')
| otherwise = M.throwError . ErrorString
$ "undefined function " ++ fName ++ "is referenced"
evaluateF (ReferenceF x) env@(Env glob func param)
| Just v <- Map.lookup x param = return (v, env)
| Just v <- Map.lookup x glob = return (v, env)
| otherwise = M.throwError $ ErrorString "undefined var is referenced"
-- well boy howdie this one is easy
evaluateF (LiteralF n) env = return (n, env)
| ClathomasPrime/ImpCore | Impcore/src/OpSem.hs | bsd-3-clause | 4,185 | 0 | 17 | 1,247 | 1,667 | 833 | 834 | 102 | 7 |
-- |
-- Module : Network.TLS.Types
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
module Network.TLS.Types
( Version(..)
, SessionID
, SessionData(..)
, CipherID
, CompressionID
, Role(..)
, invertRole
, Direction(..)
) where
import Data.ByteString (ByteString)
import Data.Word
type HostName = String
-- | Versions known to TLS
--
-- SSL2 is just defined, but this version is and will not be supported.
data Version = SSL2 | SSL3 | TLS10 | TLS11 | TLS12 deriving (Show, Eq, Ord, Bounded)
-- | A session ID
type SessionID = ByteString
-- | Session data to resume
data SessionData = SessionData
{ sessionVersion :: Version
, sessionCipher :: CipherID
, sessionCompression :: CompressionID
, sessionClientSNI :: Maybe HostName
, sessionSecret :: ByteString
} deriving (Show,Eq)
-- | Cipher identification
type CipherID = Word16
-- | Compression identification
type CompressionID = Word8
-- | Role
data Role = ClientRole | ServerRole
deriving (Show,Eq)
-- | Direction
data Direction = Tx | Rx
deriving (Show,Eq)
invertRole :: Role -> Role
invertRole ClientRole = ServerRole
invertRole ServerRole = ClientRole
| erikd/hs-tls | core/Network/TLS/Types.hs | bsd-3-clause | 1,296 | 0 | 9 | 292 | 262 | 166 | 96 | 30 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE GADTs #-}
module Network.Krist.Transaction
where
import Data.Aeson
import GHC.Generics
import Data.Monoid
import Control.Krist.Request
import Control.Monad
import Control.Monad.IO.Class
import System.FilePath
import Network.Krist.Node
data Transaction
= Transaction { transID :: Int
, transFrom :: Maybe String
, transTo :: String
, transValue :: Int
, transTime :: String
, transName :: Maybe String
, transMeta :: Maybe String }
deriving (Eq, Show, Ord)
data TrnsRequestResp
= TrnsRequestResp { ok :: Bool
, transaction :: Transaction }
deriving (Eq, Show, Ord, Generic)
data TransesRequestRep
= TransesRequestRep { ok :: Bool
, count :: Int
, total :: Int
, transactions :: [Transaction] }
deriving (Eq, Show, Ord, Generic)
instance FromJSON TrnsRequestResp
instance FromJSON TransesRequestRep
instance FromJSON Transaction where
parseJSON (Object v)
= Transaction <$> v .: "id"
<*> v .: "from"
<*> v .: "to"
<*> v .: "value"
<*> v .: "time"
<*> v .: "name"
<*> v .: "metadata"
parseJSON _ = mzero
data TransRequest a where
GetTransaction :: Int -> TransRequest Transaction
GetTransactions :: Int -> Int -> TransRequest [Transaction]
GetLatest :: Int -> Int -> TransRequest [Transaction]
GetLatestMined :: Int -> Int -> TransRequest [Transaction]
GetAddrLatest :: String -> Int -> Int -> TransRequest [Transaction]
GetAddrLatestMined :: String -> Int -> Int -> TransRequest [Transaction]
instance Requestable TransRequest where
makeRequest n (GetTransaction x)
= selector transaction $ requestJSON n ("transactions" </> show x)
makeRequest n (GetTransactions a o)
= selector transactions $ requestJSON n ("transactions?limit=" <> show a <> "&offset=" <> show o)
makeRequest n (GetLatest a o)
= selector transactions $ requestJSON n $ concat [ "transactions/latest?limit=" , show a
, "&offset=", show o
, "&excludeMined=true" ]
makeRequest n (GetLatestMined a o)
= selector transactions $ requestJSON n $ concat [ "transactions/latest?limit=" , show a
, "&offset=", show o
, "&excludeMined=false" ]
makeRequest n (GetAddrLatestMined a l o)
= selector transactions $ requestJSON (n `nodeAt` ("addresses" </> a))
$ concat [ "transactions?limit=" , show l
, "&offset=", show o
, "&excludeMined=true" ]
makeRequest n (GetAddrLatest a l o)
= selector transactions $ requestJSON (n `nodeAt` ("addresses" </> a))
$ concat [ "transactions?limit=" , show l
, "&offset=", show o
, "&excludeMined=falsed" ]
getTransaction :: MonadIO m => Node -> Int -> m (Either ReqError Transaction)
getTransaction n x = makeRequest n (GetTransaction x)
getTransactions :: MonadIO m => Node -> Int -> Int -> m (Either ReqError [Transaction])
getTransactions n a o = makeRequest n (GetTransactions a o)
getLatestTransactions :: MonadIO m => Node -> Int -> Int -> m (Either ReqError [Transaction])
getLatestTransactions n a o = makeRequest n (GetLatest a o)
getLatestMined :: MonadIO m => Node -> Int -> Int -> m (Either ReqError [Transaction])
getLatestMined n a o = makeRequest n (GetLatestMined a o)
addressTransactions :: MonadIO m => Node -> String -> Int -> Int -> m (Either ReqError [Transaction])
addressTransactions n a l o = n `makeRequest` GetAddrLatest a l o
addressMined :: MonadIO m => Node -> String -> Int -> Int -> m (Either ReqError [Transaction])
addressMined n a l o = n `makeRequest` GetAddrLatestMined a l o
| demhydraz/krisths | src/Network/Krist/Transaction.hs | bsd-3-clause | 4,115 | 0 | 19 | 1,215 | 1,181 | 618 | 563 | 86 | 1 |
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Exts ( Float(F#),
eqFloat#, neFloat#, ltFloat#,
leFloat#, gtFloat#, geFloat#
)
fcmp_eq, fcmp_ne, fcmp_lt, fcmp_le, fcmp_gt, fcmp_ge :: (String, Float -> Float -> Bool)
fcmp_eq = ("==", \ (F# a) (F# b) -> a `eqFloat#` b)
fcmp_ne = ("/=", \ (F# a) (F# b) -> a `neFloat#` b)
fcmp_lt = ("< ", \ (F# a) (F# b) -> a `ltFloat#` b)
fcmp_le = ("<=", \ (F# a) (F# b) -> a `leFloat#` b)
fcmp_gt = ("> ", \ (F# a) (F# b) -> a `gtFloat#` b)
fcmp_ge = (">=", \ (F# a) (F# b) -> a `geFloat#` b)
float_fns = [fcmp_eq, fcmp_ne, fcmp_lt, fcmp_le, fcmp_gt, fcmp_ge]
float_vals :: [Float]
float_vals = [0.0, 1.0, read "NaN"]
float_text
= [show4 arg1 ++ " " ++ fn_name ++ " " ++ show4 arg2 ++ " = " ++ show (fn arg1 arg2)
| (fn_name, fn) <- float_fns,
arg1 <- float_vals,
arg2 <- float_vals
]
where
show4 x = take 4 (show x ++ repeat ' ')
main
= putStrLn (unlines float_text)
| kfish/const-math-ghc-plugin | tests/ghc-7.6/arith016.hs | bsd-3-clause | 982 | 6 | 12 | 246 | 457 | 265 | 192 | 23 | 1 |
{- Test Show instances
Copyright (c) 2014 Richard Eisenberg
-}
module Tests.Show where
import Data.Metrology
import Data.Metrology.Show ()
import Data.Metrology.SI
import Test.Tasty
import Test.Tasty.HUnit
five :: Double
five = 5
tests :: TestTree
tests = testGroup "Show"
[ testCase "Meter" $ show (five % Meter) @?= "5.0 m"
, testCase "Meter/Second" $ show (five % (Meter :/ Second)) @?= "5.0 m/s"
, testCase "Meter/Second2" $ show (five % (Number :* Second :* Meter :/ (Second :^ sTwo))) @?= "5.0 m/s"
, testCase "Hertz" $ show (five % Hertz) @?= "5.0 s^-1"
, testCase "Joule" $ show (five % Joule) @?= "5.0 (kg * m^2)/s^2"
]
| goldfirere/units | units-test/Tests/Show.hs | bsd-3-clause | 649 | 0 | 15 | 125 | 212 | 115 | 97 | 15 | 1 |
{-|
Module : Idris.Parser
Description : Idris' parser.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE ConstraintKinds, FlexibleContexts, GeneralizedNewtypeDeriving,
PatternGuards #-}
{-# OPTIONS_GHC -O0 #-}
module Idris.Parser(module Idris.Parser,
module Idris.Parser.Expr,
module Idris.Parser.Data,
module Idris.Parser.Helpers,
module Idris.Parser.Ops) where
import Idris.AbsSyntax hiding (namespace, params)
import Idris.Core.Evaluate
import Idris.Core.TT
import Idris.Coverage
import Idris.Delaborate
import Idris.Docstrings hiding (Unchecked)
import Idris.DSL
import Idris.Elab.Term
import Idris.Elab.Value
import Idris.ElabDecls
import Idris.Error
import Idris.IBC
import Idris.Imports
import Idris.Options
import Idris.Output
import Idris.Parser.Data
import Idris.Parser.Expr
import Idris.Parser.Helpers
import Idris.Parser.Ops
import Idris.Providers
import Idris.Termination
import Idris.Unlit
import Util.DynamicLinker
import qualified Util.Pretty as P
import Util.System (readSource, writeSource)
import Paths_idris
import Prelude hiding (pi)
import Control.Applicative hiding (Const)
import Control.Monad
import Control.Monad.State.Strict
import qualified Data.ByteString.UTF8 as UTF8
import Data.Char
import Data.Foldable (asum)
import Data.Function
import Data.Generics.Uniplate.Data (descendM)
import qualified Data.HashSet as HS
import Data.List
import qualified Data.List.Split as Spl
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import Data.Ord
import qualified Data.Set as S
import qualified Data.Text as T
import Debug.Trace
import qualified System.Directory as Dir (makeAbsolute)
import System.FilePath
import System.IO
import qualified Text.Parser.Char as Chr
import Text.Parser.Expression
import Text.Parser.LookAhead
import qualified Text.Parser.Token as Tok
import qualified Text.Parser.Token.Highlight as Hi
import Text.PrettyPrint.ANSI.Leijen (Doc, plain)
import qualified Text.PrettyPrint.ANSI.Leijen as ANSI
import Text.Trifecta hiding (Err, char, charLiteral, natural, span, string,
stringLiteral, symbol, whiteSpace)
import Text.Trifecta.Delta
{-
@
grammar shortcut notation:
~CHARSEQ = complement of char sequence (i.e. any character except CHARSEQ)
RULE? = optional rule (i.e. RULE or nothing)
RULE* = repeated rule (i.e. RULE zero or more times)
RULE+ = repeated rule with at least one match (i.e. RULE one or more times)
RULE! = invalid rule (i.e. rule that is not valid in context, report meaningful error in case)
RULE{n} = rule repeated n times
@
-}
{- * Main grammar -}
{-| Parses module definition
@
ModuleHeader ::= DocComment_t? 'module' Identifier_t ';'?;
@
-}
moduleHeader :: IdrisParser (Maybe (Docstring ()), [String], [(FC, OutputAnnotation)])
moduleHeader = try (do docs <- optional docComment
noArgs docs
reservedHL "module"
(i, ifc) <- identifier
option ';' (lchar ';')
let modName = moduleName i
return (fmap fst docs,
modName,
[(ifc, AnnNamespace (map T.pack modName) Nothing)]))
<|> try (do lchar '%'; reserved "unqualified"
return (Nothing, [], []))
<|> return (Nothing, moduleName "Main", [])
where moduleName x = case span (/='.') x of
(x, "") -> [x]
(x, '.':y) -> x : moduleName y
noArgs (Just (_, args)) | not (null args) = fail "Modules do not take arguments"
noArgs _ = return ()
data ImportInfo = ImportInfo { import_reexport :: Bool
, import_path :: FilePath
, import_rename :: Maybe (String, FC)
, import_namespace :: [T.Text]
, import_location :: FC
, import_modname_location :: FC
}
{-| Parses an import statement
@
Import ::= 'import' Identifier_t ';'?;
@
-}
import_ :: IdrisParser ImportInfo
import_ = do fc <- getFC
reservedHL "import"
reexport <- option False (do reservedHL "public"
return True)
(id, idfc) <- identifier
newName <- optional (do reservedHL "as"
identifier)
option ';' (lchar ';')
return $ ImportInfo reexport (toPath id)
(fmap (\(n, fc) -> (toPath n, fc)) newName)
(map T.pack $ ns id) fc idfc
<?> "import statement"
where ns = Spl.splitOn "."
toPath = foldl1' (</>) . ns
{-| Parses program source
@
Prog ::= Decl* EOF;
@
-}
prog :: SyntaxInfo -> IdrisParser [PDecl]
prog syn = do whiteSpace
decls <- many (decl syn)
let c = concat decls
case maxline syn of
Nothing -> do notOpenBraces; eof
_ -> return ()
ist <- get
fc <- getFC
put ist { idris_parsedSpan = Just (FC (fc_fname fc) (0,0) (fc_end fc)),
ibc_write = IBCParsedRegion fc : ibc_write ist }
return c
{-| Parses a top-level declaration
@
Decl ::=
Decl'
| Using
| Params
| Mutual
| Namespace
| Interface
| Implementation
| DSL
| Directive
| Provider
| Transform
| Import!
| RunElabDecl
;
@
-}
decl :: SyntaxInfo -> IdrisParser [PDecl]
decl syn = try (externalDecl syn)
<|> internalDecl syn
<?> "declaration"
internalDecl :: SyntaxInfo -> IdrisParser [PDecl]
internalDecl syn
= do fc <- getFC
-- if we're after maxline, stop at the next type declaration
-- (so we get all cases of a definition to preserve totality
-- results, in particular).
let continue = case maxline syn of
Nothing -> True
Just l -> if fst (fc_end fc) > l
then mut_nesting syn /= 0
else True
-- What I'd really like to do here is explicitly save the
-- current state, then if reading ahead finds we've passed
-- the end of the definition, reset the state. But I've lost
-- patience with trying to find out how to do that from the
-- trifecta docs, so this does the job instead.
if continue then
do notEndBlock
declBody continue
else try (do notEndBlock
declBody continue)
<|> fail "End of readable input"
where declBody :: Bool -> IdrisParser [PDecl]
declBody b =
try (implementation True syn)
<|> try (openInterface syn)
<|> declBody' b
<|> using_ syn
<|> params syn
<|> mutual syn
<|> namespace syn
<|> interface_ syn
<|> do d <- dsl syn; return [d]
<|> directive syn
<|> provider syn
<|> transform syn
<|> do import_; fail "imports must be at top of file"
<?> "declaration"
declBody' :: Bool -> IdrisParser [PDecl]
declBody' cont = do d <- decl' syn
i <- get
let d' = fmap (debindApp syn . (desugar syn i)) d
if continue cont d'
then return [d']
else fail "End of readable input"
-- Keep going while we're still parsing clauses
continue False (PClauses _ _ _ _) = True
continue c _ = c
{-| Parses a top-level declaration with possible syntax sugar
@
Decl' ::=
Fixity
| FunDecl'
| Data
| Record
| SyntaxDecl
;
@
-}
decl' :: SyntaxInfo -> IdrisParser PDecl
decl' syn = fixity
<|> syntaxDecl syn
<|> fnDecl' syn
<|> data_ syn
<|> record syn
<|> runElabDecl syn
<?> "declaration"
externalDecl :: SyntaxInfo -> IdrisParser [PDecl]
externalDecl syn = do i <- get
notEndBlock
FC fn start _ <- getFC
decls <- declExtensions syn (syntaxRulesList $ syntax_rules i)
FC _ _ end <- getFC
let outerFC = FC fn start end
return $ map (mapPDeclFC (fixFC outerFC)
(fixFCH fn outerFC))
decls
where
-- | Fix non-highlighting FCs to prevent spurious error location reports
fixFC :: FC -> FC -> FC
fixFC outer inner | inner `fcIn` outer = inner
| otherwise = outer
-- | Fix highlighting FCs by obliterating them, to avoid spurious highlights
fixFCH fn outer inner | inner `fcIn` outer = inner
| otherwise = FileFC fn
declExtensions :: SyntaxInfo -> [Syntax] -> IdrisParser [PDecl]
declExtensions syn rules = declExtension syn [] (filter isDeclRule rules)
<?> "user-defined declaration"
where
isDeclRule (DeclRule _ _) = True
isDeclRule _ = False
declExtension :: SyntaxInfo -> [Maybe (Name, SynMatch)] -> [Syntax]
-> IdrisParser [PDecl]
declExtension syn ns rules =
choice $ flip map (groupBy (ruleGroup `on` syntaxSymbols) rules) $ \rs ->
case head rs of -- can never be []
DeclRule (symb:_) _ -> try $ do
n <- extSymbol symb
declExtension syn (n : ns) [DeclRule ss t | (DeclRule (_:ss) t) <- rs]
-- If we have more than one Rule in this bucket, our grammar is
-- nondeterministic.
DeclRule [] dec -> let r = map (update (mapMaybe id ns)) dec in
return r
where
update :: [(Name, SynMatch)] -> PDecl -> PDecl
update ns = updateNs ns . fmap (updateRefs ns) . fmap (updateSynMatch ns)
updateRefs ns = mapPT newref
where
newref (PRef fc fcs n) = PRef fc fcs (updateB ns n)
newref t = t
-- Below is a lot of tedious boilerplate which updates any top level
-- names in the declaration. It will only change names which are bound in
-- the declaration (including method names in interfaces and field names in
-- record declarations, not including pattern variables)
updateB :: [(Name, SynMatch)] -> Name -> Name
updateB ns (NS n mods) = NS (updateB ns n) mods
updateB ns n = case lookup n ns of
Just (SynBind tfc t) -> t
_ -> n
updateNs :: [(Name, SynMatch)] -> PDecl -> PDecl
updateNs ns (PTy doc argdoc s fc o n fc' t)
= PTy doc argdoc s fc o (updateB ns n) fc' t
updateNs ns (PClauses fc o n cs)
= PClauses fc o (updateB ns n) (map (updateClause ns) cs)
updateNs ns (PCAF fc n t) = PCAF fc (updateB ns n) t
updateNs ns (PData ds cds s fc o dat)
= PData ds cds s fc o (updateData ns dat)
updateNs ns (PParams fc ps ds) = PParams fc ps (map (updateNs ns) ds)
updateNs ns (PNamespace s fc ds) = PNamespace s fc (map (updateNs ns) ds)
updateNs ns (PRecord doc syn fc o n fc' ps pdocs fields cname cdoc s)
= PRecord doc syn fc o (updateB ns n) fc' ps pdocs
(map (updateField ns) fields)
(updateRecCon ns cname)
cdoc
s
updateNs ns (PInterface docs s fc cs cn fc' ps pdocs pdets ds cname cdocs)
= PInterface docs s fc cs (updateB ns cn) fc' ps pdocs pdets
(map (updateNs ns) ds)
(updateRecCon ns cname)
cdocs
updateNs ns (PImplementation docs pdocs s fc cs pnames acc opts cn fc' ps pextra ity ni ds)
= PImplementation docs pdocs s fc cs pnames acc opts (updateB ns cn) fc'
ps pextra ity (fmap (updateB ns) ni)
(map (updateNs ns) ds)
updateNs ns (PMutual fc ds) = PMutual fc (map (updateNs ns) ds)
updateNs ns (PProvider docs s fc fc' pw n)
= PProvider docs s fc fc' pw (updateB ns n)
updateNs ns d = d
updateRecCon ns Nothing = Nothing
updateRecCon ns (Just (n, fc)) = Just (updateB ns n, fc)
updateField ns (m, p, t, doc) = (updateRecCon ns m, p, t, doc)
updateClause ns (PClause fc n t ts t' ds)
= PClause fc (updateB ns n) t ts t' (map (update ns) ds)
updateClause ns (PWith fc n t ts t' m ds)
= PWith fc (updateB ns n) t ts t' m (map (update ns) ds)
updateClause ns (PClauseR fc ts t ds)
= PClauseR fc ts t (map (update ns) ds)
updateClause ns (PWithR fc ts t m ds)
= PWithR fc ts t m (map (update ns) ds)
updateData ns (PDatadecl n fc t cs)
= PDatadecl (updateB ns n) fc t (map (updateCon ns) cs)
updateData ns (PLaterdecl n fc t)
= PLaterdecl (updateB ns n) fc t
updateCon ns (cd, ads, cn, fc, ty, fc', fns)
= (cd, ads, updateB ns cn, fc, ty, fc', fns)
ruleGroup [] [] = True
ruleGroup (s1:_) (s2:_) = s1 == s2
ruleGroup _ _ = False
extSymbol :: SSymbol -> IdrisParser (Maybe (Name, SynMatch))
extSymbol (Keyword n) = do fc <- reservedFC (show n)
highlightP fc AnnKeyword
return Nothing
extSymbol (Expr n) = do tm <- expr syn
return $ Just (n, SynTm tm)
extSymbol (SimpleExpr n) = do tm <- simpleExpr syn
return $ Just (n, SynTm tm)
extSymbol (Binding n) = do (b, fc) <- name
return $ Just (n, SynBind fc b)
extSymbol (Symbol s) = do fc <- symbolFC s
highlightP fc AnnKeyword
return Nothing
{-| Parses a syntax extension declaration (and adds the rule to parser state)
@
SyntaxDecl ::= SyntaxRule;
@
-}
syntaxDecl :: SyntaxInfo -> IdrisParser PDecl
syntaxDecl syn = do s <- syntaxRule syn
i <- get
put (i `addSyntax` s)
fc <- getFC
return (PSyntax fc s)
-- | Extend an 'IState' with a new syntax extension. See also 'addReplSyntax'.
addSyntax :: IState -> Syntax -> IState
addSyntax i s = i { syntax_rules = updateSyntaxRules [s] rs,
syntax_keywords = ks ++ ns,
ibc_write = IBCSyntax s : map IBCKeyword ks ++ ibc }
where rs = syntax_rules i
ns = syntax_keywords i
ibc = ibc_write i
ks = map show (syntaxNames s)
-- | Like 'addSyntax', but no effect on the IBC.
addReplSyntax :: IState -> Syntax -> IState
addReplSyntax i s = i { syntax_rules = updateSyntaxRules [s] rs,
syntax_keywords = ks ++ ns }
where rs = syntax_rules i
ns = syntax_keywords i
ks = map show (syntaxNames s)
{-| Parses a syntax extension declaration
@
SyntaxRuleOpts ::= 'term' | 'pattern';
@
@
SyntaxRule ::=
SyntaxRuleOpts? 'syntax' SyntaxSym+ '=' TypeExpr Terminator;
@
@
SyntaxSym ::= '[' Name_t ']'
| '{' Name_t '}'
| Name_t
| StringLiteral_t
;
@
-}
syntaxRule :: SyntaxInfo -> IdrisParser Syntax
syntaxRule syn
= do sty <- try (do
pushIndent
sty <- option AnySyntax
(do reservedHL "term"; return TermSyntax
<|> do reservedHL "pattern"; return PatternSyntax)
reservedHL "syntax"
return sty)
syms <- some syntaxSym
when (all isExpr syms) $ unexpected "missing keywords in syntax rule"
let ns = mapMaybe getName syms
when (length ns /= length (nub ns))
$ unexpected "repeated variable in syntax rule"
lchar '='
tm <- typeExpr (allowImp syn) >>= uniquifyBinders [n | Binding n <- syms]
terminator
return (Rule (mkSimple syms) tm sty)
<|> do reservedHL "decl"; reservedHL "syntax"
syms <- some syntaxSym
when (all isExpr syms) $ unexpected "missing keywords in syntax rule"
let ns = mapMaybe getName syms
when (length ns /= length (nub ns))
$ unexpected "repeated variable in syntax rule"
lchar '='
openBlock
dec <- some (decl syn)
closeBlock
return (DeclRule (mkSimple syms) (concat dec))
where
isExpr (Expr _) = True
isExpr _ = False
getName (Expr n) = Just n
getName _ = Nothing
-- Can't parse two full expressions (i.e. expressions with application) in a row
-- so change them both to a simple expression
mkSimple (Expr e : es) = SimpleExpr e : mkSimple' es
mkSimple xs = mkSimple' xs
mkSimple' (Expr e : Expr e1 : es) = SimpleExpr e : SimpleExpr e1 :
mkSimple es
-- Can't parse a full expression followed by operator like characters due to ambiguity
mkSimple' (Expr e : Symbol s : es)
| takeWhile (`elem` opChars) ts /= "" = SimpleExpr e : Symbol s : mkSimple' es
where ts = dropWhile isSpace . dropWhileEnd isSpace $ s
mkSimple' (e : es) = e : mkSimple' es
mkSimple' [] = []
-- Prevent syntax variable capture by making all binders under syntax unique
-- (the ol' Common Lisp GENSYM approach)
uniquifyBinders :: [Name] -> PTerm -> IdrisParser PTerm
uniquifyBinders userNames = fixBind 0 []
where
fixBind :: Int -> [(Name, Name)] -> PTerm -> IdrisParser PTerm
fixBind 0 rens (PRef fc hls n) | Just n' <- lookup n rens =
return $ PRef fc hls n'
fixBind 0 rens (PPatvar fc n) | Just n' <- lookup n rens =
return $ PPatvar fc n'
fixBind 0 rens (PLam fc n nfc ty body)
| n `elem` userNames = liftM2 (PLam fc n nfc)
(fixBind 0 rens ty)
(fixBind 0 rens body)
| otherwise =
do ty' <- fixBind 0 rens ty
n' <- gensym n
body' <- fixBind 0 ((n,n'):rens) body
return $ PLam fc n' nfc ty' body'
fixBind 0 rens (PPi plic n nfc argTy body)
| n `elem` userNames = liftM2 (PPi plic n nfc)
(fixBind 0 rens argTy)
(fixBind 0 rens body)
| otherwise =
do ty' <- fixBind 0 rens argTy
n' <- gensym n
body' <- fixBind 0 ((n,n'):rens) body
return $ (PPi plic n' nfc ty' body')
fixBind 0 rens (PLet fc n nfc ty val body)
| n `elem` userNames = liftM3 (PLet fc n nfc)
(fixBind 0 rens ty)
(fixBind 0 rens val)
(fixBind 0 rens body)
| otherwise =
do ty' <- fixBind 0 rens ty
val' <- fixBind 0 rens val
n' <- gensym n
body' <- fixBind 0 ((n,n'):rens) body
return $ PLet fc n' nfc ty' val' body'
fixBind 0 rens (PMatchApp fc n) | Just n' <- lookup n rens =
return $ PMatchApp fc n'
-- Also rename resolved quotations, to allow syntax rules to
-- have quoted references to their own bindings.
fixBind 0 rens (PQuoteName n True fc) | Just n' <- lookup n rens =
return $ PQuoteName n' True fc
-- Don't mess with quoted terms
fixBind q rens (PQuasiquote tm goal) =
flip PQuasiquote goal <$> fixBind (q + 1) rens tm
fixBind q rens (PUnquote tm) =
PUnquote <$> fixBind (q - 1) rens tm
fixBind q rens x = descendM (fixBind q rens) x
gensym :: Name -> IdrisParser Name
gensym n = do ist <- get
let idx = idris_name ist
put ist { idris_name = idx + 1 }
return $ sMN idx (show n)
{-| Parses a syntax symbol (either binding variable, keyword or expression)
@
SyntaxSym ::= '[' Name_t ']'
| '{' Name_t '}'
| Name_t
| StringLiteral_t
;
@
-}
syntaxSym :: IdrisParser SSymbol
syntaxSym = try (do lchar '['; n <- fst <$> name; lchar ']'
return (Expr n))
<|> try (do lchar '{'; n <- fst <$> name; lchar '}'
return (Binding n))
<|> do n <- fst <$> iName []
return (Keyword n)
<|> do sym <- fmap fst stringLiteral
return (Symbol sym)
<?> "syntax symbol"
{-| Parses a function declaration with possible syntax sugar
@
FunDecl ::= FunDecl';
@
-}
fnDecl :: SyntaxInfo -> IdrisParser [PDecl]
fnDecl syn = try (do notEndBlock
d <- fnDecl' syn
i <- get
let d' = fmap (desugar syn i) d
return [d']) <?> "function declaration"
{-| Parses a function declaration
@
FunDecl' ::=
DocComment_t? FnOpts* Accessibility? FnOpts* FnName TypeSig Terminator
| Postulate
| Pattern
| CAF
;
@
-}
fnDecl' :: SyntaxInfo -> IdrisParser PDecl
fnDecl' syn = checkDeclFixity $
do (doc, argDocs, fc, opts', n, nfc, acc) <- try (do
pushIndent
(doc, argDocs) <- docstring syn
(opts, acc) <- fnOpts
(n_in, nfc) <- fnName
let n = expandNS syn n_in
fc <- getFC
lchar ':'
return (doc, argDocs, fc, opts, n, nfc, acc))
ty <- typeExpr (allowImp syn)
terminator
-- If it's a top level function, note the accessibility
-- rules
when (syn_toplevel syn) $ addAcc n acc
return (PTy doc argDocs syn fc opts' n nfc ty)
<|> postulate syn
<|> caf syn
<|> pattern syn
<?> "function declaration"
{-| Parses a series of function and accessbility options
@
FnOpts ::= FnOpt* Accessibility FnOpt*
@
-}
fnOpts :: IdrisParser ([FnOpt], Accessibility)
fnOpts = do
opts <- many fnOpt
acc <- accessibility
opts' <- many fnOpt
let allOpts = opts ++ opts'
let existingTotality = allOpts `intersect` [TotalFn, CoveringFn, PartialFn]
opts'' <- addDefaultTotality (nub existingTotality) allOpts
return (opts'', acc)
where prettyTot TotalFn = "total"
prettyTot PartialFn = "partial"
prettyTot CoveringFn = "covering"
addDefaultTotality [] opts = do
ist <- get
case default_total ist of
DefaultCheckingTotal -> return (TotalFn:opts)
DefaultCheckingCovering -> return (CoveringFn:opts)
DefaultCheckingPartial -> return opts -- Don't add partial so that --warn-partial still reports warnings if necessary
addDefaultTotality [tot] opts = return opts
-- Should really be a semantics error instead of a parser error
addDefaultTotality (tot1:tot2:tots) opts =
fail ("Conflicting totality modifiers specified " ++ prettyTot tot1 ++ " and " ++ prettyTot tot2)
{-| Parses a function option
@
FnOpt ::= 'total'
| 'partial'
| 'covering'
| 'implicit'
| '%' 'no_implicit'
| '%' 'assert_total'
| '%' 'error_handler'
| '%' 'reflection'
| '%' 'specialise' '[' NameTimesList? ']'
;
@
@
NameTimes ::= FnName Natural?;
@
@
NameTimesList ::=
NameTimes
| NameTimes ',' NameTimesList
;
@
-}
fnOpt :: IdrisParser FnOpt
fnOpt = do reservedHL "total"; return TotalFn
<|> do reservedHL "partial"; return PartialFn
<|> do reservedHL "covering"; return CoveringFn
<|> do try (lchar '%' *> reserved "export"); c <- fmap fst stringLiteral;
return $ CExport c
<|> do try (lchar '%' *> reserved "no_implicit");
return NoImplicit
<|> do try (lchar '%' *> reserved "inline");
return Inlinable
<|> do try (lchar '%' *> reserved "static");
return StaticFn
<|> do try (lchar '%' *> reserved "assert_total");
fc <- getFC
parserWarning fc Nothing (Msg "%assert_total is deprecated. Use the 'assert_total' function instead.")
return AssertTotal
<|> do try (lchar '%' *> reserved "error_handler");
return ErrorHandler
<|> do try (lchar '%' *> reserved "error_reverse");
return ErrorReverse
<|> do try (lchar '%' *> reserved "error_reduce");
return ErrorReduce
<|> do try (lchar '%' *> reserved "reflection");
return Reflection
<|> do try (lchar '%' *> reserved "hint");
return AutoHint
<|> do try (lchar '%' *> reserved "overlapping");
return OverlappingDictionary
<|> do lchar '%'; reserved "specialise";
lchar '['; ns <- sepBy nameTimes (lchar ','); lchar ']';
return $ Specialise ns
<|> do reservedHL "implicit"; return Implicit
<?> "function modifier"
where nameTimes :: IdrisParser (Name, Maybe Int)
nameTimes = do n <- fst <$> fnName
t <- option Nothing (do reds <- fmap fst natural
return (Just (fromInteger reds)))
return (n, t)
{-| Parses a postulate
@
Postulate ::=
DocComment_t? 'postulate' FnOpts* Accesibility? FnOpts* FnName TypeSig Terminator
;
@
-}
postulate :: SyntaxInfo -> IdrisParser PDecl
postulate syn = do (doc, ext)
<- try $ do (doc, _) <- docstring syn
pushIndent
ext <- ppostDecl
return (doc, ext)
ist <- get
(opts, acc) <- fnOpts
(n_in, nfc) <- fnName
let n = expandNS syn n_in
lchar ':'
ty <- typeExpr (allowImp syn)
fc <- getFC
terminator
addAcc n acc
return (PPostulate ext doc syn fc nfc opts n ty)
<?> "postulate"
where ppostDecl = do fc <- reservedHL "postulate"; return False
<|> do lchar '%'; reserved "extern"; return True
{-| Parses a using declaration
@
Using ::=
'using' '(' UsingDeclList ')' OpenBlock Decl* CloseBlock
;
@
-}
using_ :: SyntaxInfo -> IdrisParser [PDecl]
using_ syn =
do reservedHL "using"
lchar '('; ns <- usingDeclList syn; lchar ')'
openBlock
let uvars = using syn
ds <- many (decl (syn { using = uvars ++ ns }))
closeBlock
return (concat ds)
<?> "using declaration"
{-| Parses a parameters declaration
@
Params ::=
'parameters' '(' TypeDeclList ')' OpenBlock Decl* CloseBlock
;
@
-}
params :: SyntaxInfo -> IdrisParser [PDecl]
params syn =
do reservedHL "parameters"; lchar '('; ns <- typeDeclList syn; lchar ')'
let ns' = [(n, ty) | (_, n, _, ty) <- ns]
openBlock
let pvars = syn_params syn
ds <- many (decl syn { syn_params = pvars ++ ns' })
closeBlock
fc <- getFC
return [PParams fc ns' (concat ds)]
<?> "parameters declaration"
-- | Parses an open block
openInterface :: SyntaxInfo -> IdrisParser [PDecl]
openInterface syn =
do reservedHL "using"
reservedHL "implementation"
fc <- getFC
ns <- sepBy1 fnName (lchar ',')
openBlock
ds <- many (decl syn)
closeBlock
return [POpenInterfaces fc (map fst ns) (concat ds)]
<?> "open interface declaration"
{-| Parses a mutual declaration (for mutually recursive functions)
@
Mutual ::=
'mutual' OpenBlock Decl* CloseBlock
;
@
-}
mutual :: SyntaxInfo -> IdrisParser [PDecl]
mutual syn =
do reservedHL "mutual"
openBlock
let pvars = syn_params syn
ds <- many (decl (syn { mut_nesting = mut_nesting syn + 1 } ))
closeBlock
fc <- getFC
return [PMutual fc (concat ds)]
<?> "mutual block"
{-| Parses a namespace declaration
@
Namespace ::=
'namespace' identifier OpenBlock Decl+ CloseBlock
;
@
-}
namespace :: SyntaxInfo -> IdrisParser [PDecl]
namespace syn =
do reservedHL "namespace"
(n, nfc) <- identifier
openBlock
ds <- some (decl syn { syn_namespace = n : syn_namespace syn })
closeBlock
return [PNamespace n nfc (concat ds)]
<?> "namespace declaration"
{-| Parses a methods block (for implementations)
@
ImplementationBlock ::= 'where' OpenBlock FnDecl* CloseBlock
@
-}
implementationBlock :: SyntaxInfo -> IdrisParser [PDecl]
implementationBlock syn = do reservedHL "where"
openBlock
ds <- many (fnDecl syn)
closeBlock
return (concat ds)
<?> "implementation block"
{-| Parses a methods and implementations block (for interfaces)
@
MethodOrImplementation ::=
FnDecl
| Implementation
;
@
@
InterfaceBlock ::=
'where' OpenBlock Constructor? MethodOrImplementation* CloseBlock
;
@
-}
interfaceBlock :: SyntaxInfo -> IdrisParser (Maybe (Name, FC), Docstring (Either Err PTerm), [PDecl])
interfaceBlock syn = do reservedHL "where"
openBlock
(cn, cd) <- option (Nothing, emptyDocstring) $
try (do (doc, _) <- option noDocs docComment
n <- constructor
return (Just n, doc))
ist <- get
let cd' = annotate syn ist cd
ds <- many (notEndBlock >> try (implementation True syn)
<|> do x <- data_ syn
return [x]
<|> fnDecl syn)
closeBlock
return (cn, cd', concat ds)
<?> "interface block"
where
constructor :: IdrisParser (Name, FC)
constructor = reservedHL "constructor" *> fnName
annotate :: SyntaxInfo -> IState -> Docstring () -> Docstring (Either Err PTerm)
annotate syn ist = annotCode $ tryFullExpr syn ist
{-| Parses an interface declaration
@
InterfaceArgument ::=
Name
| '(' Name ':' Expr ')'
;
@
@
Interface ::=
DocComment_t? Accessibility? 'interface' ConstraintList? Name InterfaceArgument* InterfaceBlock?
;
@
-}
interface_ :: SyntaxInfo -> IdrisParser [PDecl]
interface_ syn = do (doc, argDocs, acc)
<- try (do (doc, argDocs) <- docstring syn
acc <- accessibility
interfaceKeyword
return (doc, argDocs, acc))
fc <- getFC
cons <- constraintList syn
let cons' = [(c, ty) | (_, c, _, ty) <- cons]
(n_in, nfc) <- fnName
let n = expandNS syn n_in
cs <- many carg
fds <- option [(cn, NoFC) | (cn, _, _) <- cs] fundeps
(cn, cd, ds) <- option (Nothing, fst noDocs, []) (interfaceBlock syn)
accData acc n (concatMap declared ds)
return [PInterface doc syn fc cons' n nfc cs argDocs fds ds cn cd]
<?> "interface declaration"
where
fundeps :: IdrisParser [(Name, FC)]
fundeps = do lchar '|'; sepBy name (lchar ',')
interfaceKeyword :: IdrisParser ()
interfaceKeyword = reservedHL "interface"
<|> do reservedHL "class"
fc <- getFC
parserWarning fc Nothing (Msg "The 'class' keyword is deprecated. Use 'interface' instead.")
carg :: IdrisParser (Name, FC, PTerm)
carg = do lchar '('; (i, ifc) <- name; lchar ':'; ty <- expr syn; lchar ')'
return (i, ifc, ty)
<|> do (i, ifc) <- name
fc <- getFC
return (i, ifc, PType fc)
{-| Parses an interface implementation declaration
@
Implementation ::=
DocComment_t? 'implementation' ImplementationName? ConstraintList? Name SimpleExpr* ImplementationBlock?
;
@
@
ImplementationName ::= '[' Name ']';
@
-}
implementation :: Bool -> SyntaxInfo -> IdrisParser [PDecl]
implementation kwopt syn
= do ist <- get
(doc, argDocs) <- docstring syn
(opts, acc) <- fnOpts
if kwopt then optional implementationKeyword
else do implementationKeyword
return (Just ())
fc <- getFC
en <- optional implementationName
cs <- constraintList syn
let cs' = [(c, ty) | (_, c, _, ty) <- cs]
(cn, cnfc) <- fnName
args <- many (simpleExpr syn)
let sc = PApp fc (PRef cnfc [cnfc] cn) (map pexp args)
let t = bindList (\r -> PPi constraint { pcount = r }) cs sc
pnames <- implementationUsing
ds <- implementationBlock syn
return [PImplementation doc argDocs syn fc cs' pnames acc opts cn cnfc args [] t en ds]
<?> "implementation declaration"
where implementationName :: IdrisParser Name
implementationName = do lchar '['; n_in <- fst <$> fnName; lchar ']'
let n = expandNS syn n_in
return n
<?> "implementation name"
implementationKeyword :: IdrisParser ()
implementationKeyword = reservedHL "implementation"
<|> do reservedHL "instance"
fc <- getFC
parserWarning fc Nothing (Msg "The 'instance' keyword is deprecated. Use 'implementation' (or omit it) instead.")
implementationUsing :: IdrisParser [Name]
implementationUsing = do reservedHL "using"
ns <- sepBy1 fnName (lchar ',')
return (map fst ns)
<|> return []
-- | Parse a docstring
docstring :: SyntaxInfo
-> IdrisParser (Docstring (Either Err PTerm),
[(Name,Docstring (Either Err PTerm))])
docstring syn = do (doc, argDocs) <- option noDocs docComment
ist <- get
let doc' = annotCode (tryFullExpr syn ist) doc
argDocs' = [ (n, annotCode (tryFullExpr syn ist) d)
| (n, d) <- argDocs ]
return (doc', argDocs')
{-| Parses a using declaration list
@
UsingDeclList ::=
UsingDeclList'
| NameList TypeSig
;
@
@
UsingDeclList' ::=
UsingDecl
| UsingDecl ',' UsingDeclList'
;
@
@
NameList ::=
Name
| Name ',' NameList
;
@
-}
usingDeclList :: SyntaxInfo -> IdrisParser [Using]
usingDeclList syn
= try (sepBy1 (usingDecl syn) (lchar ','))
<|> do ns <- sepBy1 (fst <$> name) (lchar ',')
lchar ':'
t <- typeExpr (disallowImp syn)
return (map (\x -> UImplicit x t) ns)
<?> "using declaration list"
{-| Parses a using declaration
@
UsingDecl ::=
FnName TypeSig
| FnName FnName+
;
@
-}
usingDecl :: SyntaxInfo -> IdrisParser Using
usingDecl syn = try (do x <- fst <$> fnName
lchar ':'
t <- typeExpr (disallowImp syn)
return (UImplicit x t))
<|> do c <- fst <$> fnName
xs <- many (fst <$> fnName)
return (UConstraint c xs)
<?> "using declaration"
{-| Parse a clause with patterns
@
Pattern ::= Clause;
@
-}
pattern :: SyntaxInfo -> IdrisParser PDecl
pattern syn = do fc <- getFC
clause <- clause syn
return (PClauses fc [] (sMN 2 "_") [clause]) -- collect together later
<?> "pattern"
{-| Parse a constant applicative form declaration
@
CAF ::= 'let' FnName '=' Expr Terminator;
@
-}
caf :: SyntaxInfo -> IdrisParser PDecl
caf syn = do reservedHL "let"
n_in <- fst <$> fnName; let n = expandNS syn n_in
pushIndent
lchar '='
t <- indented $ expr syn
terminator
fc <- getFC
return (PCAF fc n t)
<?> "constant applicative form declaration"
{-| Parse an argument expression
@
ArgExpr ::= HSimpleExpr | {- In Pattern External (User-defined) Expression -};
@
-}
argExpr :: SyntaxInfo -> IdrisParser PTerm
argExpr syn = let syn' = syn { inPattern = True } in
try (hsimpleExpr syn') <|> simpleExternalExpr syn'
<?> "argument expression"
{-| Parse a right hand side of a function
@
RHS ::= '=' Expr
| '?=' RHSName? Expr
| Impossible
;
@
@
RHSName ::= '{' FnName '}';
@
-}
rhs :: SyntaxInfo -> Name -> IdrisParser PTerm
rhs syn n = do lchar '='
indentPropHolds gtProp
expr syn
<|> do symbol "?=";
fc <- getFC
name <- option n' (do symbol "{"; n <- fst <$> fnName; symbol "}";
return n)
r <- expr syn
return (addLet fc name r)
<|> impossible
<?> "function right hand side"
where mkN :: Name -> Name
mkN (UN x) = if (tnull x || not (isAlpha (thead x)))
then sUN "infix_op_lemma_1"
else sUN (str x++"_lemma_1")
mkN (NS x n) = NS (mkN x) n
n' :: Name
n' = mkN n
addLet :: FC -> Name -> PTerm -> PTerm
addLet fc nm (PLet fc' n nfc ty val r) = PLet fc' n nfc ty val (addLet fc nm r)
addLet fc nm (PCase fc' t cs) = PCase fc' t (map addLetC cs)
where addLetC (l, r) = (l, addLet fc nm r)
addLet fc nm r = (PLet fc (sUN "value") NoFC Placeholder r (PMetavar NoFC nm))
{-|Parses a function clause
@
RHSOrWithBlock ::= RHS WhereOrTerminator
| 'with' SimpleExpr OpenBlock FnDecl+ CloseBlock
;
@
@
Clause ::= WExpr+ RHSOrWithBlock
| SimpleExpr '<==' FnName RHS WhereOrTerminator
| ArgExpr Operator ArgExpr WExpr* RHSOrWithBlock {- Except "=" and "?=" operators to avoid ambiguity -}
| FnName ConstraintArg* ImplicitOrArgExpr* WExpr* RHSOrWithBlock
;
@
@
ImplicitOrArgExpr ::= ImplicitArg | ArgExpr;
@
@
WhereOrTerminator ::= WhereBlock | Terminator;
@
-}
clause :: SyntaxInfo -> IdrisParser PClause
clause syn
= do wargs <- try (do pushIndent; some (wExpr syn))
fc <- getFC
ist <- get
n <- case lastParse ist of
Just t -> return t
Nothing -> fail "Invalid clause"
(do r <- rhs syn n
let ctxt = tt_ctxt ist
let wsyn = syn { syn_namespace = [], syn_toplevel = False }
(wheres, nmap) <- choice [do x <- whereBlock n wsyn
popIndent
return x,
do terminator
return ([], [])]
return $ PClauseR fc wargs r wheres) <|> (do
popIndent
reservedHL "with"
wval <- simpleExpr syn
pn <- optProof
openBlock
ds <- some $ fnDecl syn
let withs = concat ds
closeBlock
return $ PWithR fc wargs wval pn withs)
<|> do ty <- try (do pushIndent
ty <- simpleExpr syn
symbol "<=="
return ty)
fc <- getFC
n_in <- fst <$> fnName; let n = expandNS syn n_in
r <- rhs syn n
ist <- get
let ctxt = tt_ctxt ist
let wsyn = syn { syn_namespace = [] }
(wheres, nmap) <- choice [do x <- whereBlock n wsyn
popIndent
return x,
do terminator
return ([], [])]
let capp = PLet fc (sMN 0 "match") NoFC
ty
(PMatchApp fc n)
(PRef fc [] (sMN 0 "match"))
ist <- get
put (ist { lastParse = Just n })
return $ PClause fc n capp [] r wheres
<|> do (l, op, nfc) <- try (do
pushIndent
l <- argExpr syn
(op, nfc) <- operatorFC
when (op == "=" || op == "?=" ) $
fail "infix clause definition with \"=\" and \"?=\" not supported "
return (l, op, nfc))
let n = expandNS syn (sUN op)
r <- argExpr syn
fc <- getFC
wargs <- many (wExpr syn)
(do rs <- rhs syn n
let wsyn = syn { syn_namespace = [] }
(wheres, nmap) <- choice [do x <- whereBlock n wsyn
popIndent
return x,
do terminator
return ([], [])]
ist <- get
let capp = PApp fc (PRef nfc [nfc] n) [pexp l, pexp r]
put (ist { lastParse = Just n })
return $ PClause fc n capp wargs rs wheres) <|> (do
popIndent
reservedHL "with"
wval <- bracketed syn
pn <- optProof
openBlock
ds <- some $ fnDecl syn
closeBlock
ist <- get
let capp = PApp fc (PRef fc [] n) [pexp l, pexp r]
let withs = map (fillLHSD n capp wargs) $ concat ds
put (ist { lastParse = Just n })
return $ PWith fc n capp wargs wval pn withs)
<|> do pushIndent
(n_in, nfc) <- fnName; let n = expandNS syn n_in
fc <- getFC
args <- many (try (implicitArg (syn { inPattern = True } ))
<|> try (constraintArg (syn { inPattern = True }))
<|> (fmap pexp (argExpr syn)))
wargs <- many (wExpr syn)
let capp = PApp fc (PRef nfc [nfc] n) args
(do r <- rhs syn n
ist <- get
let ctxt = tt_ctxt ist
let wsyn = syn { syn_namespace = [] }
(wheres, nmap) <- choice [do x <- whereBlock n wsyn
popIndent
return x,
do terminator
return ([], [])]
ist <- get
put (ist { lastParse = Just n })
return $ PClause fc n capp wargs r wheres) <|> (do
reservedHL "with"
ist <- get
put (ist { lastParse = Just n })
wval <- bracketed syn
pn <- optProof
openBlock
ds <- some $ fnDecl syn
let withs = map (fillLHSD n capp wargs) $ concat ds
closeBlock
popIndent
return $ PWith fc n capp wargs wval pn withs)
<?> "function clause"
where
optProof = option Nothing (do reservedHL "proof"
n <- fnName
return (Just n))
fillLHS :: Name -> PTerm -> [PTerm] -> PClause -> PClause
fillLHS n capp owargs (PClauseR fc wargs v ws)
= PClause fc n capp (owargs ++ wargs) v ws
fillLHS n capp owargs (PWithR fc wargs v pn ws)
= PWith fc n capp (owargs ++ wargs) v pn
(map (fillLHSD n capp (owargs ++ wargs)) ws)
fillLHS _ _ _ c = c
fillLHSD :: Name -> PTerm -> [PTerm] -> PDecl -> PDecl
fillLHSD n c a (PClauses fc o fn cs) = PClauses fc o fn (map (fillLHS n c a) cs)
fillLHSD n c a x = x
{-| Parses with pattern
@
WExpr ::= '|' Expr';
@
-}
wExpr :: SyntaxInfo -> IdrisParser PTerm
wExpr syn = do lchar '|'
expr' (syn { inPattern = True })
<?> "with pattern"
{-| Parses a where block
@
WhereBlock ::= 'where' OpenBlock Decl+ CloseBlock;
@
-}
whereBlock :: Name -> SyntaxInfo -> IdrisParser ([PDecl], [(Name, Name)])
whereBlock n syn
= do reservedHL "where"
ds <- indentedBlock1 (decl syn)
let dns = concatMap (concatMap declared) ds
return (concat ds, map (\x -> (x, decoration syn x)) dns)
<?> "where block"
{-|Parses a code generation target language name
@
Codegen ::= 'C'
| 'Java'
| 'JavaScript'
| 'Node'
| 'LLVM'
| 'Bytecode'
;
@
-}
codegen_ :: IdrisParser Codegen
codegen_ = do n <- fst <$> identifier
return (Via IBCFormat (map toLower n))
<|> do reserved "Bytecode"; return Bytecode
<?> "code generation language"
{-|Parses a compiler directive
@
StringList ::=
String
| String ',' StringList
;
@
@
Directive ::= '%' Directive';
@
@
Directive' ::= 'lib' CodeGen String_t
| 'link' CodeGen String_t
| 'flag' CodeGen String_t
| 'include' CodeGen String_t
| 'hide' Name
| 'freeze' Name
| 'thaw' Name
| 'access' Accessibility
| 'default' Totality
| 'logging' Natural
| 'dynamic' StringList
| 'name' Name NameList
| 'error_handlers' Name NameList
| 'language' 'TypeProviders'
| 'language' 'ErrorReflection'
| 'deprecated' Name String
| 'fragile' Name Reason
;
@
-}
directive :: SyntaxInfo -> IdrisParser [PDecl]
directive syn = do try (lchar '%' *> reserved "lib")
cgn <- codegen_
lib <- fmap fst stringLiteral
return [PDirective (DLib cgn lib)]
<|> do try (lchar '%' *> reserved "link")
cgn <- codegen_; obj <- fst <$> stringLiteral
return [PDirective (DLink cgn obj)]
<|> do try (lchar '%' *> reserved "flag")
cgn <- codegen_; flag <- fst <$> stringLiteral
return [PDirective (DFlag cgn flag)]
<|> do try (lchar '%' *> reserved "include")
cgn <- codegen_
hdr <- fst <$> stringLiteral
return [PDirective (DInclude cgn hdr)]
<|> do try (lchar '%' *> reserved "hide"); n <- fst <$> fnName
return [PDirective (DHide n)]
<|> do try (lchar '%' *> reserved "freeze"); n <- fst <$> iName []
return [PDirective (DFreeze n)]
<|> do try (lchar '%' *> reserved "thaw"); n <- fst <$> iName []
return [PDirective (DThaw n)]
-- injectivity assertins are intended for debugging purposes
-- only, and won't be documented/could be removed at any point
<|> do try (lchar '%' *> reserved "assert_injective"); n <- fst <$> fnName
return [PDirective (DInjective n)]
-- Assert totality of something after definition. This is
-- here as a debugging aid, so commented out...
-- <|> do try (lchar '%' *> reserved "assert_set_total"); n <- fst <$> fnName
-- return [PDirective (DSetTotal n)]
<|> do try (lchar '%' *> reserved "access")
acc <- accessibility
ist <- get
put ist { default_access = acc }
return [PDirective (DAccess acc)]
<|> do try (lchar '%' *> reserved "default"); tot <- totality
i <- get
put (i { default_total = tot } )
return [PDirective (DDefault tot)]
<|> do try (lchar '%' *> reserved "logging")
i <- fst <$> natural
return [PDirective (DLogging i)]
<|> do try (lchar '%' *> reserved "dynamic")
libs <- sepBy1 (fmap fst stringLiteral) (lchar ',')
return [PDirective (DDynamicLibs libs)]
<|> do try (lchar '%' *> reserved "name")
(ty, tyFC) <- fnName
ns <- sepBy1 name (lchar ',')
return [PDirective (DNameHint ty tyFC ns)]
<|> do try (lchar '%' *> reserved "error_handlers")
(fn, nfc) <- fnName
(arg, afc) <- fnName
ns <- sepBy1 name (lchar ',')
return [PDirective (DErrorHandlers fn nfc arg afc ns) ]
<|> do try (lchar '%' *> reserved "language"); ext <- pLangExt;
return [PDirective (DLanguage ext)]
<|> do try (lchar '%' *> reserved "deprecate")
n <- fst <$> fnName
alt <- option "" (fst <$> stringLiteral)
return [PDirective (DDeprecate n alt)]
<|> do try (lchar '%' *> reserved "fragile")
n <- fst <$> fnName
alt <- option "" (fst <$> stringLiteral)
return [PDirective (DFragile n alt)]
<|> do fc <- getFC
try (lchar '%' *> reserved "used")
fn <- fst <$> fnName
arg <- fst <$> iName []
return [PDirective (DUsed fc fn arg)]
<|> do try (lchar '%' *> reserved "auto_implicits")
b <- on_off
return [PDirective (DAutoImplicits b)]
<?> "directive"
where on_off = do reserved "on"; return True
<|> do reserved "off"; return False
pLangExt :: IdrisParser LanguageExt
pLangExt = (reserved "TypeProviders" >> return TypeProviders)
<|> (reserved "ErrorReflection" >> return ErrorReflection)
<|> (reserved "UniquenessTypes" >> return UniquenessTypes)
<|> (reserved "LinearTypes" >> return LinearTypes)
<|> (reserved "DSLNotation" >> return DSLNotation)
<|> (reserved "ElabReflection" >> return ElabReflection)
<|> (reserved "FirstClassReflection" >> return FCReflection)
{-| Parses a totality
@
Totality ::= 'partial' | 'total' | 'covering'
@
-}
totality :: IdrisParser DefaultTotality
totality
= do reservedHL "total"; return DefaultCheckingTotal
<|> do reservedHL "partial"; return DefaultCheckingPartial
<|> do reservedHL "covering"; return DefaultCheckingCovering
{-| Parses a type provider
@
Provider ::= DocComment_t? '%' 'provide' Provider_What? '(' FnName TypeSig ')' 'with' Expr;
ProviderWhat ::= 'proof' | 'term' | 'type' | 'postulate'
@
-}
provider :: SyntaxInfo -> IdrisParser [PDecl]
provider syn = do doc <- try (do (doc, _) <- docstring syn
fc1 <- getFC
lchar '%'
fc2 <- reservedFC "provide"
highlightP (spanFC fc1 fc2) AnnKeyword
return doc)
provideTerm doc <|> providePostulate doc
<?> "type provider"
where provideTerm doc =
do lchar '('; (n, nfc) <- fnName; lchar ':'; t <- typeExpr syn; lchar ')'
fc <- getFC
reservedHL "with"
e <- expr syn <?> "provider expression"
return [PProvider doc syn fc nfc (ProvTerm t e) n]
providePostulate doc =
do reservedHL "postulate"
(n, nfc) <- fnName
fc <- getFC
reservedHL "with"
e <- expr syn <?> "provider expression"
return [PProvider doc syn fc nfc (ProvPostulate e) n]
{-| Parses a transform
@
Transform ::= '%' 'transform' Expr '==>' Expr
@
-}
transform :: SyntaxInfo -> IdrisParser [PDecl]
transform syn = do try (lchar '%' *> reserved "transform")
-- leave it unchecked, until we work out what this should
-- actually mean...
-- safety <- option True (do reserved "unsafe"
-- return False)
l <- expr syn
fc <- getFC
symbol "==>"
r <- expr syn
return [PTransform fc False l r]
<?> "transform"
{-| Parses a top-level reflected elaborator script
@
RunElabDecl ::= '%' 'runElab' Expr
@
-}
runElabDecl :: SyntaxInfo -> IdrisParser PDecl
runElabDecl syn =
do kwFC <- try (do fc <- getFC
lchar '%'
fc' <- reservedFC "runElab"
return (spanFC fc fc'))
script <- expr syn <?> "elaborator script"
highlightP kwFC AnnKeyword
return $ PRunElabDecl kwFC script (syn_namespace syn)
<?> "top-level elaborator script"
{- * Loading and parsing -}
{-| Parses an expression from input -}
parseExpr :: IState -> String -> Result PTerm
parseExpr st = runparser (fullExpr defaultSyntax) st "(input)"
{-| Parses a constant form input -}
parseConst :: IState -> String -> Result Const
parseConst st = runparser (fmap fst constant) st "(input)"
{-| Parses a tactic from input -}
parseTactic :: IState -> String -> Result PTactic
parseTactic st = runparser (fullTactic defaultSyntax) st "(input)"
{-| Parses a do-step from input (used in the elab shell) -}
parseElabShellStep :: IState -> String -> Result (Either ElabShellCmd PDo)
parseElabShellStep ist = runparser (fmap Right (do_ defaultSyntax) <|> fmap Left elabShellCmd) ist "(input)"
where elabShellCmd = char ':' >>
(reserved "qed" >> pure EQED ) <|>
(reserved "abandon" >> pure EAbandon ) <|>
(reserved "undo" >> pure EUndo ) <|>
(reserved "state" >> pure EProofState) <|>
(reserved "term" >> pure EProofTerm ) <|>
(expressionTactic ["e", "eval"] EEval ) <|>
(expressionTactic ["t", "type"] ECheck) <|>
(expressionTactic ["search"] ESearch ) <|>
(do reserved "doc"
doc <- (Right . fst <$> constant) <|> (Left . fst <$> fnName)
eof
return (EDocStr doc))
<?> "elab command"
expressionTactic cmds tactic =
do asum (map reserved cmds)
t <- spaced (expr defaultSyntax)
i <- get
return $ tactic (desugar defaultSyntax i t)
spaced parser = indentPropHolds gtProp *> parser
-- | Parse module header and imports
parseImports :: FilePath -> String -> Idris (Maybe (Docstring ()), [String], [ImportInfo], Maybe Delta)
parseImports fname input
= do i <- getIState
case parseString (runInnerParser (evalStateT imports i)) (Directed (UTF8.fromString fname) 0 0 0 0) input of
Failure (ErrInfo err _) -> fail (show err)
Success (x, annots, i) ->
do putIState i
fname' <- runIO $ Dir.makeAbsolute fname
sendHighlighting $ addPath annots fname'
return x
where imports :: IdrisParser ((Maybe (Docstring ()), [String],
[ImportInfo],
Maybe Delta),
[(FC, OutputAnnotation)], IState)
imports = do optional shebang
whiteSpace
(mdoc, mname, annots) <- moduleHeader
ps_exp <- many import_
mrk <- mark
isEof <- lookAheadMatches eof
let mrk' = if isEof
then Nothing
else Just mrk
i <- get
-- add Builtins and Prelude, unless options say
-- not to
let ps = ps_exp -- imp "Builtins" : imp "Prelude" : ps_exp
return ((mdoc, mname, ps, mrk'), annots, i)
imp m = ImportInfo False (toPath m)
Nothing [] NoFC NoFC
ns = Spl.splitOn "."
toPath = foldl1' (</>) . ns
addPath :: [(FC, OutputAnnotation)] -> FilePath -> [(FC, OutputAnnotation)]
addPath [] _ = []
addPath ((fc, AnnNamespace ns Nothing) : annots) path =
(fc, AnnNamespace ns (Just path)) : addPath annots path
addPath (annot:annots) path = annot : addPath annots path
shebang :: IdrisParser ()
shebang = string "#!" *> many (satisfy $ not . isEol) *> eol *> pure ()
-- | There should be a better way of doing this...
findFC :: Doc -> (FC, String)
findFC x = let s = show (plain x) in findFC' s
where findFC' s = case span (/= ':') s of
-- Horrid kludge to prevent crashes on Windows
(prefix, ':':'\\':rest) ->
case findFC' rest of
(NoFC, msg) -> (NoFC, msg)
(FileFC f, msg) -> (FileFC (prefix ++ ":\\" ++ f), msg)
(FC f start end, msg) -> (FC (prefix ++ ":\\" ++ f) start end, msg)
(failname, ':':rest) -> case span isDigit rest of
(line, ':':rest') -> case span isDigit rest' of
(col, ':':msg) -> let pos = (read line, read col) in
(FC failname pos pos, msg)
-- | Check if the coloring matches the options and corrects if necessary
fixColour :: Bool -> ANSI.Doc -> ANSI.Doc
fixColour False doc = ANSI.plain doc
fixColour True doc = doc
-- | A program is a list of declarations, possibly with associated
-- documentation strings.
parseProg :: SyntaxInfo -> FilePath -> String -> Maybe Delta ->
Idris [PDecl]
parseProg syn fname input mrk
= do i <- getIState
case runparser mainProg i fname input of
Failure (ErrInfo doc _) -> do -- FIXME: Get error location from trifecta
-- this can't be the solution!
-- Issue #1575 on the issue tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1575
let (fc, msg) = findFC doc
i <- getIState
case idris_outputmode i of
RawOutput h -> iputStrLn (show $ fixColour (idris_colourRepl i) doc)
IdeMode n h -> iWarn fc (P.text msg)
putIState (i { errSpan = Just fc })
return []
Success (x, i) -> do putIState i
reportParserWarnings
return $ collect x
where mainProg :: IdrisParser ([PDecl], IState)
mainProg = case mrk of
Nothing -> do i <- get; return ([], i)
Just mrk -> do
release mrk
ds <- prog syn
i' <- get
return (ds, i')
{-| Load idris module and show error if something wrong happens -}
loadModule :: FilePath -> IBCPhase -> Idris (Maybe String)
loadModule f phase
= idrisCatch (loadModule' f phase)
(\e -> do setErrSpan (getErrSpan e)
ist <- getIState
iWarn (getErrSpan e) $ pprintErr ist e
return Nothing)
{-| Load idris module -}
loadModule' :: FilePath -> IBCPhase -> Idris (Maybe String)
loadModule' f phase
= do i <- getIState
let file = takeWhile (/= ' ') f
ibcsd <- valIBCSubDir i
ids <- allImportDirs
fp <- findImport ids ibcsd file
if file `elem` imported i
then do logParser 1 $ "Already read " ++ file
return Nothing
else do putIState (i { imported = file : imported i })
case fp of
IDR fn -> loadSource False fn Nothing
LIDR fn -> loadSource True fn Nothing
IBC fn src ->
idrisCatch (loadIBC True phase fn)
(\c -> do logParser 1 $ fn ++ " failed " ++ pshow i c
case src of
IDR sfn -> loadSource False sfn Nothing
LIDR sfn -> loadSource True sfn Nothing)
return $ Just file
{-| Load idris code from file -}
loadFromIFile :: Bool -> IBCPhase -> IFileType -> Maybe Int -> Idris ()
loadFromIFile reexp phase i@(IBC fn src) maxline
= do logParser 1 $ "Skipping " ++ getSrcFile i
idrisCatch (loadIBC reexp phase fn)
(\err -> ierror $ LoadingFailed fn err)
where
getSrcFile (IDR fn) = fn
getSrcFile (LIDR fn) = fn
getSrcFile (IBC f src) = getSrcFile src
loadFromIFile _ _ (IDR fn) maxline = loadSource' False fn maxline
loadFromIFile _ _ (LIDR fn) maxline = loadSource' True fn maxline
{-| Load idris source code and show error if something wrong happens -}
loadSource' :: Bool -> FilePath -> Maybe Int -> Idris ()
loadSource' lidr r maxline
= idrisCatch (loadSource lidr r maxline)
(\e -> do setErrSpan (getErrSpan e)
ist <- getIState
case e of
At f e' -> iWarn f (pprintErr ist e')
_ -> iWarn (getErrSpan e) (pprintErr ist e))
{-| Load Idris source code-}
loadSource :: Bool -> FilePath -> Maybe Int -> Idris ()
loadSource lidr f toline
= do logParser 1 ("Reading " ++ f)
iReport 2 ("Reading " ++ f)
i <- getIState
let def_total = default_total i
file_in <- runIO $ readSource f
file <- if lidr then tclift $ unlit f file_in else return file_in
(mdocs, mname, imports_in, pos) <- parseImports f file
ai <- getAutoImports
let imports = map (\n -> ImportInfo True n Nothing [] NoFC NoFC) ai ++ imports_in
ids <- allImportDirs
ibcsd <- valIBCSubDir i
mapM_ (\(re, f, ns, nfc) ->
do fp <- findImport ids ibcsd f
case fp of
LIDR fn -> ifail $ "No ibc for " ++ f
IDR fn -> ifail $ "No ibc for " ++ f
IBC fn src ->
do loadIBC True IBC_Building fn
let srcFn = case src of
IDR fn -> Just fn
LIDR fn -> Just fn
_ -> Nothing
srcFnAbs <- case srcFn of
Just fn -> fmap Just (runIO $ Dir.makeAbsolute fn)
Nothing -> return Nothing
sendHighlighting [(nfc, AnnNamespace ns srcFnAbs)])
[(re, fn, ns, nfc) | ImportInfo re fn _ ns _ nfc <- imports]
reportParserWarnings
sendParserHighlighting
-- process and check module aliases
let modAliases = M.fromList
[ (prep alias, prep realName)
| ImportInfo { import_reexport = reexport
, import_path = realName
, import_rename = Just (alias, _)
, import_location = fc } <- imports
]
prep = map T.pack . reverse . Spl.splitOn [pathSeparator]
aliasNames = [ (alias, fc)
| ImportInfo { import_rename = Just (alias, _)
, import_location = fc } <- imports
]
histogram = groupBy ((==) `on` fst) . sortBy (comparing fst) $ aliasNames
case map head . filter ((/= 1) . length) $ histogram of
[] -> logParser 3 $ "Module aliases: " ++ show (M.toList modAliases)
(n,fc):_ -> throwError . At fc . Msg $ "import alias not unique: " ++ show n
i <- getIState
putIState (i { default_access = Private, module_aliases = modAliases })
clearIBC -- start a new .ibc file
-- record package info in .ibc
imps <- allImportDirs
mapM_ addIBC (map IBCImportDir imps)
mapM_ (addIBC . IBCImport)
[ (reexport, realName)
| ImportInfo { import_reexport = reexport
, import_path = realName
} <- imports
]
let syntax = defaultSyntax{ syn_namespace = reverse mname,
maxline = toline }
ist <- getIState
-- Save the span from parsing the module header, because
-- an empty program parse might obliterate it.
let oldSpan = idris_parsedSpan ist
ds' <- parseProg syntax f file pos
case (ds', oldSpan) of
([], Just fc) ->
-- If no program elements were parsed, we dind't
-- get a loaded region in the IBC file. That
-- means we need to add it back.
do ist <- getIState
putIState ist { idris_parsedSpan = oldSpan
, ibc_write = IBCParsedRegion fc :
ibc_write ist
}
_ -> return ()
sendParserHighlighting
-- Parsing done, now process declarations
let ds = namespaces mname ds'
logParser 3 (show $ showDecls verbosePPOption ds)
i <- getIState
logLvl 10 (show (toAlist (idris_implicits i)))
logLvl 3 (show (idris_infixes i))
-- Now add all the declarations to the context
iReport 1 $ "Type checking " ++ f
-- we totality check after every Mutual block, so if
-- anything is a single definition, wrap it in a
-- mutual block on its own
elabDecls (toplevelWith f) (map toMutual ds)
i <- getIState
-- simplify every definition do give the totality checker
-- a better chance
mapM_ (\n -> do logLvl 5 $ "Simplifying " ++ show n
ctxt' <-
do ctxt <- getContext
tclift $ simplifyCasedef n [] [] (getErasureInfo i) ctxt
setContext ctxt')
(map snd (idris_totcheck i))
-- build size change graph from simplified definitions
iReport 3 $ "Totality checking " ++ f
logLvl 1 $ "Totality checking " ++ f
i <- getIState
mapM_ buildSCG (idris_totcheck i)
mapM_ checkDeclTotality (idris_totcheck i)
mapM_ verifyTotality (idris_totcheck i)
-- Redo totality check for deferred names
let deftots = idris_defertotcheck i
logLvl 2 $ "Totality checking " ++ show deftots
mapM_ (\x -> do tot <- getTotality x
case tot of
Total _ ->
do let opts = case lookupCtxtExact x (idris_flags i) of
Just os -> os
Nothing -> []
when (AssertTotal `notElem` opts) $
setTotality x Unchecked
_ -> return ()) (map snd deftots)
mapM_ buildSCG deftots
mapM_ checkDeclTotality deftots
logLvl 1 ("Finished " ++ f)
ibcsd <- valIBCSubDir i
logLvl 1 $ "Universe checking " ++ f
iReport 3 $ "Universe checking " ++ f
iucheck
let ibc = ibcPathNoFallback ibcsd f
i <- getIState
addHides (hide_list i)
-- Save module documentation if applicable
i <- getIState
case mdocs of
Nothing -> return ()
Just docs -> addModDoc syntax mname docs
-- Finally, write an ibc and highlights if checking was successful
ok <- noErrors
when ok $
do idrisCatch (do writeIBC f ibc; clearIBC)
(\c -> return ()) -- failure is harmless
hl <- getDumpHighlighting
when hl $
idrisCatch (writeHighlights f)
(const $ return ()) -- failure is harmless
clearHighlights
i <- getIState
putIState (i { default_total = def_total,
hide_list = emptyContext })
return ()
where
namespaces :: [String] -> [PDecl] -> [PDecl]
namespaces [] ds = ds
namespaces (x:xs) ds = [PNamespace x NoFC (namespaces xs ds)]
toMutual :: PDecl -> PDecl
toMutual m@(PMutual _ d) = m
toMutual (PNamespace x fc ds) = PNamespace x fc (map toMutual ds)
toMutual x = let r = PMutual (fileFC "single mutual") [x] in
case x of
PClauses{} -> r
PInterface{} -> r
PData{} -> r
PImplementation{} -> r
_ -> x
addModDoc :: SyntaxInfo -> [String] -> Docstring () -> Idris ()
addModDoc syn mname docs =
do ist <- getIState
docs' <- elabDocTerms (toplevelWith f) (parsedDocs ist)
let modDocs' = addDef docName docs' (idris_moduledocs ist)
putIState ist { idris_moduledocs = modDocs' }
addIBC (IBCModDocs docName)
where
docName = NS modDocName (map T.pack (reverse mname))
parsedDocs ist = annotCode (tryFullExpr syn ist) docs
{-| Adds names to hide list -}
addHides :: Ctxt Accessibility -> Idris ()
addHides xs = do i <- getIState
let defh = default_access i
mapM_ doHide (toAlist xs)
where doHide (n, a) = do setAccessibility n a
addIBC (IBCAccess n a)
| Heather/Idris-dev | src/Idris/Parser.hs | bsd-3-clause | 73,853 | 561 | 26 | 30,496 | 15,918 | 8,532 | 7,386 | 1,275 | 27 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "Network/Sendfile/Types.hs" #-}
module Network.Sendfile.Types where
-- |
-- File range for 'sendfile'.
data FileRange = EntireFile
| PartOfFile {
rangeOffset :: Integer
, rangeLength :: Integer
}
| phischu/fragnix | tests/packages/scotty/Network.Sendfile.Types.hs | bsd-3-clause | 307 | 0 | 8 | 105 | 35 | 24 | 11 | 7 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Rede.SimpleHTTP1Response(exampleHTTP11Response, exampleHTTP20Response, shortResponse) where
import qualified Data.ByteString as B
-- Just to check what a browser thinks about this port
exampleHTTP11Response :: B.ByteString
exampleHTTP11Response = "HTTP/1.1 200 OK\r\n\
\Content-Length: 1418\r\n\
\Keep-Alive: timeout=5, max=100\r\n\
\Content-Type: text/html\r\n\
\\r\n\
\<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\r\n\
\<HTML>\r\n\
\ <HEAD>\r\n\
\ <TITLE> [Haskell-cafe] multiline strings in haskell?\r\n\
\ </TITLE>\r\n\
\ <LINK REL=\"Index\" HREF=\"index.html\" >\r\n\
\ <LINK REL=\"made\" HREF=\"mailto:haskell-cafe%40haskell.org?Subject=%5BHaskell-cafe%5D%20multiline%20strings%20in%20haskell%3F&In-Reply-To=Pine.LNX.4.44.0601121646300.23112-100000%40peano.math.uni-bremen.de\">\r\n\
\ <META NAME=\"robots\" CONTENT=\"index,nofollow\">\r\n\
\ <META http-equiv=\"Content-Type\" content=\"text/html; charset=us-ascii\">\r\n\
\ <LINK REL=\"Previous\" HREF=\"013910.html\">\r\n\
\ <LINK REL=\"Next\" HREF=\"013901.html\">\r\n\
\ </HEAD>\r\n\
\ <BODY BGCOLOR=\"#ffffff\">\r\n\
\ <H1>[Haskell-cafe] multiline strings in haskell?</H1>\r\n\
\ <B>Sebastian Sylvan</B> \r\n\
\ <A HREF=\"mailto:haskell-cafe%40haskell.org?Subject=%5BHaskell-cafe%5D%20multiline%20strings%20in%20haskell%3F&In-Reply-To=Pine.LNX.4.44.0601121646300.23112-100000%40peano.math.uni-bremen.de\"\r\n\
\ TITLE=\"[Haskell-cafe] multiline strings in haskell?\">sebastian.sylvan at gmail.com\r\n\
\ </A><BR>\r\n\
\ <I>Thu Jan 12 11:04:43 EST 2006</I>\r\n\
\ <P><UL>\r\n\
\ <LI>Previous message: <A HREF=\"013910.html\">[Haskell-cafe] multiline strings in haskell?\r\n\
\</A></li>\r\n\
\ <LI>Next message: <A HREF=\"013901.html\">[Haskell-cafe] multiline strings in haskell?\r\n\
\</A></li>\r\n\
\ <LI> <B>Messages sorted by:</B> \r\n\
\ <a href=\"date.html#13911\">[ date ]</a>\r\n\
\ <a href=\"thread.html#13911\">[ thread ]</a>\r\n\
\ <a href=\"subject.html#13911\">[ subject ]</a>\r\n\
\ <a href=\"author.html#13911\">[ author ]</a>\r\n\
\ </LI>\r\n\
\ </UL>\r\n\
\ <HR> \r\n\
\<!--beginarticle-->\r\n\
\<PRE>On 1/12/06, Henning Thielemann <<A HREF=\"http://www.haskell.org/mailman/listinfo/haskell-cafe\">lemming at henning-thielemann.de</A>> wrote:\r\n\
\><i>\r\n\
\</I>><i> On Thu, 12 Jan 2006, Jason Dagit wrote:\r\n\
\</I>><i>\r\n\
\</I>><i> > On Jan 12, 2006, at 1:34 AM, Henning Thielemann wrote:\r\n\
\</I>><i> >\r\n\
\</I>><i> > > On Wed, 11 Jan 2006, Michael Vanier wrote:\r\n\
\</I>><i> > >\r\n\
\</I>><i> > >> Is there any support for multi-line string literals in Haskell? I've\r\n\
\</I>><i> > >> done a web search and come up empty. I'm thinking of using\r\n\
\</I>><i> > >> Haskell to\r\n\
\</I>><i> > >> generate web pages and having multi-line strings would be very\r\n\
\</I>><i> > >> useful.\r\n\
\</I>><i> > >\r\n\
\</I>><i> > > Do you mean\r\n\
\</I>><i> > >\r\n\
\</I>><i> > > unlines ["first line", "second line", "third line"]\r\n\
\</I>><i> >\r\n\
\</I>><i> > The original poster probably meant something like this:\r\n\
\</I>><i> >\r\n\
\</I>><i> > let foo = "This is a\r\n\
\</I>><i> > long string\r\n\
\</I>><i> >\r\n\
\</I>><i> >\r\n\
\</I>><i> > Which does not end until the matching end quote."\r\n\
\</I>><i>\r\n\
\</I>><i> I don't see the need for it, since\r\n\
\</I>><i>\r\n\
\</I>><i> unlines [\r\n\
\</I>><i> "first line",\r\n\
\</I>><i> "second line",\r\n\
\</I>><i> "third line"]\r\n\
\</I>><i>\r\n\
\</I>><i> works as well.\r\n\
\</I>><i>\r\n\
\</I>\r\n\
\Nevertheless Haskell supports multiline strings (although it seems\r\n\
\like a lot of people don't know about it). You escape it using and\r\n\
\then another where the string starts again.\r\n\
\\r\n\
\str = "multi \r\n\
\ \\line" \r\n\
\\r\n\
\Prelude>str\r\n\
\"multiline"\r\n\
\\r\n\
\\r\n\
\/S\r\n\
\\r\n\
\--\r\n\
\Sebastian Sylvan\r\n\
\+46(0)736-818655\r\n\
\UIN: 44640862\r\n\
\</PRE>\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\<!--endarticle-->\r\n\
\ <HR>\r\n\
\ <P><UL>\r\n\
\ <!--threads-->\r\n\
\<a href=\"http://www.haskell.org/mailman/listinfo/haskell-cafe\">More information about the Haskell-Cafe\r\n\
\mailing list</a><br>\r\n\
\</body></html>\r\n\
\\r\n"
exampleHTTP20Response :: B.ByteString
exampleHTTP20Response = "\
\<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//EN\">\r\n\
\<HTML>\r\n\
\ <HEAD>\r\n\
\ <TITLE> [Haskell-cafe] multiline strings in haskell?\r\n\
\ </TITLE>\r\n\
\ <LINK REL=\"Index\" HREF=\"index.html\" >\r\n\
\ <LINK REL=\"made\" HREF=\"mailto:haskell-cafe%40haskell.org?Subject=%5BHaskell-cafe%5D%20multiline%20strings%20in%20haskell%3F&In-Reply-To=Pine.LNX.4.44.0601121646300.23112-100000%40peano.math.uni-bremen.de\">\r\n\
\ <META NAME=\"robots\" CONTENT=\"index,nofollow\">\r\n\
\ <META http-equiv=\"Content-Type\" content=\"text/html; charset=us-ascii\">\r\n\
\ <LINK REL=\"Previous\" HREF=\"013910.html\">\r\n\
\ <LINK REL=\"Next\" HREF=\"013901.html\">\r\n\
\ </HEAD>\r\n\
\ <BODY BGCOLOR=\"#ffffff\">\r\n\
\ <H1>[Haskell-cafe] multiline strings in haskell?</H1>\r\n\
\ <B>Sebastian Sylvan</B> \r\n\
\ <A HREF=\"mailto:haskell-cafe%40haskell.org?Subject=%5BHaskell-cafe%5D%20multiline%20strings%20in%20haskell%3F&In-Reply-To=Pine.LNX.4.44.0601121646300.23112-100000%40peano.math.uni-bremen.de\"\r\n\
\ TITLE=\"[Haskell-cafe] multiline strings in haskell?\">sebastian.sylvan at gmail.com\r\n\
\ </A><BR>\r\n\
\ <I>Thu Jan 12 11:04:43 EST 2006</I>\r\n\
\ <P><UL>\r\n\
\ <LI>Previous message: <A HREF=\"013910.html\">[Haskell-cafe] multiline strings in haskell?\r\n\
\</A></li>\r\n\
\ <LI>Next message: <A HREF=\"013901.html\">[Haskell-cafe] multiline strings in haskell?\r\n\
\</A></li>\r\n\
\ <LI> <B>Messages sorted by:</B> \r\n\
\ <a href=\"date.html#13911\">[ date ]</a>\r\n\
\ <a href=\"thread.html#13911\">[ thread ]</a>\r\n\
\ <a href=\"subject.html#13911\">[ subject ]</a>\r\n\
\ <a href=\"author.html#13911\">[ author ]</a>\r\n\
\ </LI>\r\n\
\ </UL>\r\n\
\ <HR> \r\n\
\<!--beginarticle-->\r\n\
\<PRE>On 1/12/06, Henning Thielemann <<A HREF=\"http://www.haskell.org/mailman/listinfo/haskell-cafe\">lemming at henning-thielemann.de</A>> wrote:\r\n\
\><i>\r\n\
\</I>><i> On Thu, 12 Jan 2006, Jason Dagit wrote:\r\n\
\</I>><i>\r\n\
\</I>><i> > On Jan 12, 2006, at 1:34 AM, Henning Thielemann wrote:\r\n\
\</I>><i> >\r\n\
\</I>><i> > > On Wed, 11 Jan 2006, Michael Vanier wrote:\r\n\
\</I>><i> > >\r\n\
\</I>><i> > >> Is there any support for multi-line string literals in Haskell? I've\r\n\
\</I>><i> > >> done a web search and come up empty. I'm thinking of using\r\n\
\</I>><i> > >> Haskell to\r\n\
\</I>><i> > >> generate web pages and having multi-line strings would be very\r\n\
\</I>><i> > >> useful.\r\n\
\</I>><i> > >\r\n\
\</I>><i> > > Do you mean\r\n\
\</I>><i> > >\r\n\
\</I>><i> > > unlines ["first line", "second line", "third line"]\r\n\
\</I>><i> >\r\n\
\</I>><i> > The original poster probably meant something like this:\r\n\
\</I>><i> >\r\n\
\</I>><i> > let foo = "This is a\r\n\
\</I>><i> > long string\r\n\
\</I>><i> >\r\n\
\</I>><i> >\r\n\
\</I>><i> > Which does not end until the matching end quote."\r\n\
\</I>><i>\r\n\
\</I>><i> I don't see the need for it, since\r\n\
\</I>><i>\r\n\
\</I>><i> unlines [\r\n\
\</I>><i> "first line",\r\n\
\</I>><i> "second line",\r\n\
\</I>><i> "third line"]\r\n\
\</I>><i>\r\n\
\</I>><i> works as well.\r\n\
\</I>><i>\r\n\
\</I>\r\n\
\Nevertheless Haskell supports multiline strings (although it seems\r\n\
\like a lot of people don't know about it). You escape it using and\r\n\
\then another where the string starts again.\r\n\
\\r\n\
\str = "multi \r\n\
\ \\line" \r\n\
\\r\n\
\Prelude>str\r\n\
\"multiline"\r\n\
\\r\n\
\\r\n\
\/S\r\n\
\\r\n\
\--\r\n\
\Sebastian Sylvan\r\n\
\+46(0)736-818655\r\n\
\UIN: 44640862\r\n\
\</PRE>\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\\r\n\
\<!--endarticle-->\r\n\
\ <HR>\r\n\
\ <P><UL>\r\n\
\ <!--threads-->\r\n\
\<a href=\"http://www.haskell.org/mailman/listinfo/haskell-cafe\">More information about the Haskell-Cafe\r\n\
\mailing list</a><br>\r\n\
\</body></html>\r\n\
\\r\n"
shortResponse :: B.ByteString
shortResponse = "<html><head>hello world!</head></html>\
\" | alcidesv/ReH | hs-src/Rede/SimpleHTTP1Response.hs | bsd-3-clause | 9,171 | 0 | 5 | 1,211 | 63 | 40 | 23 | 9 | 1 |
-- |
-- Module : Network.SimpleIRC
-- Copyright : (c) Dominik Picheta 2010
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : Alpha
-- Portability : portable
--
-- Simple and efficient IRC Library
--
module Network.SimpleIRC (
-- * Core
module Network.SimpleIRC.Core
-- * Messages
, module Network.SimpleIRC.Messages
) where
import Network.SimpleIRC.Core
import Network.SimpleIRC.Messages
| edwtjo/SimpleIRC | Network/SimpleIRC.hs | bsd-3-clause | 430 | 0 | 5 | 78 | 47 | 36 | 11 | 5 | 0 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>>Запуск приложений | ZAP-расширения </title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Содержание</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Индекс</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Поиск</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Избранное</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/invoke/src/main/javahelp/org/zaproxy/zap/extension/invoke/resources/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 1,042 | 76 | 55 | 159 | 523 | 261 | 262 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Create new a new project directory populated with a basic working
-- project.
module Stack.New
( new
, NewOpts(..)
, defaultTemplateName
, templateNameArgument
, getTemplates
, TemplateName
, listTemplates)
where
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Trans.Writer.Strict
import Data.Aeson
import Data.Aeson.Types
import qualified Data.ByteString as SB
import qualified Data.ByteString.Lazy as LB
import Data.Conduit
import Data.Foldable (asum)
import qualified Data.HashMap.Strict as HM
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe (fromMaybe)
import Data.Maybe.Extra (mapMaybeM)
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T (lenientDecode)
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as LT
import Data.Time.Calendar
import Data.Time.Clock
import Data.Typeable
import qualified Data.Yaml as Yaml
import Network.HTTP.Download
import Network.HTTP.Simple
import Path
import Path.IO
import Prelude
import Stack.Constants
import Stack.Types.Config
import Stack.Types.PackageName
import Stack.Types.StackT
import Stack.Types.TemplateName
import System.Process.Run
import Text.Hastache
import Text.Hastache.Context
import Text.Printf
import Text.ProjectTemplate
--------------------------------------------------------------------------------
-- Main project creation
-- | Options for creating a new project.
data NewOpts = NewOpts
{ newOptsProjectName :: PackageName
-- ^ Name of the project to create.
, newOptsCreateBare :: Bool
-- ^ Whether to create the project without a directory.
, newOptsTemplate :: Maybe TemplateName
-- ^ Name of the template to use.
, newOptsNonceParams :: Map Text Text
-- ^ Nonce parameters specified just for this invocation.
}
-- | Create a new project with the given options.
new
:: (StackM env m, HasConfig env)
=> NewOpts -> Bool -> m (Path Abs Dir)
new opts forceOverwrite = do
pwd <- getCurrentDir
absDir <- if bare then return pwd
else do relDir <- parseRelDir (packageNameString project)
liftM (pwd </>) (return relDir)
exists <- doesDirExist absDir
configTemplate <- view $ configL.to configDefaultTemplate
let template = fromMaybe defaultTemplateName $ asum [ cliOptionTemplate
, configTemplate
]
if exists && not bare
then throwM (AlreadyExists absDir)
else do
templateText <- loadTemplate template (logUsing absDir template)
files <-
applyTemplate
project
template
(newOptsNonceParams opts)
absDir
templateText
when (not forceOverwrite && bare) $ checkForOverwrite (M.keys files)
writeTemplateFiles files
runTemplateInits absDir
return absDir
where
cliOptionTemplate = newOptsTemplate opts
project = newOptsProjectName opts
bare = newOptsCreateBare opts
logUsing absDir template templateFrom =
let loading = case templateFrom of
LocalTemp -> "Loading local"
RemoteTemp -> "Downloading"
in
$logInfo
(loading <> " template \"" <> templateName template <>
"\" to create project \"" <>
packageNameText project <>
"\" in " <>
if bare then "the current directory"
else T.pack (toFilePath (dirname absDir)) <>
" ...")
data TemplateFrom = LocalTemp | RemoteTemp
-- | Download and read in a template's text content.
loadTemplate
:: forall env m. (StackM env m, HasConfig env)
=> TemplateName -> (TemplateFrom -> m ()) -> m Text
loadTemplate name logIt = do
templateDir <- view $ configL.to templatesDir
case templatePath name of
AbsPath absFile -> logIt LocalTemp >> loadLocalFile absFile
UrlPath s -> do
req <- parseRequest s
let rel = fromMaybe backupUrlRelPath (parseRelFile s)
downloadTemplate req (templateDir </> rel)
RelPath relFile ->
catch
(do f <- loadLocalFile relFile
logIt LocalTemp
return f)
(\(e :: NewException) ->
case relRequest relFile of
Just req -> downloadTemplate req
(templateDir </> relFile)
Nothing -> throwM e
)
where
loadLocalFile :: Path b File -> m Text
loadLocalFile path = do
$logDebug ("Opening local template: \"" <> T.pack (toFilePath path)
<> "\"")
exists <- doesFileExist path
if exists
then liftIO (fmap (T.decodeUtf8With T.lenientDecode) (SB.readFile (toFilePath path)))
else throwM (FailedToLoadTemplate name (toFilePath path))
relRequest :: MonadThrow n => Path Rel File -> n Request
relRequest rel = parseRequest (defaultTemplateUrl <> "/" <> toFilePath rel)
downloadTemplate :: Request -> Path Abs File -> m Text
downloadTemplate req path = do
logIt RemoteTemp
_ <-
catch
(redownload req path)
(throwM . FailedToDownloadTemplate name)
loadLocalFile path
backupUrlRelPath = $(mkRelFile "downloaded.template.file.hsfiles")
-- | Apply and unpack a template into a directory.
applyTemplate
:: (StackM env m, HasConfig env)
=> PackageName
-> TemplateName
-> Map Text Text
-> Path Abs Dir
-> Text
-> m (Map (Path Abs File) LB.ByteString)
applyTemplate project template nonceParams dir templateText = do
config <- view configL
currentYear <- do
now <- liftIO getCurrentTime
(year, _, _) <- return $ toGregorian . utctDay $ now
return $ T.pack . show $ year
let context = M.union (M.union nonceParams extraParams) configParams
where
nameAsVarId = T.replace "-" "_" $ packageNameText project
nameAsModule = T.filter (/= '-') $ T.toTitle $ packageNameText project
extraParams = M.fromList [ ("name", packageNameText project)
, ("name-as-varid", nameAsVarId)
, ("name-as-module", nameAsModule)
, ("year", currentYear) ]
configParams = configTemplateParams config
(applied,missingKeys) <-
runWriterT
(hastacheStr
defaultConfig { muEscapeFunc = id }
templateText
(mkStrContextM (contextFunction context)))
unless (S.null missingKeys)
($logInfo ("\n" <> T.pack (show (MissingParameters project template missingKeys (configUserConfigPath config))) <> "\n"))
files :: Map FilePath LB.ByteString <-
catch (execWriterT $
yield (T.encodeUtf8 (LT.toStrict applied)) $$
unpackTemplate receiveMem id
)
(\(e :: ProjectTemplateException) ->
throwM (InvalidTemplate template (show e)))
when (M.null files) $
throwM (InvalidTemplate template "Template does not contain any files")
let isPkgSpec f = ".cabal" `isSuffixOf` f || f == "package.yaml"
unless (any isPkgSpec . M.keys $ files) $
throwM (InvalidTemplate template "Template does not contain a .cabal \
\or package.yaml file")
liftM
M.fromList
(mapM
(\(fp,bytes) ->
do path <- parseRelFile fp
return (dir </> path, bytes))
(M.toList files))
where
-- | Does a lookup in the context and returns a moustache value,
-- on the side, writes out a set of keys that were requested but
-- not found.
contextFunction
:: Monad m
=> Map Text Text
-> String
-> WriterT (Set String) m (MuType (WriterT (Set String) m))
contextFunction context key =
case M.lookup (T.pack key) context of
Nothing -> do
tell (S.singleton key)
return MuNothing
Just value -> return (MuVariable value)
-- | Check if we're going to overwrite any existing files.
checkForOverwrite :: (MonadIO m, MonadThrow m) => [Path Abs File] -> m ()
checkForOverwrite files = do
overwrites <- filterM doesFileExist files
unless (null overwrites) $ throwM (AttemptedOverwrites overwrites)
-- | Write files to the new project directory.
writeTemplateFiles
:: MonadIO m
=> Map (Path Abs File) LB.ByteString -> m ()
writeTemplateFiles files =
forM_
(M.toList files)
(\(fp,bytes) ->
do ensureDir (parent fp)
liftIO (LB.writeFile (toFilePath fp) bytes))
-- | Run any initialization functions, such as Git.
runTemplateInits
:: (StackM env m, HasConfig env)
=> Path Abs Dir -> m ()
runTemplateInits dir = do
menv <- getMinimalEnvOverride
config <- view configL
case configScmInit config of
Nothing -> return ()
Just Git ->
catch (callProcess $ Cmd (Just dir) "git" menv ["init"])
(\(_ :: ProcessExitedUnsuccessfully) ->
$logInfo "git init failed to run, ignoring ...")
-- | Display the set of templates accompanied with description if available.
listTemplates :: StackM env m => m ()
listTemplates = do
templates <- getTemplates
templateInfo <- getTemplateInfo
if not . M.null $ templateInfo then do
let keySizes = map (T.length . templateName) $ S.toList templates
padWidth = show $ maximum keySizes
outputfmt = "%-" <> padWidth <> "s %s\n"
headerfmt = "%-" <> padWidth <> "s %s\n"
liftIO $ printf headerfmt ("Template"::String) ("Description"::String)
forM_ (S.toList templates) (\x -> do
let name = templateName x
desc = fromMaybe "" $ liftM (mappend "- ") (M.lookup name templateInfo >>= description)
liftIO $ printf outputfmt (T.unpack name) (T.unpack desc))
else mapM_ (liftIO . T.putStrLn . templateName) (S.toList templates)
-- | Get the set of templates.
getTemplates :: StackM env m => m (Set TemplateName)
getTemplates = do
req <- liftM setGithubHeaders (parseUrlThrow defaultTemplatesList)
resp <- catch (httpJSON req) (throwM . FailedToDownloadTemplates)
case getResponseStatusCode resp of
200 -> return $ unTemplateSet $ getResponseBody resp
code -> throwM (BadTemplatesResponse code)
getTemplateInfo :: StackM env m => m (Map Text TemplateInfo)
getTemplateInfo = do
req <- liftM setGithubHeaders (parseUrlThrow defaultTemplateInfoUrl)
resp <- catch (liftM Right $ httpLbs req) (\(ex :: HttpException) -> return . Left $ "Failed to download template info. The HTTP error was: " <> show ex)
case resp >>= is200 of
Left err -> do
liftIO . putStrLn $ err
return M.empty
Right resp' ->
case Yaml.decodeEither (LB.toStrict $ getResponseBody resp') :: Either String Object of
Left err ->
throwM $ BadTemplateInfo err
Right o ->
return (M.mapMaybe (Yaml.parseMaybe Yaml.parseJSON) (M.fromList . HM.toList $ o) :: Map Text TemplateInfo)
where
is200 resp =
case getResponseStatusCode resp of
200 -> return resp
code -> Left $ "Unexpected status code while retrieving templates info: " <> show code
newtype TemplateSet = TemplateSet { unTemplateSet :: Set TemplateName }
instance FromJSON TemplateSet where
parseJSON = fmap TemplateSet . parseTemplateSet
-- | Parser the set of templates from the JSON.
parseTemplateSet :: Value -> Parser (Set TemplateName)
parseTemplateSet a = do
xs <- parseJSON a
fmap S.fromList (mapMaybeM parseTemplate xs)
where
parseTemplate v = do
o <- parseJSON v
name <- o .: "name"
if ".hsfiles" `isSuffixOf` name
then case parseTemplateNameFromString name of
Left{} ->
fail ("Unable to parse template name from " <> name)
Right template -> return (Just template)
else return Nothing
--------------------------------------------------------------------------------
-- Defaults
-- | The default template name you can use if you don't have one.
defaultTemplateName :: TemplateName
defaultTemplateName = $(mkTemplateName "new-template")
-- | Default web root URL to download from.
defaultTemplateUrl :: String
defaultTemplateUrl =
"https://raw.githubusercontent.com/commercialhaskell/stack-templates/master"
-- | Default web URL to get a yaml file containing template metadata.
defaultTemplateInfoUrl :: String
defaultTemplateInfoUrl =
"https://raw.githubusercontent.com/commercialhaskell/stack-templates/master/template-info.yaml"
-- | Default web URL to list the repo contents.
defaultTemplatesList :: String
defaultTemplatesList =
"https://api.github.com/repos/commercialhaskell/stack-templates/contents/"
--------------------------------------------------------------------------------
-- Exceptions
-- | Exception that might occur when making a new project.
data NewException
= FailedToLoadTemplate !TemplateName
!FilePath
| FailedToDownloadTemplate !TemplateName
!DownloadException
| FailedToDownloadTemplates !HttpException
| BadTemplatesResponse !Int
| AlreadyExists !(Path Abs Dir)
| MissingParameters !PackageName !TemplateName !(Set String) !(Path Abs File)
| InvalidTemplate !TemplateName !String
| AttemptedOverwrites [Path Abs File]
| FailedToDownloadTemplateInfo !HttpException
| BadTemplateInfo !String
| BadTemplateInfoResponse !Int
deriving (Typeable)
instance Exception NewException
instance Show NewException where
show (FailedToLoadTemplate name path) =
"Failed to load download template " <> T.unpack (templateName name) <>
" from " <>
path
show (FailedToDownloadTemplate name (RedownloadFailed _ _ resp)) =
case getResponseStatusCode resp of
404 ->
"That template doesn't exist. Run `stack templates' to see a list of available templates."
code ->
"Failed to download template " <> T.unpack (templateName name) <>
": unknown reason, status code was: " <>
show code
show (AlreadyExists path) =
"Directory " <> toFilePath path <> " already exists. Aborting."
show (FailedToDownloadTemplates ex) =
"Failed to download templates. The HTTP error was: " <> show ex
show (BadTemplatesResponse code) =
"Unexpected status code while retrieving templates list: " <> show code
show (MissingParameters name template missingKeys userConfigPath) =
intercalate
"\n"
[ "The following parameters were needed by the template but not provided: " <>
intercalate ", " (S.toList missingKeys)
, "You can provide them in " <>
toFilePath userConfigPath <>
", like this:"
, "templates:"
, " params:"
, intercalate
"\n"
(map
(\key ->
" " <> key <> ": value")
(S.toList missingKeys))
, "Or you can pass each one as parameters like this:"
, "stack new " <> packageNameString name <> " " <>
T.unpack (templateName template) <>
" " <>
unwords
(map
(\key ->
"-p \"" <> key <> ":value\"")
(S.toList missingKeys))]
show (InvalidTemplate name why) =
"The template \"" <> T.unpack (templateName name) <>
"\" is invalid and could not be used. " <>
"The error was: \"" <> why <> "\""
show (AttemptedOverwrites fps) =
"The template would create the following files, but they already exist:\n" <>
unlines (map ((" " ++) . toFilePath) fps) <>
"Use --force to ignore this, and overwite these files."
show (FailedToDownloadTemplateInfo ex) =
"Failed to download templates info. The HTTP error was: " <> show ex
show (BadTemplateInfo err) =
"Template info couldn't be parsed: " <> err
show (BadTemplateInfoResponse code) =
"Unexpected status code while retrieving templates info: " <> show code
| Fuuzetsu/stack | src/Stack/New.hs | bsd-3-clause | 17,703 | 0 | 23 | 5,484 | 4,041 | 2,046 | 1,995 | 404 | 5 |
{-# LANGUAGE PolyKinds, GADTs #-}
module T17541b where
import Data.Kind
data T k :: k -> Type where
MkT1 :: T Type Int
MkT2 :: T (Type -> Type) Maybe
| sdiehl/ghc | testsuite/tests/dependent/should_fail/T17541b.hs | bsd-3-clause | 161 | 0 | 8 | 41 | 49 | 29 | 20 | -1 | -1 |
{-# LANGUAGE UndecidableInstances #-}
module LargeNumberTest where
import Data.Word
import Init
share [mkPersist sqlSettings { mpsGeneric = True }, mkMigrate "numberMigrate"] [persistLowerCase|
Number
intx Int
int32 Int32
word32 Word32
int64 Int64
word64 Word64
deriving Show Eq
|]
cleanDB
:: Runner backend m => ReaderT backend m ()
cleanDB = do
deleteWhere ([] :: [Filter (NumberGeneric backend)])
specsWith :: Runner backend m => RunDb backend m -> Spec
specsWith runDb = describe "Large Numbers" $ do
it "preserves their values in the database" $ runDb $ do
let go x = do
xid <- insert x
x' <- get xid
liftIO $ x' @?= Just x
go $ Number maxBound 0 0 0 0
go $ Number 0 maxBound 0 0 0
go $ Number 0 0 maxBound 0 0
go $ Number 0 0 0 maxBound 0
go $ Number 0 0 0 0 maxBound
go $ Number minBound 0 0 0 0
go $ Number 0 minBound 0 0 0
go $ Number 0 0 minBound 0 0
go $ Number 0 0 0 minBound 0
go $ Number 0 0 0 0 minBound
| yesodweb/persistent | persistent-test/src/LargeNumberTest.hs | mit | 1,070 | 0 | 17 | 336 | 377 | 177 | 200 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>Directory List v2.3 LC</title>
<maps>
<homeID>directorylistv2_3_lc</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/directorylistv2_3_lc/src/main/javahelp/help_sq_AL/helpset_sq_AL.hs | apache-2.0 | 984 | 83 | 52 | 158 | 397 | 210 | 187 | -1 | -1 |
module SubSubPatternIn1 where
f :: [Int] -> Int
f ((x : (y : ys)))
= case ys of
ys@[] -> x + y
ys@(b_1 : b_2) -> x + y
f ((x : (y : ys))) = x + y
| kmate/HaRe | old/testing/introCase/SubSubPatternIn1AST.hs | bsd-3-clause | 179 | 0 | 10 | 73 | 109 | 61 | 48 | 7 | 2 |
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings, TupleSections, ViewPatterns #-}
import Yesod.Routes.TH
import Yesod.Routes.Parse
import THHelper
import Language.Haskell.TH.Syntax
import Criterion.Main
import Data.Text (words)
import Prelude hiding (words)
import Control.DeepSeq
import Yesod.Routes.TH.Simple
import Test.Hspec
import Control.Monad (forM_, unless)
$(do
let (cons, decs) = mkRouteCons $ map (fmap parseType) resources
clause1 <- mkDispatchClause settings resources
clause2 <- mkSimpleDispatchClause settings resources
return $ concat
[ [FunD (mkName "dispatch1") [clause1]]
, [FunD (mkName "dispatch2") [clause2]]
, decs
, [DataD [] (mkName "Route") [] cons [''Show, ''Eq]]
]
)
instance NFData Route where
rnf HomeR = ()
rnf FooR = ()
rnf (BarR i) = i `seq` ()
rnf BazR = ()
getHomeR :: Maybe Int
getHomeR = Just 1
getFooR :: Maybe Int
getFooR = Just 2
getBarR :: Int -> Maybe Int
getBarR i = Just (i + 3)
getBazR :: Maybe Int
getBazR = Just 4
samples = take 10000 $ cycle
[ words "foo"
, words "foo bar"
, words ""
, words "bar baz"
, words "bar 4"
, words "bar 1234566789"
, words "baz"
, words "baz 4"
, words "something else"
]
dispatch2a = dispatch2 `asTypeOf` dispatch1
main :: IO ()
main = do
forM_ samples $ \sample ->
unless (dispatch1 True (sample, "GET") == dispatch2a True (sample, "GET"))
(error $ show sample)
defaultMain
[ bench "dispatch1" $ nf (map (dispatch1 True . (, "GET"))) samples
, bench "dispatch2" $ nf (map (dispatch2a True . (, "GET"))) samples
, bench "dispatch1a" $ nf (map (dispatch1 True . (, "GET"))) samples
, bench "dispatch2a" $ nf (map (dispatch2a True . (, "GET"))) samples
]
| ygale/yesod | yesod-core/bench/th.hs | mit | 1,836 | 0 | 15 | 456 | 668 | 349 | 319 | 55 | 1 |
module Helper (
module Test.Hspec
, module Control.Applicative
, module Test.Mockery.Directory
) where
import Test.Hspec
import Test.Mockery.Directory
import Control.Applicative
| sol/reserve | test/Helper.hs | mit | 211 | 0 | 5 | 52 | 41 | 27 | 14 | 7 | 0 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.HTMLMapElement (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.HTMLMapElement
#else
module Graphics.UI.Gtk.WebKit.DOM.HTMLMapElement
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.HTMLMapElement
#else
import Graphics.UI.Gtk.WebKit.DOM.HTMLMapElement
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/HTMLMapElement.hs | mit | 455 | 0 | 5 | 39 | 33 | 26 | 7 | 4 | 0 |
module Y2016.M07.D27.Solution where
import Control.Arrow ((&&&))
import Control.Monad (liftM2)
import Data.List (group, sort)
import Data.Maybe (fromJust)
import Data.Set (Set)
import qualified Data.Set as Set
import Y2016.M07.D19.Solution (figure2)
import Y2016.M07.D20.Solution (FigureC, lineSegments)
import Y2016.M07.D22.Solution (graphit)
import Y2016.M07.D26.Solution (extendPath)
-- Now, for the distance function, the question arises: as the crow flies? or
-- only along a path? The latter is harder because it already solves
-- shortestDistancePathing problem. So let's just go with 'as the crow flies.'
distance :: FigureC -> Char -> Char -> Maybe Float
distance fig@(gr, ptInfoF, vertF) start end =
vertF start >>= \v0 -> let ((x1, y1), _, _) = ptInfoF v0 in
vertF end >>= \v1 -> let ((x2, y2), _, _) = ptInfoF v1 in
return (sqrt ((x1 - x2) ^ 2 + (y1 - y2) ^ 2))
{--
*Y2016.M07.D27.Solution> distance fig 'a' 'b'
Just 18.027756
*Y2016.M07.D27.Solution> distance fig 'a' 'j'
Just 15.0
Yay, and yay!
--}
-- Okay, shortest distance. One way to solve this problem is by brute force,
-- another way is by iterative deepening on the distance (maintaining the
-- in-the-running distances as we deepen) and others are from various search
-- survey courses ACO, genetics, etc.
-- let's start with Brute Force (caps), because I always start with that, then
-- always regret starting with that, then improve if necessary:
-- this is the agile approach:
-- 1. Make it work
-- 2. make it right
-- 3. make it fast
-- Let's make it work, first
allPaths :: FigureC -> Char -> Char -> [String]
allPaths fig start =
-- now 'allPaths' is simply the work I did yesterday that accidently discovered
-- all the paths by not stopping at the shortest ones whilst iteratively
-- deepening:
flip (allps fig) (extendPath fig (Set.empty, pure start))
allps :: FigureC -> Char -> [(Set Char, String)] -> [String]
allps fig end vps = case filter ((== end) . head . snd) vps of
[] -> concatMap (allps fig end . extendPath fig) vps
anss -> map (reverse . snd) anss
{--
*Y2016.M07.D27.Solution> let fig = graphit figure2 lineSegments
*Y2016.M07.D27.Solution> let ab = allPaths fig 'a' 'b' ~> ["ab"]
*Y2016.M07.D27.Solution> let ac = allPaths fig 'a' 'c'
*Y2016.M07.D27.Solution> length ac ~> 191
*Y2016.M07.D27.Solution> take 5 ac ~>
["abjfkgc","abjfkhmgc","abjfkhmnc","abjfkhnc","abjfkhtdc"]
--}
-- brute force method: find all distances of all paths, sort by distance,
-- then group-by
shortestDistancePathing :: FigureC -> Char -> Char -> [String]
shortestDistancePathing fig start =
map snd . head . group . sort . map (distances fig &&& id)
. allPaths fig start
distances :: FigureC -> String -> Maybe Float
distances fig [a,b] = distance fig a b
distances fig (a:b:rest) =
liftM2 (+) (distance fig a b) (distances fig (b:rest))
-- So, with shortestDistancePathing defined, find the shortest distance between
-- nodf 'm' and 'a' in the figure from the value of:
{--
*Y2016.M07.D27.Solution> shortestDistancePathing fig 'a' 'c' ~> ["abgc"]
*Y2016.M07.D27.Solution> shortestDistancePathing fig 'm' 'a' ~> ["mkja"]
YAY!
We're a LITTLE bit closer to determining what trigons are (what we lead off
with two weeks ago), now we must determine what points are in a straight line,
shortestDistancePathing helps us.
We'll look at finding straight lines tomorrow.
--}
| geophf/1HaskellADay | exercises/HAD/Y2016/M07/D27/Solution.hs | mit | 3,406 | 0 | 21 | 598 | 651 | 366 | 285 | 31 | 2 |
module Control.Foldl.Extended where
import Control.Foldl (Fold(..))
import qualified Control.Foldl as L
import qualified Data.Map as Map hiding (foldr)
-- | turn a regular fold into a Map.Map fold
keyFold :: (Ord c) => Fold a b -> Fold (c, a) [(c, b)]
keyFold (Fold step begin done) = Fold step' begin' done'
where
step' x (key, a) =
case Map.lookup key x of
Nothing -> Map.insert key (step begin a) x
Just x' -> Map.insert key (step x' a) x
begin' = Map.empty
done' x = Map.toList (Map.map done x)
-- | count instances using a supplied function to generate a key
countMap :: (Ord b) => (a -> b) -> L.Fold a (Map.Map b Int)
countMap key = L.Fold step begin done
where
begin = Map.empty
done = id
step m x = Map.insertWith (+) (key x) 1 m
-- | fold counting number of keys
countK :: (Ord b) => (a -> b) -> Fold a (Map.Map b Int)
countK key = Fold step begin done
where
begin = Map.empty
done = id
step m x = Map.insertWith (+) (key x) 1 m
-- | fold counting number of keys, given a filter
countKF :: (Ord b) => (a -> b) -> (a -> Bool) -> Fold a (Map.Map b Int)
countKF key filt = Fold step begin done
where
begin = Map.empty
done = id
step m x = if filt x
then Map.insertWith (+) (key x) 1 m
else m
-- | first difference
delta :: (Num a) => Fold a (Maybe a)
delta = Fold step (Nothing, Nothing) done
where
step (p', _) p = (Just p, p')
done (Just p1, Just p2) = Just $ p1 - p2
done _ = Nothing
-- | return (geometric first difference)
ret :: Fold Double (Maybe Double)
ret = Fold step (Nothing, Nothing) done
where
step (p', _) p = (Just p, p')
done (Just p1, Just p2) = Just $ (p1 / p2) - 1
done _ = Nothing
-- | lag n
lag :: Int -> Fold a (Maybe a)
lag l = Fold step (0, []) done
where
step (c, h) a
| c > l = (c + 1, tail h ++ [a])
| otherwise = (c + 1, h ++ [a])
done (c, h)
| c > l = Just $ head h
| otherwise = Nothing
-- list folds
count :: Fold a Integer
count = Fold (const . (1 +)) 0 id
-- turn a regular fold into a list one
listify :: Int -> Fold a b -> Fold [a] [b]
listify n (Fold step' begin' done') = Fold stepL beginL doneL
where
stepL = zipWith step'
beginL = replicate n begin'
doneL = map done'
-- | tuple 2 folds
tuplefy :: Fold a b -> Fold c d -> Fold (a, c) (b, d)
tuplefy (Fold step0 begin0 done0) (Fold step1 begin1 done1) = Fold stepL beginL doneL
where
stepL (a0, a1) (x0, x1) = (step0 a0 x0, step1 a1 x1)
beginL = (begin0, begin1)
doneL (x0, x1) = (done0 x0, done1 x1)
| tonyday567/foldl-extended | src/Control/Foldl/Extended.hs | mit | 2,620 | 0 | 12 | 740 | 1,189 | 630 | 559 | 59 | 2 |
module Monoid1 where
import Data.Semigroup
import Test.QuickCheck
import SemiGroupAssociativeLaw
import MonoidLaws
data Trivial = Trivial deriving (Eq, Show)
instance Semigroup Trivial where
_ <> _ = Trivial
instance Monoid Trivial where
mempty = Trivial
mappend = (<>)
instance Arbitrary Trivial where
arbitrary = return Trivial
type TrivialAssoc = Trivial -> Trivial -> Trivial -> Bool
main :: IO ()
main = do
quickCheck (semigroupAssoc :: TrivialAssoc)
quickCheck (monoidLeftIdentity :: Trivial -> Bool)
quickCheck (monoidRightIdentity :: Trivial -> Bool) | NickAger/LearningHaskell | HaskellProgrammingFromFirstPrinciples/Chapter15.hsproj/Monoid1.hs | mit | 595 | 0 | 9 | 114 | 170 | 92 | 78 | 19 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Text.HTML.TagSoup
import Text.HTML.TagSoup.Match
import qualified Data.ByteString as B
import qualified Data.ByteString.UTF8 as UB
import Data.String.Utils (strip)
import Safe
import System.IO (stdin)
import Control.Applicative
main :: IO ()
main = do
content <- readStdin
let tags = parseTags content
let title = getTitle tags
case title of
Just s -> putStrLn s
Nothing -> putStrLn "no title found"
where
getTitle = fmap strip . headDef Nothing . fmap maybeTagText . getTitleBlock . getHeadBlock . getHtmlBlock
getBlock name = takeWhile (not . tagCloseNameLit name) . drop 1 . dropWhile (not . tagOpenNameLit name)
getHtmlBlock = getBlock "html"
getHeadBlock = getBlock "head"
getTitleBlock = getBlock "title"
readStdin :: IO String
readStdin = UB.toString <$> B.hGetContents stdin
| sdroege/snippets.hs | html2.hs | mit | 950 | 8 | 12 | 243 | 259 | 134 | 125 | 24 | 2 |
module Core.Annotation where
import qualified Data.Generics.Fixplate as Fix
import Data.Set (Set)
data Annotation typeId = Annotation
{ freeVars :: Set typeId
}
deriving (Eq, Ord, Show)
type Annotated f id = Fix.Attr (f id) (Annotation id)
| fredun/compiler | src/Core/Annotation.hs | mit | 252 | 0 | 9 | 48 | 86 | 51 | 35 | 7 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Monad (
Monad(..)
, MonadPlus(..)
, (=<<)
, (>=>)
, (<=<)
, forever
, join
, mfilter
, filterM
, mapAndUnzipM
, zipWithM
, zipWithM_
, foldM
, foldM_
, replicateM
, replicateM_
, concatMapM
, guard
, when
, unless
, liftM
, liftM2
, liftM3
, liftM4
, liftM5
, liftM'
, liftM2'
, ap
, (<$!>)
) where
import Data.List (concat)
import Prelude (seq)
#if (__GLASGOW_HASKELL__ >= 710)
import Control.Monad hiding ((<$!>))
#else
import Control.Monad
#endif
concatMapM :: (Monad m) => (a -> m [b]) -> [a] -> m [b]
concatMapM f xs = liftM concat (mapM f xs)
liftM' :: Monad m => (a -> b) -> m a -> m b
liftM' = (<$!>)
{-# INLINE liftM' #-}
liftM2' :: (Monad m) => (a -> b -> c) -> m a -> m b -> m c
liftM2' f a b = do
x <- a
y <- b
let z = f x y
z `seq` return z
{-# INLINE liftM2' #-}
(<$!>) :: Monad m => (a -> b) -> m a -> m b
f <$!> m = do
x <- m
let z = f x
z `seq` return z
{-# INLINE (<$!>) #-}
| ardfard/protolude | src/Monad.hs | mit | 1,066 | 0 | 10 | 304 | 431 | 245 | 186 | 54 | 1 |
{-# htermination delete :: (Eq a, Eq k) => (Either a k) -> [(Either a k)] -> [(Either a k)] #-}
import List
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/List_delete_11.hs | mit | 108 | 0 | 3 | 23 | 5 | 3 | 2 | 1 | 0 |
{-# LANGUAGE BangPatterns, OverloadedStrings #-}
module Network.Wai.Handler.Warp.Buffer (
bufferSize
, allocateBuffer
, freeBuffer
, mallocBS
, newBufferPool
, withBufferPool
, toBlazeBuffer
, copy
, bufferIO
) where
import qualified Data.ByteString as BS
import Data.ByteString.Internal (ByteString(..), memcpy)
import Data.ByteString.Unsafe (unsafeTake, unsafeDrop)
import Data.IORef (newIORef, readIORef, writeIORef)
import qualified Data.Streaming.ByteString.Builder.Buffer as B (Buffer (..))
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc (mallocBytes, free, finalizerFree)
import Foreign.Ptr (castPtr, plusPtr)
import Network.Wai.Handler.Warp.Types
----------------------------------------------------------------
-- | The default size of the write buffer: 16384 (2^14 = 1024 * 16).
-- This is the maximum size of TLS record.
-- This is also the maximum size of HTTP/2 frame payload
-- (excluding frame header).
bufferSize :: BufSize
bufferSize = 16384
-- | Allocating a buffer with malloc().
allocateBuffer :: Int -> IO Buffer
allocateBuffer = mallocBytes
-- | Releasing a buffer with free().
freeBuffer :: Buffer -> IO ()
freeBuffer = free
----------------------------------------------------------------
largeBufferSize :: Int
largeBufferSize = 16384
minBufferSize :: Int
minBufferSize = 2048
newBufferPool :: IO BufferPool
newBufferPool = newIORef BS.empty
mallocBS :: Int -> IO ByteString
mallocBS size = do
ptr <- allocateBuffer size
fptr <- newForeignPtr finalizerFree ptr
return $! PS fptr 0 size
{-# INLINE mallocBS #-}
usefulBuffer :: ByteString -> Bool
usefulBuffer buffer = BS.length buffer >= minBufferSize
{-# INLINE usefulBuffer #-}
getBuffer :: BufferPool -> IO ByteString
getBuffer pool = do
buffer <- readIORef pool
if usefulBuffer buffer then return buffer else mallocBS largeBufferSize
{-# INLINE getBuffer #-}
putBuffer :: BufferPool -> ByteString -> IO ()
putBuffer pool buffer = writeIORef pool buffer
{-# INLINE putBuffer #-}
withForeignBuffer :: ByteString -> ((Buffer, BufSize) -> IO Int) -> IO Int
withForeignBuffer (PS ps s l) f = withForeignPtr ps $ \p -> f (castPtr p `plusPtr` s, l)
{-# INLINE withForeignBuffer #-}
withBufferPool :: BufferPool -> ((Buffer, BufSize) -> IO Int) -> IO ByteString
withBufferPool pool f = do
buffer <- getBuffer pool
consumed <- withForeignBuffer buffer f
putBuffer pool $! unsafeDrop consumed buffer
return $! unsafeTake consumed buffer
{-# INLINE withBufferPool #-}
----------------------------------------------------------------
--
-- Utilities
--
toBlazeBuffer :: Buffer -> BufSize -> IO B.Buffer
toBlazeBuffer ptr size = do
fptr <- newForeignPtr_ ptr
return $ B.Buffer fptr ptr ptr (ptr `plusPtr` size)
-- | Copying the bytestring to the buffer.
-- This function returns the point where the next copy should start.
copy :: Buffer -> ByteString -> IO Buffer
copy !ptr (PS fp o l) = withForeignPtr fp $ \p -> do
memcpy ptr (p `plusPtr` o) (fromIntegral l)
return $! ptr `plusPtr` l
{-# INLINE copy #-}
bufferIO :: Buffer -> Int -> (ByteString -> IO ()) -> IO ()
bufferIO ptr siz io = do
fptr <- newForeignPtr_ ptr
io $ PS fptr 0 siz
| mfine/wai | warp/Network/Wai/Handler/Warp/Buffer.hs | mit | 3,222 | 0 | 11 | 557 | 823 | 445 | 378 | 72 | 2 |
{-# LANGUAGE TemplateHaskell #-}
-- | Tinkering in a scratch buffer
module Scratch where
import Control.Lens
import Control.Monad.Reader
doSthg :: Monad m => (a -> r) -> m a -> m r
doSthg f mv = mv >>= \x -> return $ f x
-- doSthg (1+) (Just 10)
-- > Just 11
-- doSthg (1+) Nothing
-- > Nothing
doStng' :: Monad m => (a -> r) -> m a -> m r
doStng' f mv = do
v <- mv
return $ f v
-- doSthg' (1+) (Just 10)
-- > Just 11
-- doSthg' (1+) Nothing
-- > Nothing
-- doSthg's types looks like fmap (<$>)
-- λ> :t fmap
-- fmap :: Functor f => (a -> b) -> f a -> f b
-- λ> :t (<$>)
-- (<$>) :: Functor f => (a -> b) -> f a -> f b
-- (1+) <$> (Just 10) :: Maybe Int
-- > Just 11
-- > it :: Maybe Int
-- As Maybe monad is a functor, it works.
-- instance Functor Maybe where
-- f (<$>) (Just x) = Just (f x)
-- f (<$>) Nothing = Nothing
-- Functor apply function to a wrapped value and returns the wrapped result.
-- Applicative:: functor apply wrapped function to a wrapped value and return the wrapped result.
-- >>= :: Monad m => m a -> (a -> m b) -> m b
-- data Writer w a = Writer { runWriter :: (a, w) }
-- instance Monad Writer where
-- w >>= f = do
-- let (v1, s1) = runWriter w
-- let (v2, s2) = runWriter $ f v2
-- Writer (v2, s1 ++ s2)
-- data Reader r a = Reader { runReader :: r -> a }
-- instance Monad Reader where
-- m >>= k = Reader \r -> runReader (k (runReader m r)) r
-- Reader monad
hello :: Reader String String
hello = do
name <- ask
return ("hello, " ++ name ++ "!\n")
bye :: Reader String String
bye = do
name <- ask
return ("bye, " ++ name ++ "!\n")
convo :: Reader String String
convo = do
c1 <- hello
c2 <- bye
return $ c1 ++ c2
readerHelloBye :: String -> IO ()
readerHelloBye s = print $ runReader convo s
-- State monad
-- State s a = State { runState :: s -> (a, s) }
-- instance State s where
-- return a = \s -> (a, s)
-- m >>= k = State \s -> let (a, s1) = runState m s
-- in runState (k a) s1
-- Lense
data Point = Point { _x, _y :: Double } deriving Show
data Player = Player { _loc :: Point } deriving Show
data World = World { _player :: Player } deriving Show
-- λ> player1
-- Player {_loc = Point {_x = 0.0, _y = 0.0}}
-- it :: Player
-- λ> ((location . x) `over` (+22)) player1
-- Player {_loc = Point {_x = 22.0, _y = 0.0}}
-- it :: Player
makeLenses ''Point
makeLenses ''Player
makeLenses ''World
-- λ> :t (loc `over`)
-- (loc `over`) :: (Point -> Point) -> Luigi -> Luigi
-- λ> :t ((loc.x) `over`)
-- ((loc.x) `over`) :: (Double -> Double) -> Luigi -> Luigi
-- λ> :t ((loc . x) `over` (+22))
-- ((loc . x) `over` (+22)) :: Luigi -> Luigi
initWorld :: World
initWorld = World $ Player (Point 0 0)
-- λ> :t (initWorld ^. player)
-- (initWorld ^. player) :: Player
-- λ> :t (initWorld ^. (player . loc))
-- (initWorld ^. (player . loc)) :: Point
-- λ> :t (initWorld ^. (player . loc . x))
-- (initWorld ^. (player . loc . x)) :: Double
-- change the world (just change player's coordinates)
movePlayer :: World -> World
movePlayer w = (player.loc.x) `over` (+1) $ w
-- λ> movePlayer initWorld
-- World {_player = Player {_loc = Point {_x = 1.0, _y = 0.0}}}
-- it :: World
-- λ> movePlayer (movePlayer initWorld)
-- World {_player = Player {_loc = Point {_x = 2.0, _y = 0.0}}}
-- it :: World
--main :: IO ()
-- main = readerHelloBye "tony" module Anagram where
import Control.Arrow ((&&&))
import Data.Char (toLower)
import Data.List
import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
import System.Environment
-- ######### Definition type
type Word = String
type Sentence = [Word]
type Occurrences = [(Char, Int)]
-- ######### Production code
wordOccurrences :: Word -> Occurrences
wordOccurrences = map ((&&&) head length) . group . sort . map toLower
sentenceOccurrences :: Sentence -> Occurrences
sentenceOccurrences = wordOccurrences . intercalate ""
combinations :: Occurrences -> [Occurrences]
combinations =
foldl' comb [[]]
where comb :: [Occurrences] -> (Char, Int) -> [Occurrences]
comb ss ci = ss ++ [sub ++ [c] | sub <- ss, c <- subOccurrences ci]
subOccurrences :: (Char, Int) -> Occurrences
subOccurrences (c, n) = [(c, i) | i <- [1..n]]
substract :: Occurrences -> Occurrences -> Occurrences
substract =
foldl' update
where update :: Occurrences -> (Char, Int) -> Occurrences
update [] _ = []
update (x@(cc, nn) : xs) e@(c, n) =
if cc == c
then let ni = nn - n in if ni <= 0 then xs else (c, ni):xs
else x : update xs e
type DicoOcc = Map.Map Occurrences [Word]
dicoByOccurrences :: [String] -> DicoOcc
dicoByOccurrences = foldl' add Map.empty
where add :: DicoOcc -> String -> DicoOcc
add dico word = Map.insertWith iadd occuKey [word] dico
where occuKey :: Occurrences
occuKey = wordOccurrences word
iadd :: Eq a => [a] -> [a] -> [a]
iadd ws (w:_) = if w `elem` ws then ws else w:ws
-- Returns all the anagrams of a given word.
wordAnagrams :: Word -> DicoOcc -> [Word]
wordAnagrams w d =
fromMaybe [] $ (flip Map.lookup d . wordOccurrences) w
extractLines :: FilePath -> IO [String]
extractLines filePath =
do contents <- readFile filePath
return $ lines contents
disp :: Int -> IO [String] -> IO ()
disp n allLines =
do ll <- allLines
let f = take n ll in
mapM_ putStrLn f
-- An anagram of a sentence is formed by taking the occurrences of all the characters of
-- all the words in the sentence, and producing all possible combinations of words with those characters,
-- such that the words have to be from the dictionary.
-- Returns a list of all anagram sentences of the given sentence.
sentenceAnagrams :: Sentence -> DicoOcc -> [Sentence]
sentenceAnagrams s d =
(filteringSentencesOnOccurrence . nub . sentenceCompute . combinations) sentenceOccurrenceRef
where filteringSentencesOnOccurrence :: [Sentence] -> [Sentence]
filteringSentencesOnOccurrence = filter (\x -> sentenceOccurrences x == sentenceOccurrenceRef)
sentenceOccurrenceRef :: Occurrences
sentenceOccurrenceRef = sentenceOccurrences s
sentenceCompute :: [Occurrences] -> [Sentence]
sentenceCompute [] = [[]]
sentenceCompute (o:os) = case Map.lookup o d of
Nothing -> sentenceCompute os
Just anagrams -> [y:ys | y <- anagrams, ys <- sentenceCompute oss] ++ sentenceCompute os
where oss = map (`substract` o) os
dictionaryFromFile :: FilePath -> IO DicoOcc
dictionaryFromFile filepath =
do dicoLines <- extractLines filepath
return $ dicoByOccurrences dicoLines
mainWordAnagrams :: String -> FilePath -> IO ()
mainWordAnagrams word filePath =
do dicoLines <- extractLines filePath
mapM_ putStrLn $ wordAnagrams word (dicoByOccurrences dicoLines)
printSentence :: Sentence -> IO ()
printSentence sentence = putStr "[" >> mapM_ (putStr . (++) " ") sentence >> putStrLn " ]"
mainSentenceAnagrams :: [String] -> FilePath -> IO ()
mainSentenceAnagrams sentence filePath =
do dico <- dictionaryFromFile filePath
mapM_ printSentence $ sentenceAnagrams sentence dico
main :: IO ()
main = do args <- getArgs
mainSentenceAnagrams args "../resources/linuxwords.txt"
| ardumont/haskell-lab | src/Scratch.hs | gpl-2.0 | 7,502 | 0 | 14 | 1,878 | 1,720 | 934 | 786 | -1 | -1 |
module BaseParser where
import Control.Applicative hiding (many)
import Control.Arrow
import Control.Monad
newtype Parser a = Parser { runParser :: String -> [(a,String)] }
instance Functor Parser where
fmap f p = Parser $ \ s -> map (first f) (runParser p s)
instance Applicative Parser where
pure x = Parser $ \ s -> [(x, s)]
p1 <*> p2 = Parser $ \ s ->
[ (f x, s2)
| (f, s1) <- runParser p1 s
, (x, s2) <- runParser p2 s1
]
instance Alternative Parser where
empty = Parser $ const []
p1 <|> p2 = Parser $ \ s -> runParser p1 s ++ runParser p2 s
instance Monad Parser where
return = ret
p1 >>= f = Parser $ concatMap (uncurry (runParser . f)) . runParser p1
instance MonadPlus Parser where
mzero = Parser $ const []
p1 `mplus` p2 = Parser $ \ s -> runParser p1 s ++ runParser p2 s
pass :: Monad m => m a -> m b -> m a
pass x f = x >>= (\ x' -> f >> return x')
(>>:) :: Parser a -> Parser [a] -> Parser [a]
p1 >>: p2 = p1 >>= \ x -> fmap (x:) p2
(>>++) :: Parser [a] -> Parser [a] -> Parser [a]
p1 >>++ p2 = p1 >>= \ x -> fmap (x++) p2
ret :: a -> Parser a
ret x = Parser $ \ s -> [(x,s)]
eof :: Parser ()
eof = Parser f where
f [] = [((),[])]
f _ = []
triv :: Parser ()
triv = return ()
sat :: (Char -> Bool) -> Parser Char
sat p = Parser f where
f [] = []
f (x:s) = if p x then [(x,s)] else []
any :: Parser Char
any = sat $ const True
char :: Char -> Parser Char
char c = sat (c ==)
many :: Parser a -> Parser [a]
many p = return [] `mplus` many1 p
many1 :: Parser a -> Parser [a]
many1 p = p >>= \ x -> fmap (x:) (many p)
boundedMany :: Int -> Parser a -> Parser [a]
boundedMany 0 _ = return []
boundedMany n p = return [] `mplus` boundedMany1 n p
boundedMany1 :: Int -> Parser a -> Parser [a]
boundedMany1 0 _ = return []
boundedMany1 n p = p >>= \ x -> fmap (x:) (boundedMany (n-1) p)
times :: Int -> Parser a -> Parser [a]
times n p = foldr (\ x y -> x >>= \ a -> fmap (a:) y) (return []) $ replicate n p
maybeP :: Parser a -> Parser (Maybe a)
maybeP p = Parser f where
f s = case runParser p s of
[] -> [(Nothing,s)]
t -> fmap (first Just) t
rescue :: a -> Parser a -> Parser a
rescue x p = Parser f where
f s = case runParser p s of
[] -> [(x,s)]
t -> t
string' :: String -> Parser ()
string' = foldr ((>>) . char) triv
string :: String -> Parser String
string s = const s <$> string' s
| xkollar/handy-haskell | irc/BaseParser.hs | gpl-3.0 | 2,446 | 0 | 12 | 674 | 1,322 | 683 | 639 | 70 | 3 |
{-# LANGUAGE TypeFamilies, QuasiQuotes, MultiParamTypeClasses,
TemplateHaskell, OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts, TupleSections #-}
module WJR.Application
where
import WJR.Imports
import Yesod.Static (Static, Route(..), static)
import Text.Hamlet (hamletFile,shamlet)
import qualified Data.Text as T
import Network.Wai
import System.FilePath (splitDirectories)
-- import Network.Wai.Handler.CGI as CGI
import Text.Julius
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import qualified Web.ClientSession as CS
import Network.HTTP.Conduit (Manager,newManager)
import Network.Gravatar as G
import WJR.AdminUsers (adminUser)
import WJR.Settings
import WJR.Jobs
import WJR.ParamDefs
bootstrap_css, bootstrap_js, jquery_js, jfileTree_css, jfileTree_js :: Route Static
bootstrap_css = StaticRoute ["bootstrap.css"] []
bootstrap_js = StaticRoute ["bootstrap-tooltip.js"] []
jquery_js = StaticRoute ["jquery-1.7.2.min.js"] []
jfileTree_css = StaticRoute ["jqueryFileTree","jqueryFileTree.css"] []
jfileTree_js = StaticRoute ["jqueryFileTree","jqueryFileTree.js"] []
data App = App { getStatic :: Static
, httpManager :: Manager
}
mkYesod "App" [parseRoutes|
/ RootR GET
/auth AuthR Auth getAuth
/static StaticR Static getStatic
/about AboutR GET
/queue QueueR GET
/new NewR
/job/#Text JobR GET
/job-delete/#Text JobDeleteR GET
/job-output/#Text JobOutputR GET
/job-files/#Text/*Texts JobFilesAjaxR POST GET
/all-jobs AllJobsR GET
|]
-- | Authorization for the various routes. TODO, use this to authorize access to jobs?
routeAuthorized r _write
| okRoutes r = return Authorized
| loggedInRoutes r = loggedIn
| adminRoutes r = isAdmin
| otherwise = return $ Unauthorized "Not allowed"
where
okRoutes RootR = True
okRoutes (AuthR _) = True
okRoutes (StaticR _) = True
okRoutes NewR = True
okRoutes (JobR _) = True
okRoutes (JobDeleteR _) = True
okRoutes (JobOutputR _) = True
okRoutes (JobFilesAjaxR _ _) = True
okRoutes AboutR = True
okRoutes _ = False
loggedInRoutes QueueR = True
loggedInRoutes _ = False
adminRoutes AllJobsR = True
adminRoutes _ = False
loggedIn = do user <- maybeAuthId
return $ case user of
Nothing -> AuthenticationRequired
Just _ -> Authorized
isAdmin = do mUser <- maybeAuthId
return $ case mUser of
Nothing -> AuthenticationRequired
Just user -> if adminUser user then Authorized else undefined Unauthorized "Admin only"
instance Yesod App where
approot = ApprootStatic $ T.pack approotSetting
authRoute _ = Just $ AuthR LoginR
isAuthorized = routeAuthorized
-- | Create the session backend. Overriden here to increase session timeout to 2 weeks
makeSessionBackend _ = do
key <- CS.getKey CS.defaultKeyFile
return $ Just $ clientSessionBackend key (14 * 24 * 60)
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
addStylesheet $ StaticR bootstrap_css
addScript $ StaticR jquery_js
addScript $ StaticR bootstrap_js
$(widgetFile "default-layout")
authId <- maybeAuthId
let mGravatar = authId >>= return . G.gravatar defGravatar
let isAdmin = maybe False adminUser authId
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
-- Allow big uploads for new jobs : TODO, more efficient upload handling : http://stackoverflow.com/questions/10880105/efficient-large-file-upload-with-yesod
maximumContentLength _ (Just NewR) = 2 * 1024 * 1024 * 1024 -- 2 gigabytes
maximumContentLength _ _ = 2 * 1024 * 1024 -- 2 megabytes
defGravatar :: GravatarOptions
defGravatar = G.defaultConfig { gSize = Just $ Size 30
, gDefault = Just MM
}
instance YesodAuth App where
type AuthId App = Text
getAuthId = return . Just . credsIdent
loginDest _ = QueueR
logoutDest _ = RootR
authPlugins _ = [authBrowserId, authGoogleEmail]
authHttpManager = httpManager
loginHandler = defaultLayout $ do
tm <- lift getRouteToMaster
let browserId = apLogin authBrowserId tm
googleEmail = apLogin authGoogleEmail tm
$(widgetFile "login")
-- | What to show on the login page.
-- loginHandler :: GHandler Auth m RepHtml
-- loginHandler = defaultLayout $ do
-- tm <- lift getRouteToMaster
-- master <- lift getYesod
-- mapM_ (flip apLogin tm) (authPlugins master)
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
defaultMain :: IO ()
defaultMain = do
st <- static "static"
man <- newManager def
let app = App st man
runWarp (fromIntegral listenPort) app
-- toWaiApp app >>= run
----------------------------------------------------------------------
-- | Convert a "Field" that uses a Bool, to use a Text yes/no instead
-- fieldBoolToText :: RenderMessage m FormMessage => Field s m Bool -> Field s m Text
fieldBoolToText :: Field sub master Bool -> Field sub master Text
fieldBoolToText fld = fld {fieldParse=parser', fieldView=viewer' }
where
showB True = "yes"
showB False = "no"
readB "yes" = True
readB _ = False
parser = fieldParse fld
viewer = fieldView fld
parser' x y = do r <- parser x y
return $ case r of
Right (Just b) -> Right . Just . showB $ b
Right Nothing -> Right Nothing
Left m -> Left m
viewer' id name attrs valOrErr req =
let toB = case valOrErr of {Left x -> Left x; Right b -> Right (readB b)}
in viewer id name attrs toB req
data ParamForm = ParamForm { fileInfo :: FileInfo
, paramMap :: Map Text Text
}
-- Params for the jobs. TODO - separate this out (how?)
paramsForm :: Html -> MForm App App (FormResult ParamForm, Widget)
paramsForm fragment = do
(fileR, fileV) <- aFormToForm $ fileAFormReq $
FieldSettings "Contigs file (FastA): "
(Just "FastA file containing your contigs to annotate")
Nothing (Just "contigs") [("required","")]
-- results :: [(Text, FormResult Text)]
-- views :: [FieldView]
(results, paramViews) <- unzip <$> sequenceA (map fs paramDefs)
let views = fileV paramViews
let widget = $(widgetFile "param-form")
let resMap = fromList . mapMaybe maybeSnd <$> sequenceA (map pairA results)
let retParamForm = ParamForm <$> fileR <*> resMap
return (retParamForm, widget)
where
pairA (a,b) = (\x -> (a,x)) <$> b
maybeSnd :: (a, Maybe b) -> Maybe (a,b)
maybeSnd (x,Just y) = Just (x,y)
maybeSnd _ = Nothing
-- fs :: ParamField -> MForm s m ((Text,FormResult Text), FieldView s m)
fs (ParamField name label tip fld def _) =
let s = FieldSettings (fromString label) (Just $ fromString tip) Nothing (Just name) []
in do (r,v) <- mopt (paramFieldToField fld) s (Just def)
return ((name,r), v)
paramFieldToField TextField = textField
paramFieldToField CheckBoxField = fieldBoolToText checkBoxField
paramFieldToField (ListField pairs) = selectFieldList pairs
----------------------------------------------------------------------
myJobs :: Handler [Job]
myJobs = do
maid <- maybeAuthId
case maid of
Nothing -> return []
Just uid -> liftIO $ jobsForUser uid
getRootR :: Handler RepHtml
getRootR = defaultLayout $(widgetFile "home")
getAboutR :: Handler RepHtml
getAboutR = defaultLayout $(widgetFile "about")
getQueueR :: Handler RepHtml
getQueueR = do
jobs <- myJobs
defaultLayout $(widgetFile "queue")
getAllJobsR :: Handler RepHtml
getAllJobsR = do
jobs <- liftIO $ allJobs
defaultLayout $(widgetFile "all-queue")
-- checkAccess :: Maybe Job -> App
checkAccess Nothing = notFound >> return Nothing
checkAccess (Just job)
| isNullUserID (jobUser job) = return $ Just job -- Job submitted by anonymous user, only need the jobId to access it
| otherwise = do
maid <- maybeAuthId
case maid of
Nothing -> -- User not logged in, and already checked it is a non-anonymous job
notFound >> return Nothing
Just user -> if adminUser user || user == jobUser job
then return $ Just job
else notFound >> return Nothing
jobStatusText :: Job -> Text
jobStatusText job = case jobStatus job of
JobWaiting -> "Waiting"
JobRunning _ -> "Running..."
JobComplete JobSuccess -> "Finished"
JobComplete JobFailure -> "FAILED"
getJobR :: JobID -> Handler RepHtml
getJobR jobId = do
mAuthId <- maybeAuthId
job <- liftIO $ infoJob jobId
checkAccess job
case job of
Nothing -> notFound
Just job -> let params = toList $ jobParams job
status = jobStatusText job
isAdmin = maybe False adminUser mAuthId
finished = case jobStatus job of { JobComplete _ -> True; _ -> False}
jsPoll = rawJS (if finished then "false" else "true" :: String)
in defaultLayout $(widgetFile "job")
getJobDeleteR :: JobID -> Handler RepHtml
getJobDeleteR jobId = do
job <- liftIO $ infoJob jobId
checkAccess job
liftIO $ deleteJob jobId
setMessage $ msgLabel "Job Deleted"
maid <- maybeAuthId
if isNothing maid
then redirect RootR
else redirect QueueR
msgLabel :: Text -> Html
msgLabel msg = [shamlet|<div class="alert alert-success">#{msg}|]
requestIP :: Handler Text
requestIP = fmap (fromString . show . remoteHost . reqWaiRequest) getRequest
handleNewR :: Handler RepHtml
handleNewR = do
maid <- maybeAuthId
((result, widget), enctype) <- runFormPost paramsForm
case result of
FormSuccess params -> do ip <- requestIP
job <- liftIO $ createJob maid ip (paramMap params) (fileInfo params)
setMessage $ msgLabel "Job created."
redirect $ JobR (jobId job)
_ -> defaultLayout $(widgetFile "new-job")
----------------------------------------------------------------------
-- Output file handling
jobOutputLink, jobOutputZippedLink :: JobID -> Route App
jobOutputLink jobId = JobOutputR $ jobId
jobOutputZippedLink jobId = JobOutputR $ T.append jobId ".zip"
getJobOutputR :: Text -> Handler RepHtml
getJobOutputR pJobId
| ".zip" `T.isSuffixOf` pJobId = let Just jobId = T.stripSuffix ".zip" pJobId
in do Just job <- checkAccess =<< liftIO (infoJob jobId)
sendZippedOutput job
| otherwise = do
Just job <- checkAccess =<< liftIO (infoJob pJobId)
root <- rawJS <$> firstSubDir
let jobId = pJobId
let empList = [] -- Can't seem to have this in the julius template!
defaultLayout $ fileListWidget >> $(widgetFile "output-browser")
where
sendZippedOutput job = do file <- liftIO $ zippedOutput (jobId job)
sendFile typeOctet file
fileListWidget = do
addStylesheet $ StaticR jfileTree_css
addScript $ StaticR jfileTree_js
firstSubDir = do actual <- liftIO $ getActualFile pJobId ["/"]
let root = "/"
return $ case actual of
Directory files -> case filter fst files of
((True,f):_) -> f
_ -> root
_ -> root
outputFileAccess :: JobID -> [Text] -> Handler ActualFile
outputFileAccess jobId dir = do
checkAccess =<< liftIO (infoJob jobId)
file <- liftIO $ getActualFile jobId dir
return file
getJobFilesAjaxR :: Text -> [Text] -> Handler RepHtml
getJobFilesAjaxR jobId dir = do
file <- outputFileAccess jobId dir
case file of
InvalidPath -> notFound
File filename -> sendFile typePlain filename
Directory _ -> notFound
postJobFilesAjaxR :: Text -> [Text] -> Handler RepHtml
postJobFilesAjaxR jobId _ = do
mDir <- lookupPostParam "dir"
case mDir of
Nothing -> notFound
Just dir -> do file <- outputFileAccess jobId (splitDir dir)
case file of
InvalidPath -> notFound
File filename -> sendFile typePlain filename
Directory filePaths -> let files = map toView filePaths
in hamletToRepHtml $(hamletFile "templates/output-files.hamlet")
where
splitDir dir = map T.pack $ splitDirectories $ T.unpack dir
toView (isDir, path) = let dirs = splitDirectories path
in (isDir, path, last dirs, JobFilesAjaxR jobId (map T.pack dirs))
| drpowell/Prokka-web | WJR/Application.hs | gpl-3.0 | 13,710 | 0 | 20 | 3,994 | 3,400 | 1,683 | 1,717 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Data.Valet.Utils.Reader
Description : Generic class for the "reader".
Copyright : (c) Leonard Monnier, 2015
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Generic 'read' function which can be used for any value.
All you need to ensure is a 'Read' instance for the given value.
The 'String' value will then be converted to the type of the value.
Values can be then defined such as:
> readable :: R.Readable b T.Text => T.Text -> Value r m b T.Text
> readable name = reader R.read $ value name ""
The above example is a 'Text' value for which data can be set from
any 'Readable' instance.
-}
module Data.Valet.Utils.Reader
( Readable
, Data.Valet.Utils.Reader.read
) where
import qualified Data.Text as T
{-|
Class defining a 'read' function.
This read function can then be used for all types being an instance of this
class.
-}
class Readable a b where
read :: a -> b
instance Read b => Readable String b where
read = Prelude.read
instance Read b => Readable T.Text b where
read = Prelude.read . T.unpack
| momomimachli/Valet | src/Data/Valet/Utils/Reader.hs | gpl-3.0 | 1,278 | 0 | 7 | 262 | 111 | 65 | 46 | 14 | 0 |
module Main where
import System.Environment(getArgs)
import Control.Monad
ageStatus :: Integer -> String
ageStatus x
| 0 <= x && x <= 2 = "Home"
| 3 <= x && x <= 4 = "Preschool"
| 5 <= x && x <= 11 = "Elementary school"
| 12 <= x && x <= 14 = "Middle school"
| 15 <= x && x <= 18 = "High school"
| 19 <= x && x <= 22 = "College"
| 23 <= x && x <= 65 = "Work"
| 66 <= x && x <= 100 = "Retirement"
| otherwise = "This program is for humans"
processLine :: String -> String
processLine = ageStatus . read
main :: IO ()
main = liftM head getArgs >>= liftM lines . readFile >>= mapM_ (putStrLn . processLine)
| cryptica/CodeEval | Challenges/152_AgeDistribution/main.hs | gpl-3.0 | 702 | 0 | 10 | 232 | 273 | 135 | 138 | 18 | 1 |
{- `s` stands for `suspension functor` -}
import Control.Monad.Trans
newtype Coroutine s m r = Coroutine { resume :: m (CoroutineState s m r) }
data CoroutineState s m r = Run (s (Coroutine s m r))
| Done r
instance (Functor s, Monad m) => Functor (Coroutine s m) where
fmap f coroutine = Coroutine $ do
cs <- resume coroutine
case cs of
Run s' -> return (Run (fmap (fmap f) s'))
Done r -> return (Done (f r))
instance (Functor s, Monad m) => Applicative (Coroutine s m) where
pure = Coroutine . pure . Done
fcoroutine <*> coroutine = Coroutine $ do
cs <- resume fcoroutine
case cs of
Run s -> return $ Run (fmap (<*> coroutine) s)
Done r -> resume (fmap r coroutine)
instance (Functor s, Monad m) => Monad (Coroutine s m) where
return = pure
coroutine >>= f = Coroutine $ do
cs <- resume coroutine
case cs of
Run s -> return $ Run (fmap (\c -> c >>= f) s)
Done r -> resume (f r)
| KenetJervet/mapensee | haskell/coroutine/02Coroutine.hs | gpl-3.0 | 993 | 0 | 18 | 290 | 434 | 217 | 217 | 24 | 0 |
{-# LANGUAGE TemplateHaskell, StandaloneDeriving #-}
module Framework where
-- * Imports
-------------------------------------------------------------------
import Control.Applicative
import Control.Lens
import Control.Monad
import Data.Foldable (foldMap, traverse_)
import System.FilePath ((</>))
import Data.IORef
import Graphics.GLUtil
import Graphics.GLUtil.Camera2D
import Graphics.UI.GLFW as GLFW
import Graphics.Rendering.OpenGL as GL
import Linear
import Debug.Trace
import qualified Data.Set as Set
-- * Types
-------------------------------------------------------------------
deriving instance Ord MouseButton
data UI = UI
{ _pressedKeys :: Set.Set Key
, _pressedMouseBtns :: Set.Set MouseButton
, _mousePos :: V2 Int
, _windowSize :: V2 Int
, _currentTime :: Double
, _timeStep :: Double
} deriving (Show, Eq)
makeLenses ''UI
-- * Main function
-------------------------------------------------------------------
setupGLFW :: String -> Int -> Int -> IO (IO UI)
setupGLFW title w h = do
GLFW.initialize
-- general OpenGL settings
--GLFW.openWindowHint FSAASamples 4
--GLFW.openWindowHint OpenGLVersionMajor 3
--GLFW.openWindowHint OpenGLVersionMinor 3
--GLFW.openWindowHint OpenGLProfile OpenGLCoreProfile
-- create window
GLFW.openWindow (Size (fromIntegral w) (fromIntegral h)) [DisplayRGBBits 8 8 8] Window
GLFW.windowTitle $= title
GLFW.enableSpecial StickyKey
-- set nice background color
GL.clearColor $= Color4 0.0 0.0 0.0 1.0
-- enable alpha blending
GL.blendFunc $= (SrcAlpha, OneMinusSrcAlpha)
GL.blend $= Enabled
-- event initialisation
keySetIO <- newIORef Set.empty
mouseBtnSetIO <- newIORef Set.empty
mousePosIO <- get GLFW.mousePos >>= newIORef . posToV2
windowSizeIO <- get GLFW.windowSize >>= newIORef . sizeToV2
lastTimeIO <- get time >>= newIORef
GLFW.keyCallback $= onKeyEvent keySetIO
GLFW.mouseButtonCallback $= onMouseBtnEvent mouseBtnSetIO
GLFW.mousePosCallback $= onMouseMove mousePosIO
GLFW.windowSizeCallback $= onWindowResize windowSizeIO
-- run main loop
let
updateUIState = do
curTime <- get time
lastTime <- readIORef lastTimeIO
writeIORef lastTimeIO curTime
UI <$> readIORef keySetIO
<*> readIORef mouseBtnSetIO
<*> readIORef mousePosIO
<*> readIORef windowSizeIO
<*> pure curTime
<*> pure (curTime - lastTime)
return updateUIState
loadTextures :: [FilePath] -> IO [TextureObject]
loadTextures = fmap (either error id . sequence) . mapM aux
where aux f = do img <- readTexture (".." </> "res" </> f)
texFilter
return img
texFilter = do textureFilter Texture2D $= ((Nearest, Nothing), Nearest)
texture2DWrap $= (Repeated, ClampToEdge)
loadTextureFile :: FilePath -> IO TextureObject
loadTextureFile f = do
img <- readTexture ("res"</>"gfx"</> f)
texFilter
return $ either error id img
where
texFilter = textureFilter Texture2D $= ((Nearest, Nothing), Nearest)
>> texture2DWrap $= (Repeated, ClampToEdge)
-- * event handling
-------------------------------------------------------------------
onKeyEvent :: IORef (Set.Set Key) -> Key -> KeyButtonState -> IO ()
onKeyEvent ref k Press = modifyIORef ref (Set.insert k)
onKeyEvent ref k Release = modifyIORef ref (Set.delete k)
onMouseBtnEvent :: IORef (Set.Set MouseButton) -> MouseButton -> KeyButtonState -> IO ()
onMouseBtnEvent ref k Press = modifyIORef ref (Set.insert k)
onMouseBtnEvent ref k Release = modifyIORef ref (Set.delete k)
onMouseMove :: IORef (V2 Int) -> Position -> IO ()
onMouseMove ref pos = writeIORef ref (posToV2 pos)
onWindowResize :: IORef (V2 Int) -> Size -> IO ()
onWindowResize ref size = writeIORef ref (sizeToV2 size)
posToV2 :: Integral a => Position -> V2 a
posToV2 (Position x y) = V2 (fromIntegral x) (fromIntegral y)
sizeToV2 :: Size -> V2 Int
sizeToV2 (Size x y) = V2 (fromIntegral x) (fromIntegral y) | fatho/spacemonads | src/Framework.hs | gpl-3.0 | 4,074 | 0 | 18 | 830 | 1,146 | 576 | 570 | 83 | 1 |
runCont :: Cont r a -> (a -> r) -> r
runCont (Cont k) h = k h | hmemcpy/milewski-ctfp-pdf | src/content/3.5/code/haskell/snippet24.hs | gpl-3.0 | 61 | 0 | 8 | 17 | 45 | 22 | 23 | 2 | 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.Discovery.APIs.GetRest
-- 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)
--
-- Retrieve the description of a particular version of an api.
--
-- /See:/ <https://developers.google.com/discovery/ API Discovery Service Reference> for @discovery.apis.getRest@.
module Network.Google.Resource.Discovery.APIs.GetRest
(
-- * REST Resource
APIsGetRestResource
-- * Creating a Request
, apisGetRest
, APIsGetRest
-- * Request Lenses
, agrVersion
, agrAPI
) where
import Network.Google.Discovery.Types
import Network.Google.Prelude
-- | A resource alias for @discovery.apis.getRest@ method which the
-- 'APIsGetRest' request conforms to.
type APIsGetRestResource =
"discovery" :>
"v1" :>
"apis" :>
Capture "api" Text :>
Capture "version" Text :>
"rest" :>
QueryParam "alt" AltJSON :>
Get '[JSON] RestDescription
-- | Retrieve the description of a particular version of an api.
--
-- /See:/ 'apisGetRest' smart constructor.
data APIsGetRest =
APIsGetRest'
{ _agrVersion :: !Text
, _agrAPI :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'APIsGetRest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'agrVersion'
--
-- * 'agrAPI'
apisGetRest
:: Text -- ^ 'agrVersion'
-> Text -- ^ 'agrAPI'
-> APIsGetRest
apisGetRest pAgrVersion_ pAgrAPI_ =
APIsGetRest' {_agrVersion = pAgrVersion_, _agrAPI = pAgrAPI_}
-- | The version of the API.
agrVersion :: Lens' APIsGetRest Text
agrVersion
= lens _agrVersion (\ s a -> s{_agrVersion = a})
-- | The name of the API.
agrAPI :: Lens' APIsGetRest Text
agrAPI = lens _agrAPI (\ s a -> s{_agrAPI = a})
instance GoogleRequest APIsGetRest where
type Rs APIsGetRest = RestDescription
type Scopes APIsGetRest = '[]
requestClient APIsGetRest'{..}
= go _agrAPI _agrVersion (Just AltJSON)
discoveryService
where go
= buildClient (Proxy :: Proxy APIsGetRestResource)
mempty
| brendanhay/gogol | gogol-discovery/gen/Network/Google/Resource/Discovery/APIs/GetRest.hs | mpl-2.0 | 2,876 | 0 | 14 | 690 | 380 | 228 | 152 | 59 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.SecurityCenter.Types
-- 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)
--
module Network.Google.SecurityCenter.Types
(
-- * Service Configuration
securityCenterService
-- * OAuth Scopes
, cloudPlatformScope
-- * ListFindingsResultStateChange
, ListFindingsResultStateChange (..)
-- * Status
, Status
, status
, sDetails
, sCode
, sMessage
-- * GoogleCloudSecuritycenterV1p1beta1TemporalAsset
, GoogleCloudSecuritycenterV1p1beta1TemporalAsset
, googleCloudSecuritycenterV1p1beta1TemporalAsset
, gcsvtaAsset
, gcsvtaChangeType
-- * GoogleCloudSecuritycenterV1p1beta1SecurityCenterProperties
, GoogleCloudSecuritycenterV1p1beta1SecurityCenterProperties
, googleCloudSecuritycenterV1p1beta1SecurityCenterProperties
, gcsvscpResourceDisplayName
, gcsvscpResourceType
, gcsvscpResourceName
, gcsvscpResourceParentDisplayName
, gcsvscpResourceParent
, gcsvscpResourceProject
, gcsvscpResourceProjectDisplayName
, gcsvscpResourceOwners
-- * ListFindingsResponse
, ListFindingsResponse
, listFindingsResponse
, lfrReadTime
, lfrNextPageToken
, lfrTotalSize
, lfrListFindingsResults
-- * AuditConfig
, AuditConfig
, auditConfig
, acService
, acAuditLogConfigs
-- * NotificationConfig
, NotificationConfig
, notificationConfig
, ncServiceAccount
, ncEventType
, ncName
, ncPubsubTopic
, ncStreamingConfig
, ncDescription
-- * Expr
, Expr
, expr
, eLocation
, eExpression
, eTitle
, eDescription
-- * ListOperationsResponse
, ListOperationsResponse
, listOperationsResponse
, lorNextPageToken
, lorOperations
-- * GetIAMPolicyRequest
, GetIAMPolicyRequest
, getIAMPolicyRequest
, giprOptions
-- * GroupFindingsResponse
, GroupFindingsResponse
, groupFindingsResponse
, gfrReadTime
, gfrNextPageToken
, gfrTotalSize
, gfrGroupByResults
-- * RunAssetDiscoveryRequest
, RunAssetDiscoveryRequest
, runAssetDiscoveryRequest
-- * GoogleCloudSecuritycenterV1p1beta1Resource
, GoogleCloudSecuritycenterV1p1beta1Resource
, googleCloudSecuritycenterV1p1beta1Resource
, gcsvrParent
, gcsvrProject
, gcsvrProjectDisplayName
, gcsvrName
, gcsvrParentDisplayName
-- * GoogleCloudSecuritycenterV1p1beta1FindingState
, GoogleCloudSecuritycenterV1p1beta1FindingState (..)
-- * GoogleCloudSecuritycenterV1p1beta1TemporalAssetChangeType
, GoogleCloudSecuritycenterV1p1beta1TemporalAssetChangeType (..)
-- * AssetDiscoveryConfigInclusionMode
, AssetDiscoveryConfigInclusionMode (..)
-- * GoogleCloudSecuritycenterV1p1beta1IAMPolicy
, GoogleCloudSecuritycenterV1p1beta1IAMPolicy
, googleCloudSecuritycenterV1p1beta1IAMPolicy
, gcsvipPolicyBlob
-- * Operation
, Operation
, operation
, oDone
, oError
, oResponse
, oName
, oMetadata
-- * Finding
, Finding
, finding
, fParent
, fSourceProperties
, fState
, fResourceName
, fSecurityMarks
, fCategory
, fExternalURI
, fEventTime
, fName
, fCreateTime
-- * Empty
, Empty
, empty
-- * ListFindingsResult
, ListFindingsResult
, listFindingsResult
, lfrFinding
, lfrResource
, lfrStateChange
-- * ListNotificationConfigsResponse
, ListNotificationConfigsResponse
, listNotificationConfigsResponse
, lncrNotificationConfigs
, lncrNextPageToken
-- * GroupAssetsRequest
, GroupAssetsRequest
, groupAssetsRequest
, garGroupBy
, garReadTime
, garFilter
, garPageToken
, garPageSize
, garCompareDuration
-- * GroupFindingsRequest
, GroupFindingsRequest
, groupFindingsRequest
, gGroupBy
, gReadTime
, gFilter
, gPageToken
, gPageSize
, gCompareDuration
-- * GoogleCloudSecuritycenterV1Resource
, GoogleCloudSecuritycenterV1Resource
, googleCloudSecuritycenterV1Resource
, gParent
, gProject
, gProjectDisplayName
, gName
, gParentDisplayName
-- * AssetDiscoveryConfig
, AssetDiscoveryConfig
, assetDiscoveryConfig
, adcInclusionMode
, adcProjectIds
-- * SecurityMarks
, SecurityMarks
, securityMarks
, smName
, smMarks
-- * NotificationConfigEventType
, NotificationConfigEventType (..)
-- * StatusDetailsItem
, StatusDetailsItem
, statusDetailsItem
, sdiAddtional
-- * GoogleCloudSecuritycenterV1p1beta1NotificationMessage
, GoogleCloudSecuritycenterV1p1beta1NotificationMessage
, googleCloudSecuritycenterV1p1beta1NotificationMessage
, gcsvnmFinding
, gcsvnmTemporalAsset
, gcsvnmResource
, gcsvnmNotificationConfigName
-- * GoogleCloudSecuritycenterV1p1beta1FindingSeverity
, GoogleCloudSecuritycenterV1p1beta1FindingSeverity (..)
-- * OrganizationSettings
, OrganizationSettings
, organizationSettings
, osAssetDiscoveryConfig
, osEnableAssetDiscovery
, osName
-- * GetPolicyOptions
, GetPolicyOptions
, getPolicyOptions
, gpoRequestedPolicyVersion
-- * GoogleCloudSecuritycenterV1p1beta1SecurityMarksMarks
, GoogleCloudSecuritycenterV1p1beta1SecurityMarksMarks
, googleCloudSecuritycenterV1p1beta1SecurityMarksMarks
, gcsvsmmAddtional
-- * SetFindingStateRequestState
, SetFindingStateRequestState (..)
-- * SetIAMPolicyRequest
, SetIAMPolicyRequest
, setIAMPolicyRequest
, siprUpdateMask
, siprPolicy
-- * FindingSourceProperties
, FindingSourceProperties
, findingSourceProperties
, fspAddtional
-- * ListAssetsResultStateChange
, ListAssetsResultStateChange (..)
-- * SetFindingStateRequest
, SetFindingStateRequest
, setFindingStateRequest
, sfsrState
, sfsrStartTime
-- * GoogleCloudSecuritycenterV1NotificationMessage
, GoogleCloudSecuritycenterV1NotificationMessage
, googleCloudSecuritycenterV1NotificationMessage
, gFinding
, gResource
, gNotificationConfigName
-- * GroupAssetsResponse
, GroupAssetsResponse
, groupAssetsResponse
, groReadTime
, groNextPageToken
, groTotalSize
, groGroupByResults
-- * ListSourcesResponse
, ListSourcesResponse
, listSourcesResponse
, lsrNextPageToken
, lsrSources
-- * GoogleCloudSecuritycenterV1p1beta1RunAssetDiscoveryResponseState
, GoogleCloudSecuritycenterV1p1beta1RunAssetDiscoveryResponseState (..)
-- * GroupResultProperties
, GroupResultProperties
, groupResultProperties
, grpAddtional
-- * AuditLogConfigLogType
, AuditLogConfigLogType (..)
-- * Resource
, Resource
, resource
, rProjectDisplayName
, rName
, rProjectName
, rParentName
, rParentDisplayName
-- * GoogleCloudSecuritycenterV1RunAssetDiscoveryResponse
, GoogleCloudSecuritycenterV1RunAssetDiscoveryResponse
, googleCloudSecuritycenterV1RunAssetDiscoveryResponse
, gcsvradrState
, gcsvradrDuration
-- * ListAssetsResponse
, ListAssetsResponse
, listAssetsResponse
, larReadTime
, larNextPageToken
, larListAssetsResults
, larTotalSize
-- * FindingState
, FindingState (..)
-- * Xgafv
, Xgafv (..)
-- * TestIAMPermissionsRequest
, TestIAMPermissionsRequest
, testIAMPermissionsRequest
, tiprPermissions
-- * GoogleCloudSecuritycenterV1RunAssetDiscoveryResponseState
, GoogleCloudSecuritycenterV1RunAssetDiscoveryResponseState (..)
-- * Source
, Source
, source
, sName
, sDisplayName
, sDescription
-- * GoogleCloudSecuritycenterV1p1beta1Finding
, GoogleCloudSecuritycenterV1p1beta1Finding
, googleCloudSecuritycenterV1p1beta1Finding
, gcsvfParent
, gcsvfSourceProperties
, gcsvfState
, gcsvfResourceName
, gcsvfSecurityMarks
, gcsvfCategory
, gcsvfSeverity
, gcsvfExternalURI
, gcsvfEventTime
, gcsvfName
, gcsvfCreateTime
-- * GoogleCloudSecuritycenterV1p1beta1RunAssetDiscoveryResponse
, GoogleCloudSecuritycenterV1p1beta1RunAssetDiscoveryResponse
, googleCloudSecuritycenterV1p1beta1RunAssetDiscoveryResponse
, gState
, gDuration
-- * GoogleCloudSecuritycenterV1p1beta1SecurityMarks
, GoogleCloudSecuritycenterV1p1beta1SecurityMarks
, googleCloudSecuritycenterV1p1beta1SecurityMarks
, gcsvsmName
, gcsvsmMarks
-- * TestIAMPermissionsResponse
, TestIAMPermissionsResponse
, testIAMPermissionsResponse
, tiamprPermissions
-- * ListAssetsResult
, ListAssetsResult
, listAssetsResult
, larAsset
, larStateChange
-- * Policy
, Policy
, policy
, pAuditConfigs
, pEtag
, pVersion
, pBindings
-- * OperationMetadata
, OperationMetadata
, operationMetadata
, omAddtional
-- * GoogleCloudSecuritycenterV1p1beta1Asset
, GoogleCloudSecuritycenterV1p1beta1Asset
, googleCloudSecuritycenterV1p1beta1Asset
, gcsvaSecurityMarks
, gcsvaResourceProperties
, gcsvaUpdateTime
, gcsvaSecurityCenterProperties
, gcsvaName
, gcsvaIAMPolicy
, gcsvaCreateTime
-- * AuditLogConfig
, AuditLogConfig
, auditLogConfig
, alcLogType
, alcExemptedMembers
-- * GoogleCloudSecuritycenterV1p1beta1AssetResourceProperties
, GoogleCloudSecuritycenterV1p1beta1AssetResourceProperties
, googleCloudSecuritycenterV1p1beta1AssetResourceProperties
, gcsvarpAddtional
-- * GroupResult
, GroupResult
, groupResult
, grCount
, grProperties
-- * OperationResponse
, OperationResponse
, operationResponse
, orAddtional
-- * StreamingConfig
, StreamingConfig
, streamingConfig
, scFilter
-- * SecurityMarksMarks
, SecurityMarksMarks
, securityMarksMarks
, smmAddtional
-- * GoogleCloudSecuritycenterV1beta1RunAssetDiscoveryResponseState
, GoogleCloudSecuritycenterV1beta1RunAssetDiscoveryResponseState (..)
-- * GoogleCloudSecuritycenterV1p1beta1FindingSourceProperties
, GoogleCloudSecuritycenterV1p1beta1FindingSourceProperties
, googleCloudSecuritycenterV1p1beta1FindingSourceProperties
, gcsvfspAddtional
-- * GoogleCloudSecuritycenterV1beta1RunAssetDiscoveryResponse
, GoogleCloudSecuritycenterV1beta1RunAssetDiscoveryResponse
, googleCloudSecuritycenterV1beta1RunAssetDiscoveryResponse
, gooState
, gooDuration
-- * Binding
, Binding
, binding
, bMembers
, bRole
, bCondition
) where
import Network.Google.Prelude
import Network.Google.SecurityCenter.Types.Product
import Network.Google.SecurityCenter.Types.Sum
-- | Default request referring to version 'v1p1beta1' of the Security Command Center API. This contains the host and root path used as a starting point for constructing service requests.
securityCenterService :: ServiceConfig
securityCenterService
= defaultService
(ServiceId "securitycenter:v1p1beta1")
"securitycenter.googleapis.com"
-- | View and manage your data across Google Cloud Platform services
cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"]
cloudPlatformScope = Proxy
| brendanhay/gogol | gogol-securitycenter/gen/Network/Google/SecurityCenter/Types.hs | mpl-2.0 | 11,832 | 0 | 7 | 2,570 | 1,107 | 769 | 338 | 315 | 1 |
-- This file is part of purebred
-- Copyright (C) 2017-2021 Róman Joost and Fraser Tweedale
--
-- purebred is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
module Purebred.UI.App where
import qualified Brick.Main as M
import Brick.BChan (BChan)
import Brick.Types (Widget)
import Brick.Focus (focusRing)
import Brick.Widgets.Core (vBox, vLimit)
import qualified Brick.Types as Brick
import qualified Brick.Widgets.Edit as E
import qualified Brick.Widgets.List as L
import qualified Brick.Widgets.FileBrowser as FB
import qualified Graphics.Vty.Input.Events as Vty
import Control.Lens (set, view)
import Control.Monad.State (execStateT)
import qualified Data.Map as Map
import qualified Data.Text.Lazy as T
import Data.Time.Clock (UTCTime(..))
import Data.Time.Calendar (fromGregorian)
import Data.Proxy
import Purebred.UI.Keybindings
import Purebred.UI.Index.Main
import Purebred.UI.Actions (applySearch, initialCompose)
import Purebred.UI.FileBrowser.Main
(renderFileBrowser, renderFileBrowserSearchPathEditor)
import Purebred.UI.Mail.Main (renderAttachmentsList, renderMailView)
import Purebred.UI.Help.Main (renderHelp)
import Purebred.UI.Status.Main (statusbar)
import Purebred.UI.Views
(indexView, mailView, composeView, helpView,
filebrowserView, focusedViewWidget, visibleViewWidgets,
focusedViewName)
import Purebred.UI.ComposeEditor.Main (attachmentsEditor, drawHeaders, renderConfirm)
import Purebred.UI.Draw.Main (renderEditorWithLabel)
import Purebred.Types
import Purebred.UI.Widgets (statefulEditor)
-- * Synopsis
--
-- $synopsis
-- This module ties in all functions for rendering and handling events.
--
-- ** Differences to Brick
-- $differences
-- Purebred uses Brick widgets, but in order to make Purebred
-- configurable, we've made changes to how we use Brick. The single
-- difference to Brick is found on how we process keys (see
-- 'Purebred.UI.Keybindings'). Brick handles keys directly in the
-- widget. Purebred instead looks up keybindings first. If nothing
-- matches, the key is forwarded to the widget.
-- | Main UI drawing function. Looks up which widgets need to be
-- rendered in the current 'View' and traverses each layer pattern
-- matching the 'ViewName' and widget 'Name' in 'renderWidget' to draw
-- the widget.
--
drawUI :: AppState -> [Widget Name]
drawUI s = vBox . fmap (renderWidget s (focusedViewName s)) <$> visibleViewWidgets s
renderWidget :: AppState -> ViewName -> Name -> Widget Name
renderWidget s _ ListOfThreads = renderListOfThreads s
renderWidget s ViewMail ListOfMails = vLimit (view (asConfig . confMailView . mvIndexRows) s) (renderListOfMails s)
renderWidget s _ MailAttachmentOpenWithEditor =
renderEditorWithLabel (Proxy @'MailAttachmentOpenWithEditor) "Open with:" s
renderWidget s _ MailAttachmentPipeToEditor =
renderEditorWithLabel (Proxy @'MailAttachmentPipeToEditor) "Pipe to:" s
renderWidget s _ ListOfMails = renderListOfMails s
renderWidget s _ ComposeListOfAttachments = attachmentsEditor s
renderWidget s _ MailListOfAttachments = renderAttachmentsList s
renderWidget s _ ListOfFiles = renderFileBrowser s
renderWidget s _ ManageFileBrowserSearchPath = renderFileBrowserSearchPathEditor s
renderWidget s _ SaveToDiskPathEditor =
renderEditorWithLabel (Proxy @'SaveToDiskPathEditor) "Save to file:" s
renderWidget s _ SearchThreadsEditor =
renderEditorWithLabel (Proxy @'SearchThreadsEditor) "Query:" s
renderWidget s _ ManageMailTagsEditor =
renderEditorWithLabel (Proxy @'ManageMailTagsEditor) "Labels:" s
renderWidget s _ ManageThreadTagsEditor =
renderEditorWithLabel (Proxy @'ManageThreadTagsEditor) "Labels:" s
renderWidget s _ ScrollingMailView = renderMailView s
renderWidget s _ ScrollingMailViewFindWordEditor =
renderEditorWithLabel (Proxy @'ScrollingMailViewFindWordEditor) "Search for:" s
renderWidget s _ ScrollingHelpView = renderHelp s
renderWidget s _ ComposeFrom = renderEditorWithLabel (Proxy @'ComposeFrom) "From:" s
renderWidget s _ ComposeTo = renderEditorWithLabel (Proxy @'ComposeTo) "To:" s
renderWidget s _ ComposeCc = renderEditorWithLabel (Proxy @'ComposeCc) "Cc:" s
renderWidget s _ ComposeBcc = renderEditorWithLabel (Proxy @'ComposeBcc) "Bcc:" s
renderWidget s _ ComposeSubject = renderEditorWithLabel (Proxy @'ComposeSubject) "Subject:" s
renderWidget s _ ComposeHeaders = drawHeaders s
renderWidget s _ StatusBar = statusbar s
renderWidget s _ ConfirmDialog = renderConfirm s
-- | Main event handler
--
handleViewEvent :: ViewName -> Name -> AppState -> Vty.Event -> Brick.EventM Name (Brick.Next AppState)
handleViewEvent = f where
f ComposeView ComposeFrom = dispatch eventHandlerComposeFrom
f ComposeView ComposeSubject = dispatch eventHandlerComposeSubject
f ComposeView ComposeTo = dispatch eventHandlerComposeTo
f ComposeView ComposeCc = dispatch eventHandlerComposeCc
f ComposeView ComposeBcc = dispatch eventHandlerComposeBcc
f ComposeView ComposeListOfAttachments = dispatch eventHandlerComposeListOfAttachments
f Threads ComposeFrom = dispatch eventHandlerThreadComposeFrom
f Threads ComposeSubject = dispatch eventHandlerThreadComposeSubject
f Threads ComposeTo = dispatch eventHandlerThreadComposeTo
f Threads ListOfThreads = dispatch eventHandlerListOfThreads
f Threads ManageThreadTagsEditor = dispatch eventHandlerManageThreadTagsEditor
f Threads SearchThreadsEditor = dispatch eventHandlerSearchThreadsEditor
f ViewMail ManageMailTagsEditor = dispatch eventHandlerViewMailManageMailTagsEditor
f ViewMail MailListOfAttachments = dispatch eventHandlerMailsListOfAttachments
f ViewMail MailAttachmentOpenWithEditor = dispatch eventHandlerMailAttachmentOpenWithEditor
f ViewMail MailAttachmentPipeToEditor = dispatch eventHandlerMailAttachmentPipeToEditor
f ViewMail ScrollingMailViewFindWordEditor = dispatch eventHandlerScrollingMailViewFind
f ViewMail SaveToDiskPathEditor = dispatch eventHandlerSaveToDiskEditor
f ViewMail ComposeTo = dispatch eventHandlerViewMailComposeTo
f ViewMail _ = dispatch eventHandlerScrollingMailView
f _ ScrollingHelpView = dispatch eventHandlerScrollingHelpView
f _ ListOfFiles = dispatch eventHandlerComposeFileBrowser
f _ ManageFileBrowserSearchPath = dispatch eventHandlerManageFileBrowserSearchPath
f _ ConfirmDialog = dispatch eventHandlerConfirm
f _ _ = dispatch nullEventHandler
-- | Handling of application events. These can be keys which are
-- pressed by the user or asynchronous events send by threads.
--
appEvent ::
AppState
-> Brick.BrickEvent Name PurebredEvent -- ^ event
-> Brick.EventM Name (Brick.Next AppState)
appEvent s (Brick.VtyEvent ev) = handleViewEvent (focusedViewName s) (focusedViewWidget s) s ev
appEvent s (Brick.AppEvent ev) = case ev of
NotifyNumThreads n gen -> M.continue $
if gen == view (asThreadsView . miListOfThreadsGeneration) s
then set (asThreadsView . miThreads . listLength) (Just n) s
else s
NotifyNewMailArrived n -> M.continue (set (asThreadsView . miNewMail) n s)
InputValidated err -> M.continue . ($ s) $
case err of
-- No error at all. Clear any existing errors set in the state.
Nothing -> set asUserMessage Nothing . set (asAsync . aValidation) Nothing
(Just msg) ->
let allVisible = concat $ visibleViewWidgets s
widget = view umContext msg
in if widget `elem` allVisible
-- Widget for this message is still visible, display
-- the message and clear the thread ID.
then set asUserMessage err . set (asAsync . aValidation) Nothing
-- Widget for this message is hidden, ignore the
-- message, clear existing message and thread states.
else set asUserMessage Nothing . set (asAsync . aValidation) Nothing
appEvent s _ = M.continue s
initialViews :: Map.Map ViewName View
initialViews = Map.fromList
[ (Threads, indexView)
, (ViewMail, mailView)
, (Help, helpView)
, (ComposeView, composeView)
, (FileBrowser, filebrowserView)
]
initialState :: Configuration -> BChan PurebredEvent -> (T.Text -> IO ()) -> IO AppState
initialState conf chan sink = do
fb' <- FB.newFileBrowser
FB.selectNonDirectories
ListOfFiles
(Just $ view (confFileBrowserView . fbHomePath) conf)
let
searchterms = view (confNotmuch . nmSearch) conf
mi =
ThreadsView
(ListWithLength (L.list ListOfMails mempty 1) (Just 0))
(ListWithLength (L.list ListOfThreads mempty 1) (Just 0))
firstGeneration
(statefulEditor $ E.editorText SearchThreadsEditor Nothing searchterms)
(E.editorText ManageMailTagsEditor Nothing "")
(E.editorText ManageThreadTagsEditor Nothing "")
0
mv = MailView
Nothing
(MailBody mempty [])
Filtered
(L.list MailListOfAttachments mempty 1)
(E.editorText SaveToDiskPathEditor Nothing "")
(E.editorText MailAttachmentOpenWithEditor Nothing "")
(E.editorText MailAttachmentPipeToEditor Nothing "")
(E.editorText ScrollingMailViewFindWordEditor Nothing "")
(focusRing [])
viewsettings =
ViewSettings
{ _vsViews = initialViews
, _vsFocusedView = focusRing [Threads, Mails, ViewMail, Help, ComposeView, FileBrowser]
}
path = view (confFileBrowserView . fbHomePath) conf
fb = CreateFileBrowser
fb'
(statefulEditor $ E.editor ManageFileBrowserSearchPath Nothing path)
mailboxes = view (confComposeView . cvIdentities) conf
epoch = UTCTime (fromGregorian 2018 07 18) 1
async = Async Nothing
s = AppState conf chan sink mi mv (initialCompose mailboxes) Nothing viewsettings fb epoch async
execStateT applySearch s
-- | Application event loop.
theApp ::
AppState -- ^ initial state
-> M.App AppState PurebredEvent Name
theApp s =
M.App
{ M.appDraw = drawUI
, M.appChooseCursor = M.showFirstCursor
, M.appHandleEvent = appEvent
, M.appStartEvent = return
, M.appAttrMap = const (view (asConfig . confTheme) s)
}
| purebred-mua/purebred | src/Purebred/UI/App.hs | agpl-3.0 | 10,825 | 0 | 18 | 1,899 | 2,385 | 1,266 | 1,119 | 176 | 25 |
module AlphabeticAnagrams where
import Data.List
import Data.Bits
import Control.Arrow
import Data.Maybe
alpha = ['A'..'Z']
type BIT = [Int]
mapString :: String -> [Int]
mapString = ((\x -> fromJust $ elemIndex x alpha) <$>)
lowbit :: Int -> Int
lowbit n = n .&. (-n)
bitSum :: [Int] -> Int -> Int
bitSum bit 0 = 0
bitSum bit x = (bit !! x) + (bitSum bit $ x - lowbit x)
-- bitAdd :: [Int] -> Int -> Int -> [Int]
-- bitAdd bit l i
-- |i > l = bit
-- |otherwise = bitAdd (update bit l l i) (i + lowbit i)
--
inv :: Ord a => [a] -> [(a, a)]
inv xs = [(a, b) | (a : bs) <- tails xs, b <- bs, a > b]
-- lexiPos :: String -> Integer
-- lexiPos s = toInteger $ 1 + (length $ inv $ mapString s)
lexiPos :: String -> Integer
lexiPos [x] = 1
lexiPos w@(c:cs) = sum (f <$> ys) + lexiPos cs
where hshs = tail . init . tails $ w
tsts = init . tail . inits $ w
func i (h : t) = h : i ++ t
ys = nub . ((sort . tail) <$>) . filter ((< c) . head) . zipWith func tsts $ hshs
f = uncurry div . (g . sum &&& product . (g <$>)) . (length <$>) . group . sort
--
| ice1000/OI-codes | codewars/201-300/alphabetic-anagrams.hs | agpl-3.0 | 1,103 | 0 | 14 | 305 | 472 | 262 | 210 | -1 | -1 |
{-# LANGUAGE CPP #-}
--
-- Copyright (C) 2004-5 Don Stewart - http://www.cse.unsw.edu.au/~dons
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
-- USA
--
module System.Loader.Package.Env (
env,
withModEnv,
withPkgEnvs,
modifyModEnv,
modifyPkgEnv,
addModule,
rmModule,
addModules,
isLoaded,
loaded,
addPkgConf,
union,
addStaticPkg,
isStaticPkg,
grabDefaultPkgConf,
readPackageConf,
lookupPkg,
Key(..),
Module(..)
) where
#include "config.h"
import System.Loader.Package.Constants ( sysPkgSuffix )
import Control.Monad ( liftM )
import Data.IORef ( writeIORef, readIORef, newIORef, IORef() )
import Data.Maybe ( isJust, isNothing )
import Data.List ( (\\), nub, )
import System.IO.Unsafe ( unsafePerformIO )
import System.Directory ( doesFileExist )
#if defined(CYGWIN) || defined(__MINGW32__)
import Prelude hiding ( catch, ioError )
import System.IO.Error ( catch, ioError, isDoesNotExistError )
#endif
import Control.Concurrent.MVar ( MVar(), newMVar, withMVar )
import Distribution.Package hiding (depends, packageName, PackageName(..))
import Distribution.Text
import Distribution.InstalledPackageInfo
import Distribution.Simple.Compiler
import Distribution.Simple.GHC
import Distribution.Simple.PackageIndex
import Distribution.Simple.Program
import Distribution.Verbosity
import qualified Data.Map as M
import qualified Data.Set as S
--
-- and map Data.Map terms to FiniteMap terms
--
type FiniteMap k e = M.Map k e
emptyFM :: FiniteMap key elt
emptyFM = M.empty
addToFM :: (Ord key) => FiniteMap key elt -> key -> elt -> FiniteMap key elt
addToFM = \m k e -> M.insert k e m
addWithFM :: (Ord key)
=> (elt -> elt -> elt) -> FiniteMap key elt -> key -> elt -> FiniteMap key elt
addWithFM = \comb m k e -> M.insertWith comb k e m
delFromFM :: (Ord key) => FiniteMap key elt -> key -> FiniteMap key elt
delFromFM = flip M.delete
lookupFM :: (Ord key) => FiniteMap key elt -> key -> Maybe elt
lookupFM = flip M.lookup
--
-- | We need to record what modules and packages we have loaded, so if
-- a package wants to load something already loaded, we
-- can safely ignore that request. We're in the IO monad anyway, so we
-- can add some extra state of our own.
--
-- The state is a FiniteMap String (Module,Int) (a hash of
-- package\/object names to Modules and how many times they've been
-- loaded).
--
-- It also contains the package.conf information, so that if there is a
-- package dependency we can find it correctly, even if it has a
-- non-standard path or name, and if it isn't an official package (but
-- rather one provided via -package-conf). This is stored as a FiniteMap
-- PackageName PackageConfig. The problem then is whether a user's
-- package.conf, that uses the same package name as an existing GHC
-- package, should be allowed, or should shadow a library package? I
-- don't know, but I'm inclined to have the GHC package shadow the
-- user's package.
--
-- This idea is based on /Hampus Ram's dynamic loader/ dependency
-- tracking system. He uses state to record dependency trees to allow
-- clean unloading and other fun. This is quite cool. We're just using
-- state to make sure we don't load the same package twice.
type ModEnv = FiniteMap String (Module,Int)
-- represents a package.conf file
type PkgEnv = FiniteMap PackageName PackageConfig
type StaticPkgEnv = S.Set PackageName
-- multiple package.conf's kept in separate namespaces
type PkgEnvs = [PkgEnv]
type Env = (MVar (),
IORef ModEnv,
IORef PkgEnvs,
IORef StaticPkgEnv)
data Key = Object String | Package String
data Module = Module { modulePath :: !FilePath
, moduleName :: !String
, moduleKey :: Key
}
--
-- our environment, contains a set of loaded objects, and a map of known
-- packages and their informations. Initially all we know is the default
-- package.conf information.
--
env = unsafePerformIO $ do
mvar <- newMVar ()
ref1 <- newIORef emptyFM -- loaded objects
p <- grabDefaultPkgConf
ref3 <- newIORef p -- package.conf info
ref4 <- newIORef (S.fromList ["base","Cabal","haskell-src", "containers",
"arrays", "directory", "random", "process",
"ghc", "ghc-prim"])
return (mvar, ref1, ref3, ref4)
{-# NOINLINE env #-}
-- -----------------------------------------------------------
--
-- | apply 'f' to the loaded objects Env, apply 'f' to the package.conf
-- FM /locks up the MVar/ so you can't recursively call a function
-- inside a with any -Env function. Nice and threadsafe
--
withModEnv :: Env -> (ModEnv -> IO a) -> IO a
withPkgEnvs :: Env -> (PkgEnvs -> IO a) -> IO a
withStaticPkgEnv :: Env -> (StaticPkgEnv -> IO a) -> IO a
withModEnv (mvar,ref,_,_) f = withMVar mvar (\_ -> readIORef ref >>= f)
withPkgEnvs (mvar,_,ref,_) f = withMVar mvar (\_ -> readIORef ref >>= f)
withStaticPkgEnv (mvar,_,_,ref) f = withMVar mvar (\_ -> readIORef ref >>= f)
-- -----------------------------------------------------------
--
-- write an object name
-- write a new PackageConfig
--
modifyModEnv :: Env -> (ModEnv -> IO ModEnv) -> IO ()
modifyPkgEnv :: Env -> (PkgEnvs -> IO PkgEnvs) -> IO ()
modifyStaticPkgEnv :: Env -> (StaticPkgEnv -> IO StaticPkgEnv) -> IO ()
modifyModEnv (mvar,ref,_,_) f = lockAndWrite mvar ref f
modifyPkgEnv (mvar,_,ref,_) f = lockAndWrite mvar ref f
modifyStaticPkgEnv (mvar,_,_,ref) f = lockAndWrite mvar ref f
-- private
lockAndWrite mvar ref f = withMVar mvar (\_->readIORef ref>>=f>>=writeIORef ref)
-- -----------------------------------------------------------
--
-- | insert a loaded module name into the environment
--
addModule :: String -> Module -> IO ()
addModule s m = modifyModEnv env $ \fm -> let c = maybe 0 snd (lookupFM fm s)
in return $ addToFM fm s (m,c+1)
--getModule :: String -> IO (Maybe Module)
--getModule s = withModEnv env $ \fm -> return (lookupFM fm s)
--
-- | remove a module name from the environment. Returns True if the
-- module was actually removed.
--
rmModule :: String -> IO Bool
rmModule s = do modifyModEnv env $ \fm -> let c = maybe 1 snd (lookupFM fm s)
fm' = delFromFM fm s
in if c-1 <= 0
then return fm'
else return fm
withModEnv env $ \fm -> return (isNothing (lookupFM fm s))
--
-- | insert a list of module names all in one go
--
addModules :: [(String,Module)] -> IO ()
addModules ns = mapM_ (uncurry addModule) ns
--
-- | is a module\/package already loaded?
--
isLoaded :: String -> IO Bool
isLoaded s = withModEnv env $ \fm -> return $ isJust (lookupFM fm s)
--
-- confusing! only for filter.
--
loaded :: String -> IO Bool
loaded m = do t <- isLoaded m ; return (not t)
-- -----------------------------------------------------------
-- Package management stuff
--
-- | Insert a single package.conf (containing multiple configs) means:
-- create a new FM. insert packages into FM. add FM to end of list of FM
-- stored in the environment.
--
addPkgConf :: FilePath -> IO ()
addPkgConf f = do
ps <- readPackageConf f
modifyPkgEnv env $ \ls -> return $ union ls ps
--
-- | add a new FM for the package.conf to the list of existing ones; if a package occurs multiple
-- times, pick the one with the higher version number as the default (e.g., important for base in
-- GHC 6.12)
--
union :: PkgEnvs -> [PackageConfig] -> PkgEnvs
union ls ps' =
let fm = emptyFM -- new FM for this package.conf
in foldr addOnePkg fm ps' : ls
where
-- we add each package with and without it's version number and with the full installedPackageId
addOnePkg p fm' = addToPkgEnvs (addToPkgEnvs (addToPkgEnvs fm' (display $ sourcePackageId p) p) (display $ installedPackageId p) p)
(packageName p) p
-- if no version number specified, pick the higher version
addToPkgEnvs = addWithFM higherVersion
higherVersion pkgconf1 pkgconf2
| installedPackageId pkgconf1 >= installedPackageId pkgconf2 = pkgconf1
| otherwise = pkgconf2
--
-- | generate a PkgEnv from the system package.conf
-- The path to the default package.conf was determined by /configure/
-- This imposes a constraint that you must build your plugins with the
-- same ghc you use to build hs-plugins. This is reasonable, we feel.
--
grabDefaultPkgConf :: IO PkgEnvs
grabDefaultPkgConf = do
pc <- configureAllKnownPrograms silent defaultProgramConfiguration
pkgIndex <- getInstalledPackages silent [GlobalPackageDB, UserPackageDB] pc
return $ [] `union` allPackages pkgIndex
--
-- parse a source file, expanding any $libdir we see.
--
readPackageConf :: FilePath -> IO [PackageConfig]
readPackageConf f = do
pc <- configureAllKnownPrograms silent defaultProgramConfiguration
pkgIndex <- getInstalledPackages silent [GlobalPackageDB, UserPackageDB, SpecificPackageDB f] pc
return $ allPackages pkgIndex
-- -----------------------------------------------------------
-- Static package management stuff. A static package is linked with the base
-- application and we should therefore not link with any of the DLLs it requires.
addStaticPkg :: PackageName -> IO ()
addStaticPkg pkg = modifyStaticPkgEnv env $ \set -> return $ S.insert pkg set
isStaticPkg :: PackageName -> IO Bool
isStaticPkg pkg = withStaticPkgEnv env $ \set -> return $ S.member pkg set
--
-- Package path, given a package name, look it up in the environment and
-- return the path to all the libraries needed to load this package.
--
-- What do we need to load? With the library_dirs as prefix paths:
-- . anything in the hs_libraries fields, libdir expanded
--
-- . anything in the extra_libraries fields (i.e. cbits), expanded,
--
-- which includes system .so files.
--
-- . also load any dependencies now, because of that weird mtl
-- library that lang depends upon, but which doesn't show up in the
-- interfaces for some reason.
--
-- We return all the package paths that possibly exist, and the leave it
-- up to loadObject not to load the same ones twice...
--
lookupPkg :: PackageName -> IO ([FilePath],[FilePath])
lookupPkg pn = go [] pn
where
go :: [PackageName] -> PackageName -> IO ([FilePath],[FilePath])
go seen p = do
(ps, (f, g)) <- lookupPkg' p
static <- isStaticPkg p
(f', g') <- liftM unzip $ mapM (go (nub $ seen ++ ps)) (ps \\ seen)
return $ (nub $ (concat f') ++ f, if static then [] else nub $ (concat g') ++ g)
data LibrarySpec
= DLL String -- -lLib
| DLLPath FilePath -- -Lpath
classifyLdInput :: FilePath -> IO (Maybe LibrarySpec)
classifyLdInput ('-':'l':lib) = return (Just (DLL lib))
classifyLdInput ('-':'L':path) = return (Just (DLLPath path))
classifyLdInput _ = return Nothing
-- TODO need to define a MAC\/DARWIN symbol
#if defined(MACOSX)
mkSOName root = "lib" ++ root ++ ".dylib"
#elif defined(CYGWIN) || defined(__MINGW32__)
-- Win32 DLLs have no .dll extension here, because addDLL tries
-- both foo.dll and foo.drv
mkSOName root = root
#else
mkSOName root = "lib" ++ root ++ ".so"
#endif
#if defined(MACOSX)
mkDynPkgName root = mkSOName (root ++ "_dyn")
#else
mkDynPkgName root = mkSOName root
#endif
data HSLib = Static FilePath | Dynamic FilePath
--
-- return any stuff to load for this package, plus the list of packages
-- this package depends on. which includes stuff we have to then load
-- too.
--
lookupPkg' :: PackageName -> IO ([PackageName],([FilePath],[FilePath]))
lookupPkg' p = withPkgEnvs env $ \fms -> go fms p
where
go [] _ = return ([],([],[]))
go (fm:fms) q = case lookupFM fm q of
Nothing -> go fms q -- look in other pkgs
Just pkg -> do
let hslibs = hsLibraries pkg
extras' = extraLibraries pkg
cbits = filter (\e -> reverse (take (length "_cbits") (reverse e)) == "_cbits") extras'
extras = filter (flip notElem cbits) extras'
ldopts = ldOptions pkg
deppkgs = packageDeps pkg
ldInput <- mapM classifyLdInput ldopts
let ldOptsLibs = [ path | Just (DLL path) <- ldInput ]
ldOptsPaths = [ path | Just (DLLPath path) <- ldInput ]
dlls = map mkSOName (extras ++ ldOptsLibs)
#if defined(CYGWIN) || defined(__MINGW32__)
libdirs = fix_topdir (libraryDirs pkg) ++ ldOptsPaths
#else
libdirs = libraryDirs pkg ++ ldOptsPaths
#endif
-- If we're loading dynamic libs we need the cbits to appear before the
-- real packages.
libs <- mapM (findHSlib libdirs) (cbits ++ hslibs)
#if defined(CYGWIN) || defined(__MINGW32__)
windowsos <- catch (getEnv "OS")
(\e -> if isDoesNotExistError e then return "Windows_98" else ioError e)
windowsdir <-
if windowsos == "Windows_9X" -- I don't know Windows 9X has OS system variable
then return "C:/windows"
else return "C:/winnt"
sysroot <- catch (getEnv "SYSTEMROOT")
(\e -> if isDoesNotExistError e then return windowsdir else ioError e) -- guess at a reasonable default
let syslibdir = sysroot ++ (if windowsos == "Windows_9X" then "/SYSTEM" else "/SYSTEM32")
libs' <- mapM (findDLL $ syslibdir : libdirs) dlls
#else
libs' <- mapM (findDLL libdirs) dlls
#endif
let slibs = [ lib | Right (Static lib) <- libs ]
dlibs = [ lib | Right (Dynamic lib) <- libs ]
return (deppkgs, (slibs,map (either id id) libs' ++ dlibs) )
#if defined(CYGWIN) || defined(__MINGW32__)
-- replace $topdir
fix_topdir [] = []
fix_topdir (x:xs) = replace_topdir x : fix_topdir xs
replace_topdir [] = []
replace_topdir ('$':xs)
| take 6 xs == "topdir" = ghcLibraryPath ++ (drop 6 xs)
| otherwise = '$' : replace_topdir xs
replace_topdir (x:xs) = x : replace_topdir xs
#endif
-- a list elimination form for the Maybe type
--filterRight :: [Either left right] -> [right]
--filterRight [] = []
--filterRight (Right x:xs) = x:filterRight xs
--filterRight (Left _:xs) = filterRight xs
--
-- Check that a path to a library actually reaches a library
findHSlib' :: [FilePath] -> String -> IO (Maybe FilePath)
findHSlib' [] _ = return Nothing
findHSlib' (dir:dirs) lib = do
let l = dir </> lib
b <- doesFileExist l
if b then return $ Just l -- found it!
else findHSlib' dirs lib
findHSslib dirs lib = findHSlib' dirs $ lib ++ sysPkgSuffix
findHSdlib dirs lib = findHSlib' dirs $ mkDynPkgName lib
-- Problem: sysPkgSuffix is ".o", but extra libraries could be
-- ".so"
-- Solution: first look for static library, if we don't find it
-- look for a dynamic version.
findHSlib :: [FilePath] -> String -> IO (Either String HSLib)
findHSlib dirs lib = do
static <- findHSslib dirs lib
case static of
Just file -> return $ Right $ Static file
Nothing -> do
dynamic <- findHSdlib dirs lib
case dynamic of
Just file -> return $ Right $ Dynamic file
Nothing -> return $ Left lib
findDLL :: [FilePath] -> String -> IO (Either String FilePath)
findDLL [] lib = return (Left lib)
findDLL (dir:dirs) lib = do
let l = dir </> lib
b <- doesFileExist l
if b then return $ Right l
else findDLL dirs lib
------------------------------------------------------------------------
-- break a module cycle
-- private:
--
(</>) :: FilePath -> FilePath -> FilePath
[] </> b = b
a </> b = a ++ "/" ++ b
------------------------------------------------------------------------
--
-- We export an abstract interface to package conf`s because we have
-- to handle either traditional or Cabal style package conf`s.
--
packageName :: PackageConfig -> PackageName
packageDeps :: PackageConfig -> [PackageName]
-- updImportDirs :: ([FilePath] -> [FilePath]) -> PackageConfig -> PackageConfig
-- updLibraryDirs :: ([FilePath] -> [FilePath]) -> PackageConfig -> PackageConfig
type PackageName = String
type PackageConfig = InstalledPackageInfo
packageName = display . pkgName . sourcePackageId
-- packageName_ = pkgName . sourcePackageId
packageDeps = (map display) . depends
{-
updImportDirs f pk@(InstalledPackageInfo { importDirs = idirs }) =
pk { importDirs = f idirs }
updLibraryDirs f pk@(InstalledPackageInfo { libraryDirs = ldirs }) =
pk { libraryDirs = f ldirs }
-}
| facundominguez/package-loader | src/System/Loader/Package/Env.hs | lgpl-2.1 | 18,508 | 0 | 23 | 5,084 | 3,780 | 2,043 | 1,737 | 209 | 9 |
{-
- This file is part of Bilder.
-
- Bilder is free software: you can redistribute it and/or modify
- it under the terms of the GNU Lesser General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- Bilder is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public License
- along with Bilder. If not, see <http://www.gnu.org/licenses/>.
-
- Copyright © 2012-2013 Filip Lundborg
- Copyright © 2012-2013 Ingemar Ådahl
-
-}
{-# LANGUAGE UnicodeSyntax #-}
module Compiler.Simple.Types where
import qualified Data.Map as Map
import Compiler.Simple.AbsSimple
data Shader = Shader {
functions ∷ Map.Map String Function
, variables ∷ Map.Map String Variable
--, structs ∷ Map.Map String Struct
, output ∷ Variable
, inputs ∷ Map.Map String Variable
}
deriving (Show, Eq)
| ingemaradahl/bilder | src/Compiler/Simple/Types.hs | lgpl-3.0 | 1,176 | 0 | 10 | 251 | 89 | 54 | 35 | 10 | 0 |
{-# OPTIONS_GHC -Wall -XFlexibleInstances #-}
{-
-
- Copyright 2014 -- name removed for blind review, all rights reserved! Please push a git request to receive author's name! --
- 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 Main (main) where
import System.Environment (getArgs)
import EParser (parse,tbrfun,pGetEMOD,pGetLisp,TermBuilder (..))
import ToNET (showNET)
import System.IO
main :: IO ()
main
= do args <- getArgs
s <- readContents args "i"
case (parse pGetLisp "(stdin)" s) of
(Left e) -> hPutStrLn stderr (show e)
(Right [g]) -> case (tbrfun (pGetEMOD g) 0) of
(TBError e) -> hPutStrLn stderr (show e)
(TB v _) -> do let (dotGraph,proofObligations) = showNET v
write args "g" dotGraph
write args "p" proofObligations
(Right []) -> hPutStrLn stderr "Please supply input at (stdin)"
_ -> hPutStrLn stderr "More than one input not supported"
readContents :: [String] -> String -> IO (String)
readContents (('-':h):v:_) h' | h==h'
= case v of
"-" -> getContents
"_" -> return ""
f -> do hd <- openFile f ReadMode
hGetContents hd
readContents (_:as) x = readContents as x
readContents [] f
= do hPutStrLn stderr$ "No `-"++f++" filename' argument given, using stdin for input (use - as a filename to suppress this warning while still using stdin, or _ to read an empty string)."
getContents
write :: [String] -> String -> String -> IO ()
write (('-':h):v:_) h' s | h==h'
= case v of
"-" -> putStrLn s
"_" -> return ()
f -> do hd <- openFile f WriteMode
hPutStrLn hd s
hClose hd
write (_:as) x y = write as x y
write [] f _ = hPutStrLn stderr$ "No `-"++f++" filename' argument given, some of the output is omitted (use - as a filename for stdout, or _ to suppress this warning)." | DatePaper616/code | eMOD.hs | apache-2.0 | 2,447 | 0 | 18 | 635 | 605 | 299 | 306 | 40 | 5 |
unit = ["", "Man","Oku","Cho","Kei","Gai","Jo","Jou","Ko","Kan","Sei","Sai","Gok","Ggs","Asg","Nyt","Fks","Mts"]
toStr 0 _ = []
toStr _ [] = []
toStr n (u:us) =
let m = n `mod` 10000
n'= n `div` 10000
in
if m == 0
then (toStr n' us)
else (toStr n' us) ++ show(m) ++ u
ans' :: Integer -> Integer -> String
ans' a b =
let n = a ^ b
in
toStr n unit
ans :: [[Integer]] -> [String]
ans ([0,0]:_) = []
ans ([a,b]:s) =
(ans' a b):(ans s)
main = do
c <- getContents
let i = map (map read) $ map words $ lines c :: [[Integer]]
o = ans i
mapM_ putStrLn o
| a143753/AOJ | 0287.hs | apache-2.0 | 595 | 0 | 14 | 159 | 365 | 198 | 167 | 22 | 2 |