code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Cauterize.Dynamic.Meta.Gen ( dynamicMetaGen , dynamicMetaGen' ) where import Cauterize.Dynamic.Meta.Types import Cauterize.Dynamic.Gen import Control.Monad import Test.QuickCheck.Gen import qualified Cauterize.Specification as Spec import qualified Data.Map as M dynamicMetaGen :: Spec.Specification -> IO MetaType dynamicMetaGen spec = generate $ dynamicMetaGen' spec dynamicMetaGen' :: Spec.Specification -> Gen MetaType dynamicMetaGen' spec = do n <- elements $ M.keys m liftM MetaType (dynamicGenType' spec n) where m = Spec.specTypeMap spec
cauterize-tools/cauterize
src/Cauterize/Dynamic/Meta/Gen.hs
bsd-3-clause
572
0
10
84
151
84
67
16
1
module Data.Vhd.Geometry where import Data.Vhd.Types import Data.Word -- | Calculates disk geometry using the algorithm presented in -- | the virtual hard disk image format specification (v 1.0). diskGeometry :: Word64 -> DiskGeometry diskGeometry totalSectors' = let (sectorsPerTrack, heads, cylindersTimesHeads) = calculate in let cylinders = cylindersTimesHeads `div` heads in DiskGeometry (fromIntegral cylinders) (fromIntegral heads) (fromIntegral sectorsPerTrack) where totalSectors = min totalSectors' (65535 * 16 * 255) calculate | totalSectors > 65536 * 16 * 63 = (255, 16, totalSectors `div` 255) | otherwise = let sectorsPerTrack = 17 in let cylindersTimesHeads = totalSectors `div` 17 in let heads = max 4 $ (cylindersTimesHeads + 1023) `div` 1024 in let (sectorsPerTrack', heads', cylindersTimesHeads') = if cylindersTimesHeads >= heads * 1024 || heads > 16 then (31, 16, totalSectors `div` 31) else (sectorsPerTrack, heads, cylindersTimesHeads) in if cylindersTimesHeads' >= heads' * 1024 then (63, 16, totalSectors `div` 63) else (sectorsPerTrack', heads', cylindersTimesHeads')
jonathanknowles/hs-vhd
Data/Vhd/Geometry.hs
bsd-3-clause
1,186
32
22
243
370
203
167
25
3
{-# LANGUAGE NoImplicitPrelude #-} module Structure.Commutative where import Structure.Function -- | 交換可能な値 class Commutative s where swap :: s a b -> s b a swap = undefined -- (,)を抽象化したクラス class (Commutative and) => Diproduct and where product :: a -> b -> and a b product a b = foesac (const a) (const b) undefined foesac :: (a -> b) -> (a -> c) -> (a -> and b c) foesac f g x = product (f x) (g x) first :: and a b -> a first = second . swap second :: and a b -> b second = first . swap curry :: (Diproduct t) => (t a b -> c) -> a -> b -> c curry f a b = f $ product a b uncurry :: (Diproduct t) => (a -> b -> c) -> t a b -> c uncurry f x = f (first x) (second x) parallel :: (Diproduct t) => (a -> b) -> (c -> d) -> t a c -> t b d parallel f g = foesac (f . first) (g . second) instance Commutative (,) where swap (a, b) = (b, a) instance Diproduct (,) where product = (,) first (a,b) = a -- | Eitherを抽象化したクラス class (Commutative or) => Disum or where caseof :: (a -> c) -> (b -> c) -> (or a b -> c) caseof f g x = undefined left :: a -> or a b left = swap . right right :: a -> or b a right = swap . left yrruc :: (Disum or, Diproduct and) => (or a b -> c) -> and (a -> c) (b -> c) yrruc f = product (f . left) (f . right) yrrucnu :: (Disum or, Diproduct and) => and (a -> c) (b -> c) -> (or a b -> c) yrrucnu = uncurry caseof data Either a b = Left a | Right b instance Commutative Either where swap (Left x) = Right x swap (Right x) = Left x instance Disum Either where caseof f g (Left x) = f x caseof f g (Right x) = g x left = Left
Hexirp/monadiclasses
src/Structure/Commutative.hs
bsd-3-clause
1,889
0
11
666
867
452
415
45
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} {- Use monadiccp/OvertonFD as a finite-domain constraint solver to construct subwords in a generic way. TODO It is really slow. Maybe it is possible to "compile" the two inequality systems so that they can later be run faster. see http://www.cs.washington.edu/research/constraints/solvers/cp97.html -} module ADP.Multi.Constraint.ConstraintSolver ( constructSubwords1, constructSubwords2 ) where import Control.Exception import qualified Data.Map as Map import Data.Maybe (fromJust, isNothing) import ADP.Debug import ADP.Multi.Parser import ADP.Multi.Rewriting import ADP.Multi.Rewriting.Model import ADP.Multi.Rewriting.YieldSize import ADP.Multi.Rewriting.RangesHelper import ADP.Multi.Constraint.MonadicCpHelper import Control.CP.FD.Interface constructSubwords1 :: SubwordConstructionAlgorithm Dim1 constructSubwords1 _ _ b | trace ("constructSubwords1 " ++ show b) False = undefined constructSubwords1 f infos [i,j] = assert (i <= j) $ let yieldSizeMap = buildYieldSizeMap infos symbolIDs = Map.keys yieldSizeMap rewritten = f symbolIDs parserCount = length infos remainingParsers = [parserCount,parserCount-1..1] `zip` infos rangeDesc = [(i,j,rewritten)] in trace ("f " ++ show symbolIDs ++ " = " ++ show rewritten) $ assert (length rewritten == Map.size yieldSizeMap && all (`elem` rewritten) symbolIDs) $ constructSubwordsRec yieldSizeMap remainingParsers rangeDesc constructSubwords2 :: SubwordConstructionAlgorithm Dim2 constructSubwords2 _ _ b | trace ("constructSubwords2 " ++ show b) False = undefined constructSubwords2 f infos [i,j,k,l] = assert (i <= j && j <= k && k <= l) $ let yieldSizeMap = buildYieldSizeMap infos symbolIDs = Map.keys yieldSizeMap (left,right) = f symbolIDs parserCount = length infos remainingParsers = [parserCount,parserCount-1..1] `zip` infos rangeDescs = [(i,j,left),(k,l,right)] in trace ("f " ++ show symbolIDs ++ " = (" ++ show left ++ "," ++ show right ++ ")") $ assert (length left + length right == Map.size yieldSizeMap && all (`elem` (left ++ right)) symbolIDs && not (null left) && not (null right)) $ constructSubwordsRec yieldSizeMap remainingParsers rangeDescs constructSubwordsRec :: YieldSizeMap -> [(Int,ParserInfo)] -> [RangeDesc] -> [SubwordTree] constructSubwordsRec a b c | trace ("constructSubwordsRec " ++ show a ++ " " ++ show b ++ " " ++ show c) False = undefined constructSubwordsRec _ [] _ = [] constructSubwordsRec yieldSizeMap ((current,ParserInfo1 {}):rest) rangeDescs = let symbolLoc = findSymbol1 current rangeDescs subwords = calcSubwords1 yieldSizeMap symbolLoc in trace ("calc subwords for dim1") $ trace ("subwords: " ++ show subwords) $ [ SubwordTree [i,j] restTrees | (i,j) <- subwords, let newDescs = constructNewRangeDescs1 rangeDescs symbolLoc (i,j), let restTrees = constructSubwordsRec yieldSizeMap rest newDescs ] constructSubwordsRec yieldSizeMap ((current,ParserInfo2 {}):rest) rangeDescs = let symbolLocs = findSymbol2 current rangeDescs subwords = calcSubwords2 yieldSizeMap symbolLocs in trace ("calc subwords for dim2") $ trace ("subwords: " ++ show subwords) $ [ SubwordTree [i,j,k,l] restTrees | (i,j,k,l) <- subwords, let newDescs = constructNewRangeDescs2 rangeDescs symbolLocs (i,j,k,l), let restTrees = constructSubwordsRec yieldSizeMap rest newDescs ] calcSubwords2 :: YieldSizeMap -> (SymbolPos,SymbolPos) -> [Subword2] calcSubwords2 a b | trace ("calcSubwords " ++ show a ++ " " ++ show b) False = undefined calcSubwords2 yieldSizeMap (left@((i,j,r),sym1Idx),right@((_,_,r'),sym2Idx)) | r == r' = calcSubwords2Dependent yieldSizeMap (i,j,r) sym1Idx sym2Idx | otherwise = [ (i',j',k',l') | (i',j') <- calcSubwords1 yieldSizeMap left , (k',l') <- calcSubwords1 yieldSizeMap right ] calcSubwords1 :: YieldSizeMap -> SymbolPos -> [Subword1] calcSubwords1 _ b | trace ("calcSubwordsIndependent " ++ show b) False = undefined calcSubwords1 yieldSizeMap pos@((i,j,_),_) = let (minY,maxY) = yieldSizeOf yieldSizeMap pos (minYLeft,maxYLeft) = combinedYieldSizeLeftOf yieldSizeMap pos (minYRight,maxYRight) = combinedYieldSizeRightOf yieldSizeMap pos model :: FDModel model = exists $ \col -> do let rangeLen = fromIntegral (j-i) [minY',minYLeft',minYRight'] = map fromIntegral [minY,minYLeft,minYRight] [maxY',maxYLeft',maxYRight'] = map (maybe rangeLen fromIntegral) [maxY,maxYLeft,maxYRight] [len1,len2,len3] <- colList col 3 xsum col @= rangeLen len1 @>= minYLeft' len2 @>= minY' len3 @>= minYRight' len1 @<= maxYLeft' len2 @<= maxY' len3 @<= maxYRight' rangeLen - maxYLeft' @<= len2 + len3 rangeLen - maxYRight' @<= len1 + len2 rangeLen - maxY' @<= len1 + len3 return col in map (\[len1,_,len3] -> (i+len1, j-len3)) $ solveModel model calcSubwords2Dependent :: YieldSizeMap -> RangeDesc -> Int -> Int -> [Subword2] calcSubwords2Dependent _ b c d | trace ("calcSubwordsDependent " ++ show b ++ " " ++ show c ++ " " ++ show d) False = undefined calcSubwords2Dependent yieldSizeMap desc sym1Idx sym2Idx = let sym1Idx' = if sym1Idx < sym2Idx then sym1Idx else sym2Idx sym2Idx' = if sym1Idx < sym2Idx then sym2Idx else sym1Idx subs = doCalcSubwords2Dependent yieldSizeMap desc sym1Idx' sym2Idx' in if sym1Idx < sym2Idx then subs else [ (k,l,m,n) | (m,n,k,l) <- subs ] doCalcSubwords2Dependent :: YieldSizeMap -> RangeDesc -> Int -> Int -> [Subword2] doCalcSubwords2Dependent yieldSizeMap desc@(i,j,_) sym1Idx sym2Idx = let (minY1,maxY1) = yieldSizeOf yieldSizeMap (desc,sym1Idx) (minY2,maxY2) = yieldSizeOf yieldSizeMap (desc,sym2Idx) (minYLeft1,maxYLeft1) = combinedYieldSizeLeftOf yieldSizeMap (desc,sym1Idx) (minYRight1,maxYRight1) = combinedYieldSizeRightOf yieldSizeMap (desc,sym1Idx) (minYRight2,maxYRight2) = combinedYieldSizeRightOf yieldSizeMap (desc,sym2Idx) minYBetween = minYRight1 - minYRight2 - minY2 maxYBetween | sym1Idx + 1 == sym2Idx = Just 0 | isNothing maxYRight1 = Nothing | otherwise = Just $ fromJust maxYRight1 - fromJust maxYRight2 - fromJust maxY2 model :: FDModel model = exists $ \col -> do let rangeLen = fromIntegral (j-i) [minYLeft1',minY1',minYBetween',minY2',minYRight2'] = map fromIntegral [minYLeft1,minY1,minYBetween,minY2,minYRight2] [maxYLeft1',maxY1',maxYBetween',maxY2',maxYRight2'] = map (maybe rangeLen fromIntegral) [maxYLeft1,maxY1,maxYBetween,maxY2,maxYRight2] [lenLeft1,len1,lenBetween,len2,lenRight2] <- colList col 5 xsum col @= rangeLen lenLeft1 @>= minYLeft1' len1 @>= minY1' lenBetween @>= minYBetween' len2 @>= minY2' lenRight2 @>= minYRight2' lenLeft1 @<= maxYLeft1' len1 @<= maxY1' lenBetween @<= maxYBetween' len2 @<= maxY2' lenRight2 @<= maxYRight2' rangeLen - maxYLeft1' @<= len1 + lenBetween + len2 + lenRight2 rangeLen - maxY1' @<= lenLeft1 + lenBetween + len2 + lenRight2 rangeLen - maxYBetween' @<= lenLeft1 + len1 + len2 + lenRight2 rangeLen - maxY2' @<= lenLeft1 + len1 + lenBetween + lenRight2 rangeLen - maxYRight2' @<= lenLeft1 + len1 + lenBetween + len2 return col in map (\ [lenLeft1,len1,_,len2,lenRight2] -> ( i + lenLeft1 , i + lenLeft1 + len1 , j - lenRight2 - len2 , j - lenRight2 ) ) $ solveModel model
adp-multi/adp-multi-monadiccp
src/ADP/Multi/Constraint/ConstraintSolver.hs
bsd-3-clause
8,813
0
18
2,640
2,542
1,339
1,203
148
4
module Generics.GPAH.Derive.Base where import qualified Data.Map as M import Control.DeepSeq import Data.Monoid data Analysis = Analysis { deriveTH :: M.Map String Int-- derive directive strings , derivePP :: M.Map String Int , driftPP :: M.Map String Int , driftGL :: M.Map String Int } deriving (Show) instance Monoid Analysis where mempty = Analysis mempty mempty mempty mempty (Analysis x1 x2 x3 x4) `mappend` (Analysis y1 y2 y3 y4) = Analysis (M.unionWith (+) x1 y1) (M.unionWith (+) x2 y2) (M.unionWith (+) x3 y3) (M.unionWith (+) x4 y4) instance NFData Analysis where rnf (Analysis a1 a2 a3 a4) = a1 `deepseq` a2 `deepseq` a3 `deepseq` a4 `deepseq` () deriveClasses = ["Arbitrary", "ArbitraryOld", "Arities", "Binary", "BinaryDefer", "Bounded", "Data", "DataAbstract", "Default", "Enum", "EnumCyclic", "Eq", "Fold", "Foldable", "From", "Fucntor", "Has", "Is", "JSON", "LazySet", "Lens", "Monoid", "NFData", "Ord", "Read", "Ref", "Serial", "Serialize", "Set", "Show", "Traversable", "Typeable", "UniplateDirect", "UniplateTypeable", "Update"] driftClasses = ["Binary", "GhcBinary", "Observable", "NFData", "Typeable", "FuncotrM", "HFoldable", "Monoid", "RMapM", "Term", "Bounded", "Enum", "Eq", "Ord", "Read", "Show", "ATermConvertible", "Haskell2Xml", "XmlContent", "Parse", "Query", "from", "get", "has", "is", "test", "un", "update"] defaultDerivations = ["makeArbitrary", "makeArbitraryOld", "makeArities", "makeBinary", "makeBinaryDefer", "makeBounded", "makeData", "makeDataAbstract", "makeDefault", "makeEnum", "makeEnumCyclic", "makeEq", "makeFold", "makeFoldable", "makeFrom", "makeFunctor", "makeHas", "makeIs", "makeJSON", "makeLazySet", "makeMonoid", "makeNFData", "makeOrd", "makeRead", "makeRef", "makeSerial", "makeSerialize", "makeSet", "makeShow", "makeTraversable", "makeTypeable", "makeUniplateDirect", "makeUniplateTypeable", "makeUpdate"]
bezirg/gpah
src/Generics/GPAH/Derive/Base.hs
bsd-3-clause
3,816
0
10
2,159
579
356
223
120
1
runLength [] = [] runLength (x:xs) = runLength' 1 x xs where runLength' n a [] = [(n, a)] runLength' n a (x:xs) | a == x = runLength' (n+1) a xs | otherwise = (n, a) : runLength' 1 x xs
binesiyu/ifl
examples/ch04/RunLength.hs
mit
225
0
10
81
129
65
64
6
2
import Data.List import Data.Function (on) import Data.Char import qualified Data.Map as Map import qualified Data.Set as Set import Geometry import qualified Geometry.Sphere as Sphere import qualified Geometry.Cuboid as Cuboid import qualified Geometry.Cube as Cube doubleMe x = x + x doubleUs x y = doubleMe x + doubleMe y doubleSmallNumber x = if x > 100 then x else x*2 doubleSmallNumber' x = (if x > 100 then x else x*2) + 1 conanO'Brien = "It's a-me, Conan O'Brien!" boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x ] length' xs = sum [1 | _ <- xs] removeNonUppercase :: [Char] -> [Char] removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z'] ] addThree :: Int -> Int -> Int -> Int addThree x y z = x + y + z factorial' :: Integer -> Integer factorial' n = product [1..n] circumference :: Float -> Float circumference r = 2 * pi * r circumference' :: Double -> Double circumference' r = 2 * pi * r lucky :: (Integral a) => a -> String lucky 7 = "LUCKY NUMBER SEVEN!" lucky x = "Sorry, you're out of luck, pal!" sayMe :: (Integral a) => a -> String sayMe 1 = "One!" sayMe 2 = "Two!" sayMe 3 = "Three!" sayMe 4 = "Four!" sayMe 5 = "Five!" sayMe x = "Not between 1 and 5" factorial :: (Integral a) => a -> a factorial 0 = 1 factorial n = n * factorial (n - 1) charName :: Char -> String charName 'a' = "Albert" charName 'b' = "Broseph" charName 'c' = "Cecil" addVectors' :: (Num a) => (a, a) -> (a, a) -> (a, a) addVectors' a b = (fst a + fst b, snd a + snd b) addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a) addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2) first :: (a, b, c) -> a first (x, _, _) = x second :: (a, b, c) -> b second (_, y, _) = y third :: (a, b, c) -> c third (_, _, z) = z head' :: [a] -> a head' [] = error "Can't call head on an empty list, dummy!" head' (x:_) = x tell :: (Show a) => [a] -> String tell [] = "The list is empty" tell [x] = "The list has one element: " ++ show x tell [x,y] = "The list has two elements: " ++ show x ++ " and " ++ show y tell (x:y:_) = "This list is long. The first two elements are: " ++ show x ++ " and " ++ show y length'' :: (Num b) => [a] -> b length'' [] = 0 length'' (_:xs) = 1 + length'' xs sum' :: (Num a) => [a] -> a sum' [] = 0 sum' (x:xs) = x + sum' xs capital :: String -> String capital "" = "Empty string, whoops!" capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x] bmiTell :: (RealFloat a) => a -> String bmiTell bmi | bmi <= 18.5 = "You're underweight, you emo, you!" | bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!" | bmi <= 30.0 = "You're fat! Lose some weight, fatty!" | otherwise = "You're a whale, congratulations!" bmiTell' :: (RealFloat a) => a -> a -> String bmiTell' weight height | weight / height ^ 2 <= 18.5 = "You're underweight, you emo, you!" | weight / height ^ 2 <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!" | weight / height ^ 2 <= 30.0 = "You're fat! Lose some weight, fatty!" | otherwise = "You're a whale, congratulations!" max' :: (Ord a) => a -> a -> a max' a b | a > b = a | otherwise = b max'' :: (Ord a) => a -> a -> a max'' a b | a > b = a | otherwise = b compare' :: (Ord a) => a -> a -> Ordering a `compare'` b | a > b = GT | a == b = EQ | otherwise = LT bmiTell'' :: (RealFloat a) => a -> a -> String bmiTell'' weight height | bmi <= 18.5 = "You're underweight, you emo, you!" | bmi <= 25.0 = "You're supposedly normal. Pffft, I bet you're ugly!" | bmi <= 30.0 = "You're fat! Lose some weight, fatty!" | otherwise = "You're a whale, congratulations!" where bmi = weight / height ^ 2 bmiTell''' :: (RealFloat a) => a -> a -> String bmiTell''' weight height | bmi <= skinny = "You're underweight, you emo, you!" | bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!" | bmi <= fat = "You're fat! Lose some weight, fatty!" | otherwise = "You're a whale, congratulations!" where bmi = weight / height ^ 2 skinny = 18.5 normal = 25.0 fat = 30.0 bmiTell'''' :: (RealFloat a) => a -> a -> String bmiTell'''' weight height | bmi <= skinny = "You're underweight, you emo, you!" | bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!" | bmi <= fat = "You're fat! Lose some weight, fatty!" | otherwise = "You're a whale, congratulations!" where bmi = weight / height ^ 2 (skinny, normal, fat) = (18.5, 25.0, 30.0) initials :: String -> String -> String initials firstname lastname = [f] ++ ". " ++ [l] ++ "." where (f:_) = firstname (l:_) = lastname calcBmis :: (RealFloat a) => [(a, a)] -> [a] calcBmis xs = [ bmi w h | (w, h) <- xs ] where bmi weight height = weight / height ^ 2 calcBmis' :: (RealFloat a) => [(a, a)] -> [a] calcBmis' xs = [ w / h ^ 2 | (w, h) <- xs ] cylinder :: (RealFloat a) => a -> a -> a cylinder r h = let sideArea = 2 * pi * r * h topArea = pi * r ^ 2 in sideArea + 2 * topArea calcBmis'' :: (RealFloat a) => [(a, a)] -> [a] calcBmis'' xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2] calcBmis''' :: (RealFloat a) => [(a, a)] -> [a] calcBmis''' xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2, bmi >= 25.0] head'' :: [a] -> a head'' [] = error "No head for empty lists!" head'' (x:_) = x head''' :: [a] -> a head''' xs = case xs of [] -> error "No head for empty lists!" (x:_) -> x describeList :: [a] -> String describeList xs = "The list is " ++ case xs of [] -> "empty." [x] -> "a singleton list." xs -> "a longer list." describeList' :: [a] -> String describeList' xs = "The list is " ++ what xs where what [] = "empty." what [x] = "a singleton list." what xs = "a longer list." maximum' :: (Ord a) => [a] -> a maximum' [] = error "maximum of empty list" maximum' [x] = x maximum' (x:xs) | x > maxTail = x | otherwise = maxTail where maxTail = maximum' xs maximum'' :: (Ord a) => [a] -> a maximum'' [] = error "maximum of empty list" maximum'' [x] = x maximum'' (x:xs) = max x (maximum'' xs) replicate' :: (Num i, Ord i) => i -> a -> [a] replicate' n x | n <= 0 = [] | otherwise = x:replicate' (n-1) x take' :: (Num i, Ord i) => i -> [a] -> [a] take' n _ | n <= 0 = [] take' _ [] = [] take' n (x:xs) = x : take' (n-1) xs reverse' :: [a] -> [a] reverse' [] = [] reverse' (x:xs) = reverse' xs ++ [x] repeat' :: a -> [a] repeat' x = x:repeat' x zip' :: [a] -> [b] -> [(a,b)] zip' _ [] = [] zip' [] _ = [] zip' (x:xs) (y:ys) = (x,y):zip' xs ys elem' :: (Eq a) => a -> [a] -> Bool elem' a [] = False elem' a (x:xs) | a == x = True | otherwise = a `elem'` xs quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = let smallerSorted = quicksort [a | a <- xs, a <= x] biggerSorted = quicksort [a | a <- xs, a > x] in smallerSorted ++ [x] ++ biggerSorted multThree :: (Num a) => a -> a -> a -> a multThree x y z = x * y * z compareWithHundred :: (Num a, Ord a) => a -> Ordering compareWithHundred x = compare 100 x compareWithHundred' :: (Num a, Ord a) => a -> Ordering compareWithHundred' = compare 100 divideByTen :: (Floating a) => a -> a divideByTen = (/10) isUpperAlphanum :: Char -> Bool isUpperAlphanum = (`elem` ['A'..'Z']) applyTwice :: (a -> a) -> a -> a applyTwice f x = f (f x) zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith' _ [] _ = [] zipWith' _ _ [] = [] zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys flip' :: (a -> b -> c) -> (b -> a -> c) flip' f = g where g x y = f y x flip'' :: (a -> b -> c) -> b -> a -> c flip'' f y x = f x y map' :: (a -> b) -> [a] -> [b] map' _ [] = [] map' f (x:xs) = f x : map' f xs filter' :: (a -> Bool) -> [a] -> [a] filter' _ [] = [] filter' p (x:xs) | p x = x : filter' p xs | otherwise = filter' p xs quicksort' :: (Ord a) => [a] -> [a] quicksort' [] = [] quicksort' (x:xs) = let smallerSorted = quicksort' (filter (<=x) xs) biggerSorted = quicksort' (filter (>x) xs) in smallerSorted ++ [x] ++ biggerSorted largestDivisible :: (Integral a) => a largestDivisible = head (filter p [100000,99999..]) where p x = x `mod` 3829 == 0 chain :: (Integral a) => a -> [a] chain 1 = [1] chain n | even n = n:chain (n `div` 2) | odd n = n:chain (n*3 + 1) numLongChains :: Int numLongChains = length (filter isLong (map chain [1..100])) where isLong xs = length xs > 15 numLongChains' :: Int numLongChains' = length (filter (\xs -> length xs > 15) (map chain [1..100])) addThree' :: (Num a) => a -> a -> a -> a addThree' x y z = x + y + z addThree'' :: (Num a) => a -> a -> a -> a addThree'' = \x -> \y -> \z -> x + y + z flip''' :: (a -> b -> c) -> b -> a -> c flip''' f = \x y -> f y x sum'' :: (Num a) => [a] -> a sum'' xs = foldl (\acc x -> acc + x) 0 xs sum''' :: (Num a) => [a] -> a sum''' = foldl (+) 0 elem'' :: (Eq a) => a -> [a] -> Bool elem'' y ys = foldl (\acc x -> if x == y then True else acc) False ys map'' :: (a -> b) -> [a] -> [b] map'' f xs = foldr (\x acc -> f x : acc) [] xs map''' :: (a -> b) -> [a] -> [b] map''' f xs = foldl (\acc x -> acc ++ [f x]) [] xs maximum''' :: (Ord a) => [a] -> a maximum''' = foldr1 (\x acc -> if x > acc then x else acc) reverse'' :: [a] -> [a] reverse'' = foldl (\acc x -> x : acc) [] product' :: (Num a) => [a] -> a product' = foldr1 (*) filter'' :: (a -> Bool) -> [a] -> [a] filter'' p = foldr (\x acc -> if p x then x : acc else acc) [] head'''' :: [a] -> a head'''' = foldr1 (\x _ -> x) last' :: [a] -> a last' = foldl1 (\_ x -> x) reverse''' :: [a] -> [a] reverse''' = foldl (flip (:)) [] sqrtSums :: Int sqrtSums = length (takeWhile (<1000) (scanl1 (+) (map sqrt [1..]))) + 1 oddSquareSum :: Integer oddSquareSum = sum (takeWhile (<10000) (filter odd (map (^2) [1..]))) oddSquareSum' :: Integer oddSquareSum' = sum . takeWhile (<10000) . filter odd . map (^2) $ [1..] oddSquareSum'' :: Integer oddSquareSum'' = let oddSquares = filter odd $ map (^2) [1..] belowLimit = takeWhile (<10000) oddSquares in sum belowLimit numUniques :: (Eq a) => [a] -> Int numUniques = length . nub search :: (Eq a) => [a] -> [a] -> Bool search needle haystack = let nlen = length needle in foldl (\acc x -> if take nlen x == needle then True else acc) False (tails haystack) search' :: (Eq a) => [a] -> [a] -> Bool search' needle haystack = let nlen = length needle in foldl (\acc x -> if take nlen x == needle then True else acc) False (inits haystack) encode' :: Int -> String -> String encode' shift msg = let ords = map ord msg shifted = map (+ shift) ords in map chr shifted encode :: Int -> String -> String encode shift msg = map (chr . (+ shift) . ord) msg decode :: Int -> String -> String decode shift msg = encode (negate shift) msg findKey :: (Eq k) => k -> [(k,v)] -> v findKey key xs = snd . head . filter (\(k,v) -> key == k) $ xs findKey' :: (Eq k) => k -> [(k,v)] -> Maybe v findKey' key [] = Nothing findKey' key ((k,v):xs) = if key == k then Just v else findKey' key xs findKey'' :: (Eq k) => k -> [(k,v)] -> Maybe v findKey'' key = foldr (\(k,v) acc -> if key == k then Just v else acc) Nothing fromList' :: (Ord k) => [(k,v)] -> Map.Map k v fromList' = foldr (\(k,v) acc -> Map.insert k v acc) Map.empty fromList'' :: (Ord k) => [(k,v)] -> Map.Map k v fromList'' = foldl (\acc (k,v) -> Map.insert k v acc) Map.empty phoneBookToMap :: (Ord k) => [(k, String)] -> Map.Map k String phoneBookToMap xs = Map.fromListWith (\number1 number2 -> number1 ++ ", " ++ number2) xs phoneBookToMap' :: (Ord k) => [(k, a)] -> Map.Map k [a] phoneBookToMap' xs = Map.fromListWith (++) $ map (\(k,v) -> (k,[v])) xs
leichunfeng/learnyouahaskell
baby.hs
mit
11,961
0
13
3,173
5,865
3,124
2,741
316
3
-- This file is part of HamSql -- -- Copyright 2014-2016 by it's authors. -- Some rights reserved. See COPYING, AUTHORS. module Database.HamSql.Internal.Load where import Control.Exception import Control.Monad import qualified Data.ByteString as B import Data.Char import Data.Frontmatter import Data.List import Data.Maybe import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import Data.Yaml import System.Directory ( doesDirectoryExist , doesFileExist , getDirectoryContents ) import System.FilePath.Posix (combine, dropFileName, takeFileName) import System.IO (stdin) import Database.HamSql.Internal.Utils import Database.HamSql.Setup import Database.YamSql import Database.YamSql.Parser loadSetup :: FilePath -> IO Setup loadSetup filePath = do setup <- readObjectFromFile filePath setup' <- loadSetupSchemas (dropFileName filePath) (initSetupInternal setup) return $ applyTpl setup' where initSetupInternal s' = s' {setupSchemas = removeDuplicates $ setupSchemas s'} -- Tries to loads all defined modules from defined module dirs loadSetupSchemas :: FilePath -> Setup -> IO Setup loadSetupSchemas path s = do schemaData <- loadSchemas path s [] (setupSchemas s) return s {_setupSchemaData = _setupSchemaData s <> Just schemaData} loadSchemas :: FilePath -> Setup -> [Schema] -> [SqlName] -> IO [Schema] loadSchemas _ _ allLoaded [] = return allLoaded loadSchemas path setup loadedSchemas missingSchemas = do schemas <- sequence [ loadSchema (T.unpack $ unsafePlainName schema) | schema <- missingSchemas ] let newDependencyNames = nub . concat $ map (fromMaybe [] . schemaDependencies) schemas let allLoadedSchemas = schemas ++ loadedSchemas let newMissingDepencenyNames = newDependencyNames \\ map schemaName allLoadedSchemas loadSchemas path setup allLoadedSchemas newMissingDepencenyNames where loadSchema :: FilePath -> IO Schema loadSchema schema = do schemaPath <- findSchemaPath schema schemaDirs readSchema schemaPath schemaDirs = map (combine path) (fromMaybe [""] $ setupSchemaDirs setup) findSchemaPath :: FilePath -> [FilePath] -> IO FilePath findSchemaPath schema search = findDir search where findDir [] = err $ "Schema '" <> tshow schema <> "' not found in " <> tshow search findDir (d:ds) = do let dir = combine d schema dirExists <- doesDirectoryExist (dir :: FilePath) if dirExists then return dir else findDir ds catchErrors :: ToJSON a => FilePath -> a -> IO a catchErrors filePath x = do y <- try (forceToJson x) return $ case y of Left (YamsqlException exc) -> err $ "In file '" <> tshow filePath <> "': " <> exc Right _ -> x isConfigDirFile :: FilePath -> Bool isConfigDirFile xs = isAlphaNum (last fn) && head fn /= '.' where fn = takeFileName xs getFilesInDir :: FilePath -> IO [FilePath] getFilesInDir path = do conts <- getDirectoryContents path let ordConts = sort conts fmap (map (combine path)) (filterM doesFileExist' ordConts) where doesFileExist' relName = doesFileExist (combine path relName) selectFilesInDir :: (FilePath -> Bool) -> FilePath -> IO [FilePath] selectFilesInDir ending dir = do dirExists <- doesDirectoryExist dir if not dirExists then return [] else do files <- getFilesInDir dir return $ filter ending files errorCheck :: Text -> Bool -> IO () errorCheck errMsg False = err errMsg errorCheck _ True = return () readSchema :: FilePath -> IO Schema readSchema md = do doesDirectoryExist md >>= errorCheck ("module dir does not exist: " <> tshow md) schemaData <- readObjectFromFile schemaConfig domains <- confDirFiles "domains.d" >>= mapM readObjectFromFile types <- confDirFiles "types.d" >>= mapM readObjectFromFile sequences <- confDirFiles "sequences.d" >>= mapM readObjectFromFile tables <- confDirFiles "tables.d" >>= mapM readObjectFromFile functions <- let ins x s = x {functionBody = Just s} in confDirFiles "functions.d" >>= mapM (readFunctionFromFile ins) let schemaData' = schemaData { _schemaDomains = _schemaDomains schemaData <> presetEmpty domains , _schemaFunctions = _schemaFunctions schemaData <> presetEmpty functions , _schemaSequences = _schemaSequences schemaData <> presetEmpty sequences , _schemaTables = _schemaTables schemaData <> presetEmpty tables , _schemaTypes = _schemaTypes schemaData <> presetEmpty types } return schemaData' where schemaConfig = combine md "schema.yml" confDirFiles confDir = selectFilesInDir isConfigDirFile (combine md confDir) readObjectFromFile :: (FromJSON a, ToJSON a) => FilePath -> IO a readObjectFromFile file = do b <- readYamSqlFile file readObject file b readObject :: (FromJSON a, ToJSON a) => FilePath -> B.ByteString -> IO a readObject file b = catchErrors file $ case decodeEither' b of Left errMsg -> err $ "in yaml-file: " <> tshow file <> ": " <> tshow errMsg Right obj -> obj readFunctionFromFile :: (FromJSON a, ToJSON a) => (a -> Text -> a) -> FilePath -> IO a readFunctionFromFile rpl file = do b <- readYamSqlFile file case parseFrontmatter b of Done body yaml -> do f <- readObject file yaml return $ rpl f (decodeUtf8 body) _ -> readObject file b readYamSqlFile :: FilePath -> IO B.ByteString readYamSqlFile "-" = B.hGetContents stdin readYamSqlFile file = do fileExists <- doesFileExist file unless fileExists $ err $ "Expected file existance: '" <> tshow file <> "'" B.readFile file
hemio-ev/hamsql
src/Database/HamSql/Internal/Load.hs
gpl-3.0
5,666
0
15
1,186
1,714
833
881
137
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.EC2.CancelBundleTask -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Cancels a bundling operation for an instance store-backed Windows -- instance. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CancelBundleTask.html AWS API Reference> for CancelBundleTask. module Network.AWS.EC2.CancelBundleTask ( -- * Creating a Request cancelBundleTask , CancelBundleTask -- * Request Lenses , cbtDryRun , cbtBundleId -- * Destructuring the Response , cancelBundleTaskResponse , CancelBundleTaskResponse -- * Response Lenses , cbtrsBundleTask , cbtrsResponseStatus ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'cancelBundleTask' smart constructor. data CancelBundleTask = CancelBundleTask' { _cbtDryRun :: !(Maybe Bool) , _cbtBundleId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CancelBundleTask' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cbtDryRun' -- -- * 'cbtBundleId' cancelBundleTask :: Text -- ^ 'cbtBundleId' -> CancelBundleTask cancelBundleTask pBundleId_ = CancelBundleTask' { _cbtDryRun = Nothing , _cbtBundleId = pBundleId_ } -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have -- the required permissions, the error response is 'DryRunOperation'. -- Otherwise, it is 'UnauthorizedOperation'. cbtDryRun :: Lens' CancelBundleTask (Maybe Bool) cbtDryRun = lens _cbtDryRun (\ s a -> s{_cbtDryRun = a}); -- | The ID of the bundle task. cbtBundleId :: Lens' CancelBundleTask Text cbtBundleId = lens _cbtBundleId (\ s a -> s{_cbtBundleId = a}); instance AWSRequest CancelBundleTask where type Rs CancelBundleTask = CancelBundleTaskResponse request = postQuery eC2 response = receiveXML (\ s h x -> CancelBundleTaskResponse' <$> (x .@? "bundleInstanceTask") <*> (pure (fromEnum s))) instance ToHeaders CancelBundleTask where toHeaders = const mempty instance ToPath CancelBundleTask where toPath = const "/" instance ToQuery CancelBundleTask where toQuery CancelBundleTask'{..} = mconcat ["Action" =: ("CancelBundleTask" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), "DryRun" =: _cbtDryRun, "BundleId" =: _cbtBundleId] -- | /See:/ 'cancelBundleTaskResponse' smart constructor. data CancelBundleTaskResponse = CancelBundleTaskResponse' { _cbtrsBundleTask :: !(Maybe BundleTask) , _cbtrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CancelBundleTaskResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cbtrsBundleTask' -- -- * 'cbtrsResponseStatus' cancelBundleTaskResponse :: Int -- ^ 'cbtrsResponseStatus' -> CancelBundleTaskResponse cancelBundleTaskResponse pResponseStatus_ = CancelBundleTaskResponse' { _cbtrsBundleTask = Nothing , _cbtrsResponseStatus = pResponseStatus_ } -- | Information about the bundle task. cbtrsBundleTask :: Lens' CancelBundleTaskResponse (Maybe BundleTask) cbtrsBundleTask = lens _cbtrsBundleTask (\ s a -> s{_cbtrsBundleTask = a}); -- | The response status code. cbtrsResponseStatus :: Lens' CancelBundleTaskResponse Int cbtrsResponseStatus = lens _cbtrsResponseStatus (\ s a -> s{_cbtrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/CancelBundleTask.hs
mpl-2.0
4,447
0
13
904
628
376
252
79
1
{- Copyright 2015,2016 Markus Ongyerth This file is part of Monky. Monky 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. Monky 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 Monky. If not, see <http://www.gnu.org/licenses/>. -} {-| Module : Monky.Examples.Alsa Description : Proxy module for backwards compat. See Monky.Examples.Sound.Alsa Maintainer : ongy Stability : testing Portability : Linux -} module Monky.Examples.Alsa {-# DEPRECATED "Use Monky.Examples.Sound.Alsa" #-} ( getVOLHandle , AlsaH ) where import Monky.Examples.Sound.Alsa
Ongy/monky
Monky/Examples/Alsa.hs
lgpl-3.0
1,063
0
4
219
25
18
7
4
0
-- | -- Module : Data.Array.Accelerate.CUDA.CodeGen.Util -- Copyright : [2008..2011] Manuel M T Chakravarty, Gabriele Keller, Sean Lee, Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-partable (GHC extensions) -- module Data.Array.Accelerate.CUDA.CodeGen.Util where import Language.C import Data.Array.Accelerate.CUDA.CodeGen.Data data Direction = Forward | Backward -- Common device functions -- ----------------------- mkIdentity :: [CExpr] -> CExtDecl mkIdentity = mkDeviceFun "identity" (typename "TyOut") [] mkApply :: Int -> [CExpr] -> CExtDecl mkApply argc = mkDeviceFun "apply" (typename "TyOut") $ map (\n -> (typename ("TyIn"++ show n), 'x':show n)) [argc-1,argc-2..0] mkProject :: Direction -> [CExpr] -> CExtDecl mkProject Forward = mkDeviceFun "project" (typename "DimOut") [(typename "DimIn0","x0")] mkProject Backward = mkDeviceFun "project" (typename "DimIn0") [(typename "DimOut","x0")] mkSliceIndex :: [CExpr] -> CExtDecl mkSliceIndex = mkDeviceFun "sliceIndex" (typename "SliceDim") [(typename "Slice","sl"), (typename "CoSlice","co")] mkSliceReplicate :: [CExpr] -> CExtDecl mkSliceReplicate = mkDeviceFun "sliceIndex" (typename "Slice") [(typename "SliceDim","dim")] -- Helper functions -- ---------------- cvar :: String -> CExpr cvar x = CVar (internalIdent x) internalNode ccall :: String -> [CExpr] -> CExpr ccall fn args = CCall (cvar fn) args internalNode typename :: String -> CType typename var = [CTypeDef (internalIdent var) internalNode] fromBool :: Bool -> CExpr fromBool True = CConst $ CIntConst (cInteger 1) internalNode fromBool False = CConst $ CIntConst (cInteger 0) internalNode mkDim :: String -> Int -> CExtDecl mkDim name n = mkTypedef name False False [CTypeDef (internalIdent ("DIM" ++ show n)) internalNode] mkTypedef :: String -> Bool -> Bool -> CType -> CExtDecl mkTypedef var volatile ptr ty = CDeclExt $ CDecl (CStorageSpec (CTypedef internalNode) : [CTypeQual (CVolatQual internalNode) | volatile] ++ map CTypeSpec ty) [(Just (CDeclr (Just (internalIdent var)) [CPtrDeclr [] internalNode | ptr] Nothing [] internalNode), Nothing, Nothing)] internalNode mkShape :: Int -> String -> CExtDecl mkShape d n = mkGlobal [constant,dimension] n where constant = CTypeQual (CAttrQual (CAttr (internalIdent "constant") [] internalNode)) dimension = CTypeSpec (CTypeDef (internalIdent ("DIM" ++ show d)) internalNode) mkGlobal :: [CDeclSpec] -> String -> CExtDecl mkGlobal spec name = CDeclExt (CDecl (CStorageSpec (CStatic internalNode) : spec) [(Just (CDeclr (Just (internalIdent name)) [] Nothing [] internalNode),Nothing,Nothing)] internalNode) mkInitList :: [CExpr] -> CInit mkInitList [] = CInitExpr (CConst (CIntConst (cInteger 0) internalNode)) internalNode mkInitList [x] = CInitExpr x internalNode mkInitList xs = CInitList (map (\e -> ([],CInitExpr e internalNode)) xs) internalNode -- typedef struct { -- ... (volatile?) ty1 (*?) a1; (volatile?) ty0 (*?) a0; -- } var; -- -- NOTE: The Accelerate language uses snoc based tuple projection, so the last -- field of the structure is named 'a' instead of the first. -- mkStruct :: String -> Bool -> Bool -> [CType] -> CExtDecl mkStruct name volatile ptr types = CDeclExt $ CDecl [CStorageSpec (CTypedef internalNode) , CTypeSpec (CSUType (CStruct CStructTag Nothing (Just (zipWith field names types)) [] internalNode) internalNode)] [(Just (CDeclr (Just (internalIdent name)) [] Nothing [] internalNode),Nothing,Nothing)] internalNode where names = reverse . take (length types) $ (enumFrom 0 :: [Int]) field v ty = CDecl ([CTypeQual (CVolatQual internalNode) | volatile] ++ map CTypeSpec ty) [(Just (CDeclr (Just (internalIdent ('a':show v))) [CPtrDeclr [] internalNode | ptr] Nothing [] internalNode), Nothing, Nothing)] internalNode -- typedef struct __attribute__((aligned(n * sizeof(ty)))) { -- ty [x, y, z, w]; -- } var; -- mkTyVector :: String -> Int -> CType -> CExtDecl mkTyVector var n ty = CDeclExt $ CDecl [CStorageSpec (CTypedef internalNode), CTypeSpec (CSUType (CStruct CStructTag Nothing (Just [CDecl (map CTypeSpec ty) fields internalNode]) [CAttr (internalIdent "aligned") [CBinary CMulOp (CConst (CIntConst (cInteger (toInteger n)) internalNode)) (CSizeofType (CDecl (map CTypeSpec ty) [] internalNode) internalNode) internalNode] internalNode] internalNode) internalNode)] [(Just (CDeclr (Just (internalIdent var)) [] Nothing [] internalNode), Nothing, Nothing)] internalNode where fields = take n . flip map "xyzw" $ \f -> (Just (CDeclr (Just (internalIdent [f])) [] Nothing [] internalNode), Nothing, Nothing) -- static inline __attribute__((device)) tyout name(args) -- { -- tyout r = { expr }; -- return r; -- } -- mkDeviceFun :: String -> CType -> [(CType,String)] -> [CExpr] -> CExtDecl mkDeviceFun name tyout args expr = let body = [ CBlockDecl (CDecl (map CTypeSpec tyout) [(Just (CDeclr (Just (internalIdent "r")) [] Nothing [] internalNode), Just (mkInitList expr), Nothing)] internalNode) , CBlockStmt (CReturn (Just (CVar (internalIdent "r") internalNode)) internalNode)] in mkDeviceFun' name tyout args body -- static inline __attribute__((device)) tyout name(args) -- { -- body -- } -- mkDeviceFun' :: String -> CType -> [(CType, String)] -> [CBlockItem] -> CExtDecl mkDeviceFun' name tyout args body = CFDefExt $ CFunDef ([CStorageSpec (CStatic internalNode), CTypeQual (CInlineQual internalNode), CTypeQual (CAttrQual (CAttr (builtinIdent "device") [] internalNode))] ++ map CTypeSpec tyout) (CDeclr (Just (internalIdent name)) [CFunDeclr (Right (argv,False)) [] internalNode] Nothing [] internalNode) [] (CCompound [] body internalNode) internalNode where argv = flip map args $ \(ty,var) -> CDecl (CTypeQual (CConstQual internalNode) : map CTypeSpec ty) [(Just (CDeclr (Just (internalIdent var)) [] Nothing [] internalNode), Nothing, Nothing)] internalNode
wilbowma/accelerate
Data/Array/Accelerate/CUDA/CodeGen/Util.hs
bsd-3-clause
6,198
0
24
1,107
2,108
1,109
999
84
1
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Setup -- Copyright : (c) David Himmelstrup 2005 -- License : BSD-like -- -- Maintainer : lemmih@gmail.com -- Stability : provisional -- Portability : portable -- -- ----------------------------------------------------------------------------- module Distribution.Client.Setup ( globalCommand, GlobalFlags(..), defaultGlobalFlags, globalRepos , configureCommand, ConfigFlags(..), filterConfigureFlags , configureExCommand, ConfigExFlags(..), defaultConfigExFlags , configureExOptions , buildCommand, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..) , replCommand, testCommand, benchmarkCommand , installCommand, InstallFlags(..), installOptions, defaultInstallFlags , listCommand, ListFlags(..) , updateCommand , upgradeCommand , uninstallCommand , infoCommand, InfoFlags(..) , fetchCommand, FetchFlags(..) , freezeCommand, FreezeFlags(..) , getCommand, unpackCommand, GetFlags(..) , checkCommand , formatCommand , uploadCommand, UploadFlags(..) , reportCommand, ReportFlags(..) , runCommand , initCommand, IT.InitFlags(..) , sdistCommand, SDistFlags(..), SDistExFlags(..), ArchiveFormat(..) , win32SelfUpgradeCommand, Win32SelfUpgradeFlags(..) , sandboxCommand, defaultSandboxLocation, SandboxFlags(..) , execCommand, ExecFlags(..) , userConfigCommand, UserConfigFlags(..) , parsePackageArgs --TODO: stop exporting these: , showRepo , parseRepo ) where import Distribution.Client.Types ( Username(..), Password(..), Repo(..), RemoteRepo(..), LocalRepo(..) ) import Distribution.Client.BuildReports.Types ( ReportLevel(..) ) import Distribution.Client.Dependency.Types ( AllowNewer(..), PreSolver(..) ) import qualified Distribution.Client.Init.Types as IT ( InitFlags(..), PackageType(..) ) import Distribution.Client.Targets ( UserConstraint, readUserConstraint ) import Distribution.Utils.NubList ( NubList, toNubList, fromNubList) import Distribution.Simple.Compiler (PackageDB) import Distribution.Simple.Program ( defaultProgramConfiguration ) import Distribution.Simple.Command hiding (boolOpt, boolOpt') import qualified Distribution.Simple.Command as Command import qualified Distribution.Simple.Setup as Cabal import Distribution.Simple.Setup ( ConfigFlags(..), BuildFlags(..), ReplFlags , TestFlags(..), BenchmarkFlags(..) , SDistFlags(..), HaddockFlags(..) , readPackageDbList, showPackageDbList , Flag(..), toFlag, fromFlag, flagToMaybe, flagToList , optionVerbosity, boolOpt, boolOpt', trueArg, falseArg, optionNumJobs ) import Distribution.Simple.InstallDirs ( PathTemplate, InstallDirs(sysconfdir) , toPathTemplate, fromPathTemplate ) import Distribution.Version ( Version(Version), anyVersion, thisVersion ) import Distribution.Package ( PackageIdentifier, packageName, packageVersion, Dependency(..) ) import Distribution.PackageDescription ( RepoKind(..) ) import Distribution.Text ( Text(..), display ) import Distribution.ReadE ( ReadE(..), readP_to_E, succeedReadE ) import qualified Distribution.Compat.ReadP as Parse ( ReadP, readP_to_S, readS_to_P, char, munch1, pfail, sepBy1, (+++) ) import Distribution.Verbosity ( Verbosity, normal ) import Distribution.Simple.Utils ( wrapText, wrapLine ) import Data.Char ( isSpace, isAlphaNum ) import Data.List ( intercalate, deleteFirstsBy ) import Data.Maybe ( listToMaybe, maybeToList, fromMaybe ) #if !MIN_VERSION_base(4,8,0) import Data.Monoid ( Monoid(..) ) #endif import Control.Monad ( liftM ) import System.FilePath ( (</>) ) import Network.URI ( parseAbsoluteURI, uriToString ) -- ------------------------------------------------------------ -- * Global flags -- ------------------------------------------------------------ -- | Flags that apply at the top level, not to any sub-command. data GlobalFlags = GlobalFlags { globalVersion :: Flag Bool, globalNumericVersion :: Flag Bool, globalConfigFile :: Flag FilePath, globalSandboxConfigFile :: Flag FilePath, globalRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers. globalCacheDir :: Flag FilePath, globalLocalRepos :: NubList FilePath, globalLogsDir :: Flag FilePath, globalWorldFile :: Flag FilePath, globalRequireSandbox :: Flag Bool, globalIgnoreSandbox :: Flag Bool } defaultGlobalFlags :: GlobalFlags defaultGlobalFlags = GlobalFlags { globalVersion = Flag False, globalNumericVersion = Flag False, globalConfigFile = mempty, globalSandboxConfigFile = mempty, globalRemoteRepos = mempty, globalCacheDir = mempty, globalLocalRepos = mempty, globalLogsDir = mempty, globalWorldFile = mempty, globalRequireSandbox = Flag False, globalIgnoreSandbox = Flag False } globalCommand :: [Command action] -> CommandUI GlobalFlags globalCommand commands = CommandUI { commandName = "", commandSynopsis = "Command line interface to the Haskell Cabal infrastructure.", commandUsage = \pname -> "See http://www.haskell.org/cabal/ for more information.\n" ++ "\n" ++ "Usage: " ++ pname ++ " [GLOBAL FLAGS] [COMMAND [FLAGS]]\n", commandDescription = Just $ \pname -> let commands' = commands ++ [commandAddAction helpCommandUI undefined] cmdDescs = getNormalCommandDescriptions commands' -- if new commands are added, we want them to appear even if they -- are not included in the custom listing below. Thus, we calculate -- the `otherCmds` list and append it under the `other` category. -- Alternatively, a new testcase could be added that ensures that -- the set of commands listed here is equal to the set of commands -- that are actually available. otherCmds = deleteFirstsBy (==) (map fst cmdDescs) [ "help" , "update" , "install" , "fetch" , "list" , "info" , "user-config" , "get" , "init" , "configure" , "build" , "clean" , "run" , "repl" , "test" , "bench" , "check" , "sdist" , "upload" , "report" , "freeze" , "haddock" , "hscolour" , "copy" , "register" , "sandbox" , "exec" ] maxlen = maximum $ [length name | (name, _) <- cmdDescs] align str = str ++ replicate (maxlen - length str) ' ' startGroup n = " ["++n++"]" par = "" addCmd n = case lookup n cmdDescs of Nothing -> "" Just d -> " " ++ align n ++ " " ++ d addCmdCustom n d = case lookup n cmdDescs of -- make sure that the -- command still exists. Nothing -> "" Just _ -> " " ++ align n ++ " " ++ d in "Commands:\n" ++ unlines ( [ startGroup "global" , addCmd "update" , addCmd "install" , par , addCmd "help" , addCmd "info" , addCmd "list" , addCmd "fetch" , addCmd "user-config" , par , startGroup "package" , addCmd "get" , addCmd "init" , par , addCmd "configure" , addCmd "build" , addCmd "clean" , par , addCmd "run" , addCmd "repl" , addCmd "test" , addCmd "bench" , par , addCmd "check" , addCmd "sdist" , addCmd "upload" , addCmd "report" , par , addCmd "freeze" , addCmd "haddock" , addCmd "hscolour" , addCmd "copy" , addCmd "register" , par , startGroup "sandbox" , addCmd "sandbox" , addCmd "exec" , addCmdCustom "repl" "Open interpreter with access to sandbox packages." ] ++ if null otherCmds then [] else par :startGroup "other" :[addCmd n | n <- otherCmds]) ++ "\n" ++ "For more information about a command use:\n" ++ " " ++ pname ++ " COMMAND --help\n" ++ "or " ++ pname ++ " help COMMAND\n" ++ "\n" ++ "To install Cabal packages from hackage use:\n" ++ " " ++ pname ++ " install foo [--dry-run]\n" ++ "\n" ++ "Occasionally you need to update the list of available packages:\n" ++ " " ++ pname ++ " update\n", commandNotes = Nothing, commandDefaultFlags = mempty, commandOptions = \showOrParseArgs -> (case showOrParseArgs of ShowArgs -> take 6; ParseArgs -> id) [option ['V'] ["version"] "Print version information" globalVersion (\v flags -> flags { globalVersion = v }) trueArg ,option [] ["numeric-version"] "Print just the version number" globalNumericVersion (\v flags -> flags { globalNumericVersion = v }) trueArg ,option [] ["config-file"] "Set an alternate location for the config file" globalConfigFile (\v flags -> flags { globalConfigFile = v }) (reqArgFlag "FILE") ,option [] ["sandbox-config-file"] "Set an alternate location for the sandbox config file (default: './cabal.sandbox.config')" globalConfigFile (\v flags -> flags { globalSandboxConfigFile = v }) (reqArgFlag "FILE") ,option [] ["require-sandbox"] "requiring the presence of a sandbox for sandbox-aware commands" globalRequireSandbox (\v flags -> flags { globalRequireSandbox = v }) (boolOpt' ([], ["require-sandbox"]) ([], ["no-require-sandbox"])) ,option [] ["ignore-sandbox"] "Ignore any existing sandbox" globalIgnoreSandbox (\v flags -> flags { globalIgnoreSandbox = v }) trueArg ,option [] ["remote-repo"] "The name and url for a remote repository" globalRemoteRepos (\v flags -> flags { globalRemoteRepos = v }) (reqArg' "NAME:URL" (toNubList . maybeToList . readRepo) (map showRepo . fromNubList)) ,option [] ["remote-repo-cache"] "The location where downloads from all remote repos are cached" globalCacheDir (\v flags -> flags { globalCacheDir = v }) (reqArgFlag "DIR") ,option [] ["local-repo"] "The location of a local repository" globalLocalRepos (\v flags -> flags { globalLocalRepos = v }) (reqArg' "DIR" (\x -> toNubList [x]) fromNubList) ,option [] ["logs-dir"] "The location to put log files" globalLogsDir (\v flags -> flags { globalLogsDir = v }) (reqArgFlag "DIR") ,option [] ["world-file"] "The location of the world file" globalWorldFile (\v flags -> flags { globalWorldFile = v }) (reqArgFlag "FILE") ] } instance Monoid GlobalFlags where mempty = GlobalFlags { globalVersion = mempty, globalNumericVersion = mempty, globalConfigFile = mempty, globalSandboxConfigFile = mempty, globalRemoteRepos = mempty, globalCacheDir = mempty, globalLocalRepos = mempty, globalLogsDir = mempty, globalWorldFile = mempty, globalRequireSandbox = mempty, globalIgnoreSandbox = mempty } mappend a b = GlobalFlags { globalVersion = combine globalVersion, globalNumericVersion = combine globalNumericVersion, globalConfigFile = combine globalConfigFile, globalSandboxConfigFile = combine globalConfigFile, globalRemoteRepos = combine globalRemoteRepos, globalCacheDir = combine globalCacheDir, globalLocalRepos = combine globalLocalRepos, globalLogsDir = combine globalLogsDir, globalWorldFile = combine globalWorldFile, globalRequireSandbox = combine globalRequireSandbox, globalIgnoreSandbox = combine globalIgnoreSandbox } where combine field = field a `mappend` field b globalRepos :: GlobalFlags -> [Repo] globalRepos globalFlags = remoteRepos ++ localRepos where remoteRepos = [ Repo (Left remote) cacheDir | remote <- fromNubList $ globalRemoteRepos globalFlags , let cacheDir = fromFlag (globalCacheDir globalFlags) </> remoteRepoName remote ] localRepos = [ Repo (Right LocalRepo) local | local <- fromNubList $ globalLocalRepos globalFlags ] -- ------------------------------------------------------------ -- * Config flags -- ------------------------------------------------------------ configureCommand :: CommandUI ConfigFlags configureCommand = (Cabal.configureCommand defaultProgramConfiguration) { commandDefaultFlags = mempty } configureOptions :: ShowOrParseArgs -> [OptionField ConfigFlags] configureOptions = commandOptions configureCommand filterConfigureFlags :: ConfigFlags -> Version -> ConfigFlags filterConfigureFlags flags cabalLibVersion | cabalLibVersion >= Version [1,22,0] [] = flags_latest -- ^ NB: we expect the latest version to be the most common case. | cabalLibVersion < Version [1,3,10] [] = flags_1_3_10 | cabalLibVersion < Version [1,10,0] [] = flags_1_10_0 | cabalLibVersion < Version [1,14,0] [] = flags_1_14_0 | cabalLibVersion < Version [1,18,0] [] = flags_1_18_0 | cabalLibVersion < Version [1,19,1] [] = flags_1_19_0 | cabalLibVersion < Version [1,19,2] [] = flags_1_19_1 | cabalLibVersion < Version [1,21,1] [] = flags_1_20_0 | cabalLibVersion < Version [1,22,0] [] = flags_1_21_0 | otherwise = flags_latest where -- Cabal >= 1.19.1 uses '--dependency' and does not need '--constraint'. flags_latest = flags { configConstraints = [] } -- Cabal < 1.22 doesn't know about '--disable-debug-info'. flags_1_21_0 = flags_latest { configDebugInfo = NoFlag } -- Cabal < 1.21.1 doesn't know about 'disable-relocatable' -- Cabal < 1.21.1 doesn't know about 'enable-profiling' flags_1_20_0 = flags_1_21_0 { configRelocatable = NoFlag , configProf = NoFlag , configProfExe = configProf flags , configProfLib = mappend (configProf flags) (configProfLib flags) , configCoverage = NoFlag , configLibCoverage = configCoverage flags } -- Cabal < 1.19.2 doesn't know about '--exact-configuration' and -- '--enable-library-stripping'. flags_1_19_1 = flags_1_20_0 { configExactConfiguration = NoFlag , configStripLibs = NoFlag } -- Cabal < 1.19.1 uses '--constraint' instead of '--dependency'. flags_1_19_0 = flags_1_19_1 { configDependencies = [] , configConstraints = configConstraints flags } -- Cabal < 1.18.0 doesn't know about --extra-prog-path and --sysconfdir. flags_1_18_0 = flags_1_19_0 { configProgramPathExtra = toNubList [] , configInstallDirs = configInstallDirs_1_18_0} configInstallDirs_1_18_0 = (configInstallDirs flags) { sysconfdir = NoFlag } -- Cabal < 1.14.0 doesn't know about '--disable-benchmarks'. flags_1_14_0 = flags_1_18_0 { configBenchmarks = NoFlag } -- Cabal < 1.10.0 doesn't know about '--disable-tests'. flags_1_10_0 = flags_1_14_0 { configTests = NoFlag } -- Cabal < 1.3.10 does not grok the '--constraints' flag. flags_1_3_10 = flags_1_10_0 { configConstraints = [] } -- ------------------------------------------------------------ -- * Config extra flags -- ------------------------------------------------------------ -- | cabal configure takes some extra flags beyond runghc Setup configure -- data ConfigExFlags = ConfigExFlags { configCabalVersion :: Flag Version, configExConstraints:: [UserConstraint], configPreferences :: [Dependency], configSolver :: Flag PreSolver, configAllowNewer :: Flag AllowNewer } defaultConfigExFlags :: ConfigExFlags defaultConfigExFlags = mempty { configSolver = Flag defaultSolver , configAllowNewer = Flag AllowNewerNone } configureExCommand :: CommandUI (ConfigFlags, ConfigExFlags) configureExCommand = configureCommand { commandDefaultFlags = (mempty, defaultConfigExFlags), commandOptions = \showOrParseArgs -> liftOptions fst setFst (filter ((`notElem` ["constraint", "dependency", "exact-configuration"]) . optionName) $ configureOptions showOrParseArgs) ++ liftOptions snd setSnd (configureExOptions showOrParseArgs) } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) configureExOptions :: ShowOrParseArgs -> [OptionField ConfigExFlags] configureExOptions _showOrParseArgs = [ option [] ["cabal-lib-version"] ("Select which version of the Cabal lib to use to build packages " ++ "(useful for testing).") configCabalVersion (\v flags -> flags { configCabalVersion = v }) (reqArg "VERSION" (readP_to_E ("Cannot parse cabal lib version: "++) (fmap toFlag parse)) (map display . flagToList)) , option [] ["constraint"] "Specify constraints on a package (version, installed/source, flags)" configExConstraints (\v flags -> flags { configExConstraints = v }) (reqArg "CONSTRAINT" (fmap (\x -> [x]) (ReadE readUserConstraint)) (map display)) , option [] ["preference"] "Specify preferences (soft constraints) on the version of a package" configPreferences (\v flags -> flags { configPreferences = v }) (reqArg "CONSTRAINT" (readP_to_E (const "dependency expected") (fmap (\x -> [x]) parse)) (map display)) , optionSolver configSolver (\v flags -> flags { configSolver = v }) , option [] ["allow-newer"] ("Ignore upper bounds in all dependencies or " ++ allowNewerArgument) configAllowNewer (\v flags -> flags { configAllowNewer = v}) (optArg allowNewerArgument (fmap Flag allowNewerParser) (Flag AllowNewerAll) allowNewerPrinter) ] where allowNewerArgument = "DEPS" instance Monoid ConfigExFlags where mempty = ConfigExFlags { configCabalVersion = mempty, configExConstraints= mempty, configPreferences = mempty, configSolver = mempty, configAllowNewer = mempty } mappend a b = ConfigExFlags { configCabalVersion = combine configCabalVersion, configExConstraints= combine configExConstraints, configPreferences = combine configPreferences, configSolver = combine configSolver, configAllowNewer = combine configAllowNewer } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Build flags -- ------------------------------------------------------------ data SkipAddSourceDepsCheck = SkipAddSourceDepsCheck | DontSkipAddSourceDepsCheck deriving Eq data BuildExFlags = BuildExFlags { buildOnly :: Flag SkipAddSourceDepsCheck } buildExOptions :: ShowOrParseArgs -> [OptionField BuildExFlags] buildExOptions _showOrParseArgs = option [] ["only"] "Don't reinstall add-source dependencies (sandbox-only)" buildOnly (\v flags -> flags { buildOnly = v }) (noArg (Flag SkipAddSourceDepsCheck)) : [] buildCommand :: CommandUI (BuildFlags, BuildExFlags) buildCommand = parent { commandDefaultFlags = (commandDefaultFlags parent, mempty), commandOptions = \showOrParseArgs -> liftOptions fst setFst (commandOptions parent showOrParseArgs) ++ liftOptions snd setSnd (buildExOptions showOrParseArgs) } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) parent = Cabal.buildCommand defaultProgramConfiguration instance Monoid BuildExFlags where mempty = BuildExFlags { buildOnly = mempty } mappend a b = BuildExFlags { buildOnly = combine buildOnly } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Repl command -- ------------------------------------------------------------ replCommand :: CommandUI (ReplFlags, BuildExFlags) replCommand = parent { commandDefaultFlags = (commandDefaultFlags parent, mempty), commandOptions = \showOrParseArgs -> liftOptions fst setFst (commandOptions parent showOrParseArgs) ++ liftOptions snd setSnd (buildExOptions showOrParseArgs) } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) parent = Cabal.replCommand defaultProgramConfiguration -- ------------------------------------------------------------ -- * Test command -- ------------------------------------------------------------ testCommand :: CommandUI (TestFlags, BuildFlags, BuildExFlags) testCommand = parent { commandDefaultFlags = (commandDefaultFlags parent, Cabal.defaultBuildFlags, mempty), commandOptions = \showOrParseArgs -> liftOptions get1 set1 (commandOptions parent showOrParseArgs) ++ liftOptions get2 set2 (Cabal.buildOptions progConf showOrParseArgs) ++ liftOptions get3 set3 (buildExOptions showOrParseArgs) } where get1 (a,_,_) = a; set1 a (_,b,c) = (a,b,c) get2 (_,b,_) = b; set2 b (a,_,c) = (a,b,c) get3 (_,_,c) = c; set3 c (a,b,_) = (a,b,c) parent = Cabal.testCommand progConf = defaultProgramConfiguration -- ------------------------------------------------------------ -- * Bench command -- ------------------------------------------------------------ benchmarkCommand :: CommandUI (BenchmarkFlags, BuildFlags, BuildExFlags) benchmarkCommand = parent { commandDefaultFlags = (commandDefaultFlags parent, Cabal.defaultBuildFlags, mempty), commandOptions = \showOrParseArgs -> liftOptions get1 set1 (commandOptions parent showOrParseArgs) ++ liftOptions get2 set2 (Cabal.buildOptions progConf showOrParseArgs) ++ liftOptions get3 set3 (buildExOptions showOrParseArgs) } where get1 (a,_,_) = a; set1 a (_,b,c) = (a,b,c) get2 (_,b,_) = b; set2 b (a,_,c) = (a,b,c) get3 (_,_,c) = c; set3 c (a,b,_) = (a,b,c) parent = Cabal.benchmarkCommand progConf = defaultProgramConfiguration -- ------------------------------------------------------------ -- * Fetch command -- ------------------------------------------------------------ data FetchFlags = FetchFlags { -- fetchOutput :: Flag FilePath, fetchDeps :: Flag Bool, fetchDryRun :: Flag Bool, fetchSolver :: Flag PreSolver, fetchMaxBackjumps :: Flag Int, fetchReorderGoals :: Flag Bool, fetchIndependentGoals :: Flag Bool, fetchShadowPkgs :: Flag Bool, fetchStrongFlags :: Flag Bool, fetchVerbosity :: Flag Verbosity } defaultFetchFlags :: FetchFlags defaultFetchFlags = FetchFlags { -- fetchOutput = mempty, fetchDeps = toFlag True, fetchDryRun = toFlag False, fetchSolver = Flag defaultSolver, fetchMaxBackjumps = Flag defaultMaxBackjumps, fetchReorderGoals = Flag False, fetchIndependentGoals = Flag False, fetchShadowPkgs = Flag False, fetchStrongFlags = Flag False, fetchVerbosity = toFlag normal } fetchCommand :: CommandUI FetchFlags fetchCommand = CommandUI { commandName = "fetch", commandSynopsis = "Downloads packages for later installation.", commandUsage = usageAlternatives "fetch" [ "[FLAGS] PACKAGES" ], commandDescription = Just $ \_ -> "Note that it currently is not possible to fetch the dependencies for a\n" ++ "package in the current directory.\n", commandNotes = Nothing, commandDefaultFlags = defaultFetchFlags, commandOptions = \ showOrParseArgs -> [ optionVerbosity fetchVerbosity (\v flags -> flags { fetchVerbosity = v }) -- , option "o" ["output"] -- "Put the package(s) somewhere specific rather than the usual cache." -- fetchOutput (\v flags -> flags { fetchOutput = v }) -- (reqArgFlag "PATH") , option [] ["dependencies", "deps"] "Resolve and fetch dependencies (default)" fetchDeps (\v flags -> flags { fetchDeps = v }) trueArg , option [] ["no-dependencies", "no-deps"] "Ignore dependencies" fetchDeps (\v flags -> flags { fetchDeps = v }) falseArg , option [] ["dry-run"] "Do not install anything, only print what would be installed." fetchDryRun (\v flags -> flags { fetchDryRun = v }) trueArg ] ++ optionSolver fetchSolver (\v flags -> flags { fetchSolver = v }) : optionSolverFlags showOrParseArgs fetchMaxBackjumps (\v flags -> flags { fetchMaxBackjumps = v }) fetchReorderGoals (\v flags -> flags { fetchReorderGoals = v }) fetchIndependentGoals (\v flags -> flags { fetchIndependentGoals = v }) fetchShadowPkgs (\v flags -> flags { fetchShadowPkgs = v }) fetchStrongFlags (\v flags -> flags { fetchStrongFlags = v }) } -- ------------------------------------------------------------ -- * Freeze command -- ------------------------------------------------------------ data FreezeFlags = FreezeFlags { freezeDryRun :: Flag Bool, freezeTests :: Flag Bool, freezeBenchmarks :: Flag Bool, freezeSolver :: Flag PreSolver, freezeMaxBackjumps :: Flag Int, freezeReorderGoals :: Flag Bool, freezeIndependentGoals :: Flag Bool, freezeShadowPkgs :: Flag Bool, freezeStrongFlags :: Flag Bool, freezeVerbosity :: Flag Verbosity } defaultFreezeFlags :: FreezeFlags defaultFreezeFlags = FreezeFlags { freezeDryRun = toFlag False, freezeTests = toFlag False, freezeBenchmarks = toFlag False, freezeSolver = Flag defaultSolver, freezeMaxBackjumps = Flag defaultMaxBackjumps, freezeReorderGoals = Flag False, freezeIndependentGoals = Flag False, freezeShadowPkgs = Flag False, freezeStrongFlags = Flag False, freezeVerbosity = toFlag normal } freezeCommand :: CommandUI FreezeFlags freezeCommand = CommandUI { commandName = "freeze", commandSynopsis = "Freeze dependencies.", commandDescription = Just $ \_ -> wrapText $ "Calculates a valid set of dependencies and their exact versions. " ++ "If successful, saves the result to the file `cabal.config`.\n" ++ "\n" ++ "The package versions specified in `cabal.config` will be used for " ++ "any future installs.\n" ++ "\n" ++ "An existing `cabal.config` is ignored and overwritten.\n", commandNotes = Nothing, commandUsage = usageFlags "freeze", commandDefaultFlags = defaultFreezeFlags, commandOptions = \ showOrParseArgs -> [ optionVerbosity freezeVerbosity (\v flags -> flags { freezeVerbosity = v }) , option [] ["dry-run"] "Do not freeze anything, only print what would be frozen" freezeDryRun (\v flags -> flags { freezeDryRun = v }) trueArg , option [] ["tests"] "freezing of the dependencies of any tests suites in the package description file." freezeTests (\v flags -> flags { freezeTests = v }) (boolOpt [] []) , option [] ["benchmarks"] "freezing of the dependencies of any benchmarks suites in the package description file." freezeBenchmarks (\v flags -> flags { freezeBenchmarks = v }) (boolOpt [] []) ] ++ optionSolver freezeSolver (\v flags -> flags { freezeSolver = v }) : optionSolverFlags showOrParseArgs freezeMaxBackjumps (\v flags -> flags { freezeMaxBackjumps = v }) freezeReorderGoals (\v flags -> flags { freezeReorderGoals = v }) freezeIndependentGoals (\v flags -> flags { freezeIndependentGoals = v }) freezeShadowPkgs (\v flags -> flags { freezeShadowPkgs = v }) freezeStrongFlags (\v flags -> flags { freezeStrongFlags = v }) } -- ------------------------------------------------------------ -- * Other commands -- ------------------------------------------------------------ updateCommand :: CommandUI (Flag Verbosity) updateCommand = CommandUI { commandName = "update", commandSynopsis = "Updates list of known packages.", commandDescription = Just $ \_ -> "For all known remote repositories, download the package list.\n", commandNotes = Just $ \_ -> relevantConfigValuesText ["remote-repo" ,"remote-repo-cache" ,"local-repo"], commandUsage = usageFlags "update", commandDefaultFlags = toFlag normal, commandOptions = \_ -> [optionVerbosity id const] } upgradeCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags) upgradeCommand = configureCommand { commandName = "upgrade", commandSynopsis = "(command disabled, use install instead)", commandDescription = Nothing, commandUsage = usageFlagsOrPackages "upgrade", commandDefaultFlags = (mempty, mempty, mempty, mempty), commandOptions = commandOptions installCommand } {- cleanCommand :: CommandUI () cleanCommand = makeCommand name shortDesc longDesc emptyFlags options where name = "clean" shortDesc = "Removes downloaded files" longDesc = Nothing emptyFlags = () options _ = [] -} checkCommand :: CommandUI (Flag Verbosity) checkCommand = CommandUI { commandName = "check", commandSynopsis = "Check the package for common mistakes.", commandDescription = Just $ \_ -> wrapText $ "Expects a .cabal package file in the current directory.\n" ++ "\n" ++ "The checks correspond to the requirements to packages on Hackage. " ++ "If no errors and warnings are reported, Hackage will accept this " ++ "package.\n", commandNotes = Nothing, commandUsage = \pname -> "Usage: " ++ pname ++ " check\n", commandDefaultFlags = toFlag normal, commandOptions = \_ -> [] } formatCommand :: CommandUI (Flag Verbosity) formatCommand = CommandUI { commandName = "format", commandSynopsis = "Reformat the .cabal file using the standard style.", commandDescription = Nothing, commandNotes = Nothing, commandUsage = usageAlternatives "format" ["[FILE]"], commandDefaultFlags = toFlag normal, commandOptions = \_ -> [] } uninstallCommand :: CommandUI (Flag Verbosity) uninstallCommand = CommandUI { commandName = "uninstall", commandSynopsis = "Warn about 'uninstall' not being implemented.", commandDescription = Nothing, commandNotes = Nothing, commandUsage = usageAlternatives "uninstall" ["PACKAGES"], commandDefaultFlags = toFlag normal, commandOptions = \_ -> [] } runCommand :: CommandUI (BuildFlags, BuildExFlags) runCommand = CommandUI { commandName = "run", commandSynopsis = "Builds and runs an executable.", commandDescription = Just $ \_ -> wrapText $ "Builds and then runs the specified executable. If no executable is " ++ "specified, but the package contains just one executable, that one " ++ "is built and executed.\n", commandNotes = Nothing, commandUsage = usageAlternatives "run" ["[FLAGS] [EXECUTABLE] [-- EXECUTABLE_FLAGS]"], commandDefaultFlags = mempty, commandOptions = \showOrParseArgs -> liftOptions fst setFst (commandOptions parent showOrParseArgs) ++ liftOptions snd setSnd (buildExOptions showOrParseArgs) } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) parent = Cabal.buildCommand defaultProgramConfiguration -- ------------------------------------------------------------ -- * Report flags -- ------------------------------------------------------------ data ReportFlags = ReportFlags { reportUsername :: Flag Username, reportPassword :: Flag Password, reportVerbosity :: Flag Verbosity } defaultReportFlags :: ReportFlags defaultReportFlags = ReportFlags { reportUsername = mempty, reportPassword = mempty, reportVerbosity = toFlag normal } reportCommand :: CommandUI ReportFlags reportCommand = CommandUI { commandName = "report", commandSynopsis = "Upload build reports to a remote server.", commandDescription = Nothing, commandNotes = Just $ \_ -> "You can store your Hackage login in the ~/.cabal/config file\n", commandUsage = usageAlternatives "report" ["[FLAGS]"], commandDefaultFlags = defaultReportFlags, commandOptions = \_ -> [optionVerbosity reportVerbosity (\v flags -> flags { reportVerbosity = v }) ,option ['u'] ["username"] "Hackage username." reportUsername (\v flags -> flags { reportUsername = v }) (reqArg' "USERNAME" (toFlag . Username) (flagToList . fmap unUsername)) ,option ['p'] ["password"] "Hackage password." reportPassword (\v flags -> flags { reportPassword = v }) (reqArg' "PASSWORD" (toFlag . Password) (flagToList . fmap unPassword)) ] } instance Monoid ReportFlags where mempty = ReportFlags { reportUsername = mempty, reportPassword = mempty, reportVerbosity = mempty } mappend a b = ReportFlags { reportUsername = combine reportUsername, reportPassword = combine reportPassword, reportVerbosity = combine reportVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Get flags -- ------------------------------------------------------------ data GetFlags = GetFlags { getDestDir :: Flag FilePath, getPristine :: Flag Bool, getSourceRepository :: Flag (Maybe RepoKind), getVerbosity :: Flag Verbosity } defaultGetFlags :: GetFlags defaultGetFlags = GetFlags { getDestDir = mempty, getPristine = mempty, getSourceRepository = mempty, getVerbosity = toFlag normal } getCommand :: CommandUI GetFlags getCommand = CommandUI { commandName = "get", commandSynopsis = "Download/Extract a package's source code (repository).", commandDescription = Just $ \_ -> wrapText $ "Creates a local copy of a package's source code. By default it gets " ++ "the source\ntarball and unpacks it in a local subdirectory. " ++ "Alternatively, with -s it will\nget the code from the source " ++ "repository specified by the package.\n", commandNotes = Nothing, commandUsage = usagePackages "get", commandDefaultFlags = defaultGetFlags, commandOptions = \_ -> [ optionVerbosity getVerbosity (\v flags -> flags { getVerbosity = v }) ,option "d" ["destdir"] "Where to place the package source, defaults to the current directory." getDestDir (\v flags -> flags { getDestDir = v }) (reqArgFlag "PATH") ,option "s" ["source-repository"] "Copy the package's source repository (ie git clone, darcs get, etc as appropriate)." getSourceRepository (\v flags -> flags { getSourceRepository = v }) (optArg "[head|this|...]" (readP_to_E (const "invalid source-repository") (fmap (toFlag . Just) parse)) (Flag Nothing) (map (fmap show) . flagToList)) , option [] ["pristine"] ("Unpack the original pristine tarball, rather than updating the " ++ ".cabal file with the latest revision from the package archive.") getPristine (\v flags -> flags { getPristine = v }) trueArg ] } -- 'cabal unpack' is a deprecated alias for 'cabal get'. unpackCommand :: CommandUI GetFlags unpackCommand = getCommand { commandName = "unpack", commandUsage = usagePackages "unpack" } instance Monoid GetFlags where mempty = GetFlags { getDestDir = mempty, getPristine = mempty, getSourceRepository = mempty, getVerbosity = mempty } mappend a b = GetFlags { getDestDir = combine getDestDir, getPristine = combine getPristine, getSourceRepository = combine getSourceRepository, getVerbosity = combine getVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * List flags -- ------------------------------------------------------------ data ListFlags = ListFlags { listInstalled :: Flag Bool, listSimpleOutput :: Flag Bool, listVerbosity :: Flag Verbosity, listPackageDBs :: [Maybe PackageDB] } defaultListFlags :: ListFlags defaultListFlags = ListFlags { listInstalled = Flag False, listSimpleOutput = Flag False, listVerbosity = toFlag normal, listPackageDBs = [] } listCommand :: CommandUI ListFlags listCommand = CommandUI { commandName = "list", commandSynopsis = "List packages matching a search string.", commandDescription = Just $ \_ -> wrapText $ "List all packages, or all packages matching one of the search" ++ " strings.\n" ++ "\n" ++ "If there is a sandbox in the current directory and " ++ "config:ignore-sandbox is False, use the sandbox package database. " ++ "Otherwise, use the package database specified with --package-db. " ++ "If not specified, use the user package database.\n", commandNotes = Nothing, commandUsage = usageAlternatives "list" [ "[FLAGS]" , "[FLAGS] STRINGS"], commandDefaultFlags = defaultListFlags, commandOptions = \_ -> [ optionVerbosity listVerbosity (\v flags -> flags { listVerbosity = v }) , option [] ["installed"] "Only print installed packages" listInstalled (\v flags -> flags { listInstalled = v }) trueArg , option [] ["simple-output"] "Print in a easy-to-parse format" listSimpleOutput (\v flags -> flags { listSimpleOutput = v }) trueArg , option "" ["package-db"] "Use a given package database. May be a specific file, 'global', 'user' or 'clear'." listPackageDBs (\v flags -> flags { listPackageDBs = v }) (reqArg' "DB" readPackageDbList showPackageDbList) ] } instance Monoid ListFlags where mempty = ListFlags { listInstalled = mempty, listSimpleOutput = mempty, listVerbosity = mempty, listPackageDBs = mempty } mappend a b = ListFlags { listInstalled = combine listInstalled, listSimpleOutput = combine listSimpleOutput, listVerbosity = combine listVerbosity, listPackageDBs = combine listPackageDBs } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Info flags -- ------------------------------------------------------------ data InfoFlags = InfoFlags { infoVerbosity :: Flag Verbosity, infoPackageDBs :: [Maybe PackageDB] } defaultInfoFlags :: InfoFlags defaultInfoFlags = InfoFlags { infoVerbosity = toFlag normal, infoPackageDBs = [] } infoCommand :: CommandUI InfoFlags infoCommand = CommandUI { commandName = "info", commandSynopsis = "Display detailed information about a particular package.", commandDescription = Just $ \_ -> wrapText $ "If there is a sandbox in the current directory and " ++ "config:ignore-sandbox is False, use the sandbox package database. " ++ "Otherwise, use the package database specified with --package-db. " ++ "If not specified, use the user package database.\n", commandNotes = Nothing, commandUsage = usageAlternatives "info" ["[FLAGS] PACKAGES"], commandDefaultFlags = defaultInfoFlags, commandOptions = \_ -> [ optionVerbosity infoVerbosity (\v flags -> flags { infoVerbosity = v }) , option "" ["package-db"] "Use a given package database. May be a specific file, 'global', 'user' or 'clear'." infoPackageDBs (\v flags -> flags { infoPackageDBs = v }) (reqArg' "DB" readPackageDbList showPackageDbList) ] } instance Monoid InfoFlags where mempty = InfoFlags { infoVerbosity = mempty, infoPackageDBs = mempty } mappend a b = InfoFlags { infoVerbosity = combine infoVerbosity, infoPackageDBs = combine infoPackageDBs } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Install flags -- ------------------------------------------------------------ -- | Install takes the same flags as configure along with a few extras. -- data InstallFlags = InstallFlags { installDocumentation :: Flag Bool, installHaddockIndex :: Flag PathTemplate, installDryRun :: Flag Bool, installMaxBackjumps :: Flag Int, installReorderGoals :: Flag Bool, installIndependentGoals :: Flag Bool, installShadowPkgs :: Flag Bool, installStrongFlags :: Flag Bool, installReinstall :: Flag Bool, installAvoidReinstalls :: Flag Bool, installOverrideReinstall :: Flag Bool, installUpgradeDeps :: Flag Bool, installOnly :: Flag Bool, installOnlyDeps :: Flag Bool, installRootCmd :: Flag String, installSummaryFile :: NubList PathTemplate, installLogFile :: Flag PathTemplate, installBuildReports :: Flag ReportLevel, installReportPlanningFailure :: Flag Bool, installSymlinkBinDir :: Flag FilePath, installOneShot :: Flag Bool, installNumJobs :: Flag (Maybe Int), installRunTests :: Flag Bool, installOfflineMode :: Flag Bool } defaultInstallFlags :: InstallFlags defaultInstallFlags = InstallFlags { installDocumentation = Flag False, installHaddockIndex = Flag docIndexFile, installDryRun = Flag False, installMaxBackjumps = Flag defaultMaxBackjumps, installReorderGoals = Flag False, installIndependentGoals= Flag False, installShadowPkgs = Flag False, installStrongFlags = Flag False, installReinstall = Flag False, installAvoidReinstalls = Flag False, installOverrideReinstall = Flag False, installUpgradeDeps = Flag False, installOnly = Flag False, installOnlyDeps = Flag False, installRootCmd = mempty, installSummaryFile = mempty, installLogFile = mempty, installBuildReports = Flag NoReports, installReportPlanningFailure = Flag False, installSymlinkBinDir = mempty, installOneShot = Flag False, installNumJobs = mempty, installRunTests = mempty, installOfflineMode = Flag False } where docIndexFile = toPathTemplate ("$datadir" </> "doc" </> "$arch-$os-$compiler" </> "index.html") allowNewerParser :: ReadE AllowNewer allowNewerParser = ReadE $ \s -> case s of "" -> Right AllowNewerNone "False" -> Right AllowNewerNone "True" -> Right AllowNewerAll _ -> case readPToMaybe pkgsParser s of Just pkgs -> Right . AllowNewerSome $ pkgs Nothing -> Left ("Cannot parse the list of packages: " ++ s) where pkgsParser = Parse.sepBy1 parse (Parse.char ',') allowNewerPrinter :: Flag AllowNewer -> [Maybe String] allowNewerPrinter (Flag AllowNewerNone) = [Just "False"] allowNewerPrinter (Flag AllowNewerAll) = [Just "True"] allowNewerPrinter (Flag (AllowNewerSome pkgs)) = [Just . intercalate "," . map display $ pkgs] allowNewerPrinter NoFlag = [] defaultMaxBackjumps :: Int defaultMaxBackjumps = 2000 defaultSolver :: PreSolver defaultSolver = Choose allSolvers :: String allSolvers = intercalate ", " (map display ([minBound .. maxBound] :: [PreSolver])) installCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags) installCommand = CommandUI { commandName = "install", commandSynopsis = "Install packages.", commandUsage = usageAlternatives "install" [ "[FLAGS]" , "[FLAGS] PACKAGES" ], commandDescription = Just $ \_ -> wrapText $ "Installs one or more packages. By default, the installed package" ++ " will be registered in the user's package database or, if a sandbox" ++ " is present in the current directory, inside the sandbox.\n" ++ "\n" ++ "If PACKAGES are specified, downloads and installs those packages." ++ " Otherwise, install the package in the current directory (and/or its" ++ " dependencies) (there must be exactly one .cabal file in the current" ++ " directory).\n" ++ "\n" ++ "When using a sandbox, the flags for `install` only affect the" ++ " current command and have no effect on future commands. (To achieve" ++ " that, `configure` must be used.)\n" ++ " In contrast, without a sandbox, the flags to `install` are saved and" ++ " affect future commands such as `build` and `repl`. See the help for" ++ " `configure` for a list of commands being affected.\n", commandNotes = Just $ \pname -> ( case commandNotes configureCommand of Just desc -> desc pname ++ "\n" Nothing -> "" ) ++ "Examples:\n" ++ " " ++ pname ++ " install " ++ " Package in the current directory\n" ++ " " ++ pname ++ " install foo " ++ " Package from the hackage server\n" ++ " " ++ pname ++ " install foo-1.0 " ++ " Specific version of a package\n" ++ " " ++ pname ++ " install 'foo < 2' " ++ " Constrained package version\n", commandDefaultFlags = (mempty, mempty, mempty, mempty), commandOptions = \showOrParseArgs -> liftOptions get1 set1 (filter ((`notElem` ["constraint", "dependency" , "exact-configuration"]) . optionName) $ configureOptions showOrParseArgs) ++ liftOptions get2 set2 (configureExOptions showOrParseArgs) ++ liftOptions get3 set3 (installOptions showOrParseArgs) ++ liftOptions get4 set4 (haddockOptions showOrParseArgs) } where get1 (a,_,_,_) = a; set1 a (_,b,c,d) = (a,b,c,d) get2 (_,b,_,_) = b; set2 b (a,_,c,d) = (a,b,c,d) get3 (_,_,c,_) = c; set3 c (a,b,_,d) = (a,b,c,d) get4 (_,_,_,d) = d; set4 d (a,b,c,_) = (a,b,c,d) haddockOptions :: ShowOrParseArgs -> [OptionField HaddockFlags] haddockOptions showOrParseArgs = [ opt { optionName = "haddock-" ++ name, optionDescr = [ fmapOptFlags (\(_, lflags) -> ([], map ("haddock-" ++) lflags)) descr | descr <- optionDescr opt] } | opt <- commandOptions Cabal.haddockCommand showOrParseArgs , let name = optionName opt , name `elem` ["hoogle", "html", "html-location" ,"executables", "tests", "benchmarks", "all", "internal", "css" ,"hyperlink-source", "hscolour-css" ,"contents-location"] ] where fmapOptFlags :: (OptFlags -> OptFlags) -> OptDescr a -> OptDescr a fmapOptFlags modify (ReqArg d f p r w) = ReqArg d (modify f) p r w fmapOptFlags modify (OptArg d f p r i w) = OptArg d (modify f) p r i w fmapOptFlags modify (ChoiceOpt xs) = ChoiceOpt [(d, modify f, i, w) | (d, f, i, w) <- xs] fmapOptFlags modify (BoolOpt d f1 f2 r w) = BoolOpt d (modify f1) (modify f2) r w installOptions :: ShowOrParseArgs -> [OptionField InstallFlags] installOptions showOrParseArgs = [ option "" ["documentation"] "building of documentation" installDocumentation (\v flags -> flags { installDocumentation = v }) (boolOpt [] []) , option [] ["doc-index-file"] "A central index of haddock API documentation (template cannot use $pkgid)" installHaddockIndex (\v flags -> flags { installHaddockIndex = v }) (reqArg' "TEMPLATE" (toFlag.toPathTemplate) (flagToList . fmap fromPathTemplate)) , option [] ["dry-run"] "Do not install anything, only print what would be installed." installDryRun (\v flags -> flags { installDryRun = v }) trueArg ] ++ optionSolverFlags showOrParseArgs installMaxBackjumps (\v flags -> flags { installMaxBackjumps = v }) installReorderGoals (\v flags -> flags { installReorderGoals = v }) installIndependentGoals (\v flags -> flags { installIndependentGoals = v }) installShadowPkgs (\v flags -> flags { installShadowPkgs = v }) installStrongFlags (\v flags -> flags { installStrongFlags = v }) ++ [ option [] ["reinstall"] "Install even if it means installing the same version again." installReinstall (\v flags -> flags { installReinstall = v }) (yesNoOpt showOrParseArgs) , option [] ["avoid-reinstalls"] "Do not select versions that would destructively overwrite installed packages." installAvoidReinstalls (\v flags -> flags { installAvoidReinstalls = v }) (yesNoOpt showOrParseArgs) , option [] ["force-reinstalls"] "Reinstall packages even if they will most likely break other installed packages." installOverrideReinstall (\v flags -> flags { installOverrideReinstall = v }) (yesNoOpt showOrParseArgs) , option [] ["upgrade-dependencies"] "Pick the latest version for all dependencies, rather than trying to pick an installed version." installUpgradeDeps (\v flags -> flags { installUpgradeDeps = v }) (yesNoOpt showOrParseArgs) , option [] ["only-dependencies"] "Install only the dependencies necessary to build the given packages" installOnlyDeps (\v flags -> flags { installOnlyDeps = v }) (yesNoOpt showOrParseArgs) , option [] ["dependencies-only"] "A synonym for --only-dependencies" installOnlyDeps (\v flags -> flags { installOnlyDeps = v }) (yesNoOpt showOrParseArgs) , option [] ["root-cmd"] "Command used to gain root privileges, when installing with --global." installRootCmd (\v flags -> flags { installRootCmd = v }) (reqArg' "COMMAND" toFlag flagToList) , option [] ["symlink-bindir"] "Add symlinks to installed executables into this directory." installSymlinkBinDir (\v flags -> flags { installSymlinkBinDir = v }) (reqArgFlag "DIR") , option [] ["build-summary"] "Save build summaries to file (name template can use $pkgid, $compiler, $os, $arch)" installSummaryFile (\v flags -> flags { installSummaryFile = v }) (reqArg' "TEMPLATE" (\x -> toNubList [toPathTemplate x]) (map fromPathTemplate . fromNubList)) , option [] ["build-log"] "Log all builds to file (name template can use $pkgid, $compiler, $os, $arch)" installLogFile (\v flags -> flags { installLogFile = v }) (reqArg' "TEMPLATE" (toFlag.toPathTemplate) (flagToList . fmap fromPathTemplate)) , option [] ["remote-build-reporting"] "Generate build reports to send to a remote server (none, anonymous or detailed)." installBuildReports (\v flags -> flags { installBuildReports = v }) (reqArg "LEVEL" (readP_to_E (const $ "report level must be 'none', " ++ "'anonymous' or 'detailed'") (toFlag `fmap` parse)) (flagToList . fmap display)) , option [] ["report-planning-failure"] "Generate build reports when the dependency solver fails. This is used by the Hackage build bot." installReportPlanningFailure (\v flags -> flags { installReportPlanningFailure = v }) trueArg , option [] ["one-shot"] "Do not record the packages in the world file." installOneShot (\v flags -> flags { installOneShot = v }) (yesNoOpt showOrParseArgs) , option [] ["run-tests"] "Run package test suites during installation." installRunTests (\v flags -> flags { installRunTests = v }) trueArg , optionNumJobs installNumJobs (\v flags -> flags { installNumJobs = v }) , option [] ["offline"] "Don't download packages from the Internet." installOfflineMode (\v flags -> flags { installOfflineMode = v }) (yesNoOpt showOrParseArgs) ] ++ case showOrParseArgs of -- TODO: remove when "cabal install" -- avoids ParseArgs -> [ option [] ["only"] "Only installs the package in the current directory." installOnly (\v flags -> flags { installOnly = v }) trueArg ] _ -> [] instance Monoid InstallFlags where mempty = InstallFlags { installDocumentation = mempty, installHaddockIndex = mempty, installDryRun = mempty, installReinstall = mempty, installAvoidReinstalls = mempty, installOverrideReinstall = mempty, installMaxBackjumps = mempty, installUpgradeDeps = mempty, installReorderGoals = mempty, installIndependentGoals= mempty, installShadowPkgs = mempty, installStrongFlags = mempty, installOnly = mempty, installOnlyDeps = mempty, installRootCmd = mempty, installSummaryFile = mempty, installLogFile = mempty, installBuildReports = mempty, installReportPlanningFailure = mempty, installSymlinkBinDir = mempty, installOneShot = mempty, installNumJobs = mempty, installRunTests = mempty, installOfflineMode = mempty } mappend a b = InstallFlags { installDocumentation = combine installDocumentation, installHaddockIndex = combine installHaddockIndex, installDryRun = combine installDryRun, installReinstall = combine installReinstall, installAvoidReinstalls = combine installAvoidReinstalls, installOverrideReinstall = combine installOverrideReinstall, installMaxBackjumps = combine installMaxBackjumps, installUpgradeDeps = combine installUpgradeDeps, installReorderGoals = combine installReorderGoals, installIndependentGoals= combine installIndependentGoals, installShadowPkgs = combine installShadowPkgs, installStrongFlags = combine installStrongFlags, installOnly = combine installOnly, installOnlyDeps = combine installOnlyDeps, installRootCmd = combine installRootCmd, installSummaryFile = combine installSummaryFile, installLogFile = combine installLogFile, installBuildReports = combine installBuildReports, installReportPlanningFailure = combine installReportPlanningFailure, installSymlinkBinDir = combine installSymlinkBinDir, installOneShot = combine installOneShot, installNumJobs = combine installNumJobs, installRunTests = combine installRunTests, installOfflineMode = combine installOfflineMode } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Upload flags -- ------------------------------------------------------------ data UploadFlags = UploadFlags { uploadCheck :: Flag Bool, uploadUsername :: Flag Username, uploadPassword :: Flag Password, uploadPasswordCmd :: Flag [String], uploadVerbosity :: Flag Verbosity } defaultUploadFlags :: UploadFlags defaultUploadFlags = UploadFlags { uploadCheck = toFlag False, uploadUsername = mempty, uploadPassword = mempty, uploadPasswordCmd = mempty, uploadVerbosity = toFlag normal } uploadCommand :: CommandUI UploadFlags uploadCommand = CommandUI { commandName = "upload", commandSynopsis = "Uploads source packages to Hackage.", commandDescription = Nothing, commandNotes = Just $ \_ -> "You can store your Hackage login in the ~/.cabal/config file\n" ++ relevantConfigValuesText ["username", "password"], commandUsage = \pname -> "Usage: " ++ pname ++ " upload [FLAGS] TARFILES\n", commandDefaultFlags = defaultUploadFlags, commandOptions = \_ -> [optionVerbosity uploadVerbosity (\v flags -> flags { uploadVerbosity = v }) ,option ['c'] ["check"] "Do not upload, just do QA checks." uploadCheck (\v flags -> flags { uploadCheck = v }) trueArg ,option ['u'] ["username"] "Hackage username." uploadUsername (\v flags -> flags { uploadUsername = v }) (reqArg' "USERNAME" (toFlag . Username) (flagToList . fmap unUsername)) ,option ['p'] ["password"] "Hackage password." uploadPassword (\v flags -> flags { uploadPassword = v }) (reqArg' "PASSWORD" (toFlag . Password) (flagToList . fmap unPassword)) ,option ['P'] ["password-command"] "Command to get Hackage password." uploadPasswordCmd (\v flags -> flags { uploadPasswordCmd = v }) (reqArg' "PASSWORD" (Flag . words) (fromMaybe [] . flagToMaybe)) ] } instance Monoid UploadFlags where mempty = UploadFlags { uploadCheck = mempty, uploadUsername = mempty, uploadPassword = mempty, uploadPasswordCmd = mempty, uploadVerbosity = mempty } mappend a b = UploadFlags { uploadCheck = combine uploadCheck, uploadUsername = combine uploadUsername, uploadPassword = combine uploadPassword, uploadPasswordCmd = combine uploadPasswordCmd, uploadVerbosity = combine uploadVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Init flags -- ------------------------------------------------------------ emptyInitFlags :: IT.InitFlags emptyInitFlags = mempty defaultInitFlags :: IT.InitFlags defaultInitFlags = emptyInitFlags { IT.initVerbosity = toFlag normal } initCommand :: CommandUI IT.InitFlags initCommand = CommandUI { commandName = "init", commandSynopsis = "Create a new .cabal package file (interactively).", commandDescription = Just $ \_ -> wrapText $ "Cabalise a project by creating a .cabal, Setup.hs, and " ++ "optionally a LICENSE file.\n" ++ "\n" ++ "Calling init with no arguments (recommended) uses an " ++ "interactive mode, which will try to guess as much as " ++ "possible and prompt you for the rest. Command-line " ++ "arguments are provided for scripting purposes. " ++ "If you don't want interactive mode, be sure to pass " ++ "the -n flag.\n", commandNotes = Nothing, commandUsage = \pname -> "Usage: " ++ pname ++ " init [FLAGS]\n", commandDefaultFlags = defaultInitFlags, commandOptions = \_ -> [ option ['n'] ["non-interactive"] "Non-interactive mode." IT.nonInteractive (\v flags -> flags { IT.nonInteractive = v }) trueArg , option ['q'] ["quiet"] "Do not generate log messages to stdout." IT.quiet (\v flags -> flags { IT.quiet = v }) trueArg , option [] ["no-comments"] "Do not generate explanatory comments in the .cabal file." IT.noComments (\v flags -> flags { IT.noComments = v }) trueArg , option ['m'] ["minimal"] "Generate a minimal .cabal file, that is, do not include extra empty fields. Also implies --no-comments." IT.minimal (\v flags -> flags { IT.minimal = v }) trueArg , option [] ["overwrite"] "Overwrite any existing .cabal, LICENSE, or Setup.hs files without warning." IT.overwrite (\v flags -> flags { IT.overwrite = v }) trueArg , option [] ["package-dir"] "Root directory of the package (default = current directory)." IT.packageDir (\v flags -> flags { IT.packageDir = v }) (reqArgFlag "DIRECTORY") , option ['p'] ["package-name"] "Name of the Cabal package to create." IT.packageName (\v flags -> flags { IT.packageName = v }) (reqArg "PACKAGE" (readP_to_E ("Cannot parse package name: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option [] ["version"] "Initial version of the package." IT.version (\v flags -> flags { IT.version = v }) (reqArg "VERSION" (readP_to_E ("Cannot parse package version: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option [] ["cabal-version"] "Required version of the Cabal library." IT.cabalVersion (\v flags -> flags { IT.cabalVersion = v }) (reqArg "VERSION_RANGE" (readP_to_E ("Cannot parse Cabal version range: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option ['l'] ["license"] "Project license." IT.license (\v flags -> flags { IT.license = v }) (reqArg "LICENSE" (readP_to_E ("Cannot parse license: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option ['a'] ["author"] "Name of the project's author." IT.author (\v flags -> flags { IT.author = v }) (reqArgFlag "NAME") , option ['e'] ["email"] "Email address of the maintainer." IT.email (\v flags -> flags { IT.email = v }) (reqArgFlag "EMAIL") , option ['u'] ["homepage"] "Project homepage and/or repository." IT.homepage (\v flags -> flags { IT.homepage = v }) (reqArgFlag "URL") , option ['s'] ["synopsis"] "Short project synopsis." IT.synopsis (\v flags -> flags { IT.synopsis = v }) (reqArgFlag "TEXT") , option ['c'] ["category"] "Project category." IT.category (\v flags -> flags { IT.category = v }) (reqArg' "CATEGORY" (\s -> toFlag $ maybe (Left s) Right (readMaybe s)) (flagToList . fmap (either id show))) , option ['x'] ["extra-source-file"] "Extra source file to be distributed with tarball." IT.extraSrc (\v flags -> flags { IT.extraSrc = v }) (reqArg' "FILE" (Just . (:[])) (fromMaybe [])) , option [] ["is-library"] "Build a library." IT.packageType (\v flags -> flags { IT.packageType = v }) (noArg (Flag IT.Library)) , option [] ["is-executable"] "Build an executable." IT.packageType (\v flags -> flags { IT.packageType = v }) (noArg (Flag IT.Executable)) , option [] ["main-is"] "Specify the main module." IT.mainIs (\v flags -> flags { IT.mainIs = v }) (reqArgFlag "FILE") , option [] ["language"] "Specify the default language." IT.language (\v flags -> flags { IT.language = v }) (reqArg "LANGUAGE" (readP_to_E ("Cannot parse language: "++) (toFlag `fmap` parse)) (flagToList . fmap display)) , option ['o'] ["expose-module"] "Export a module from the package." IT.exposedModules (\v flags -> flags { IT.exposedModules = v }) (reqArg "MODULE" (readP_to_E ("Cannot parse module name: "++) ((Just . (:[])) `fmap` parse)) (maybe [] (fmap display))) , option [] ["extension"] "Use a LANGUAGE extension (in the other-extensions field)." IT.otherExts (\v flags -> flags { IT.otherExts = v }) (reqArg "EXTENSION" (readP_to_E ("Cannot parse extension: "++) ((Just . (:[])) `fmap` parse)) (maybe [] (fmap display))) , option ['d'] ["dependency"] "Package dependency." IT.dependencies (\v flags -> flags { IT.dependencies = v }) (reqArg "PACKAGE" (readP_to_E ("Cannot parse dependency: "++) ((Just . (:[])) `fmap` parse)) (maybe [] (fmap display))) , option [] ["source-dir"] "Directory containing package source." IT.sourceDirs (\v flags -> flags { IT.sourceDirs = v }) (reqArg' "DIR" (Just . (:[])) (fromMaybe [])) , option [] ["build-tool"] "Required external build tool." IT.buildTools (\v flags -> flags { IT.buildTools = v }) (reqArg' "TOOL" (Just . (:[])) (fromMaybe [])) , optionVerbosity IT.initVerbosity (\v flags -> flags { IT.initVerbosity = v }) ] } where readMaybe s = case reads s of [(x,"")] -> Just x _ -> Nothing -- ------------------------------------------------------------ -- * SDist flags -- ------------------------------------------------------------ -- | Extra flags to @sdist@ beyond runghc Setup sdist -- data SDistExFlags = SDistExFlags { sDistFormat :: Flag ArchiveFormat } deriving Show data ArchiveFormat = TargzFormat | ZipFormat -- | ... deriving (Show, Eq) defaultSDistExFlags :: SDistExFlags defaultSDistExFlags = SDistExFlags { sDistFormat = Flag TargzFormat } sdistCommand :: CommandUI (SDistFlags, SDistExFlags) sdistCommand = Cabal.sdistCommand { commandDefaultFlags = (commandDefaultFlags Cabal.sdistCommand, defaultSDistExFlags), commandOptions = \showOrParseArgs -> liftOptions fst setFst (commandOptions Cabal.sdistCommand showOrParseArgs) ++ liftOptions snd setSnd sdistExOptions } where setFst a (_,b) = (a,b) setSnd b (a,_) = (a,b) sdistExOptions = [option [] ["archive-format"] "archive-format" sDistFormat (\v flags -> flags { sDistFormat = v }) (choiceOpt [ (Flag TargzFormat, ([], ["targz"]), "Produce a '.tar.gz' format archive (default and required for uploading to hackage)") , (Flag ZipFormat, ([], ["zip"]), "Produce a '.zip' format archive") ]) ] instance Monoid SDistExFlags where mempty = SDistExFlags { sDistFormat = mempty } mappend a b = SDistExFlags { sDistFormat = combine sDistFormat } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Win32SelfUpgrade flags -- ------------------------------------------------------------ data Win32SelfUpgradeFlags = Win32SelfUpgradeFlags { win32SelfUpgradeVerbosity :: Flag Verbosity } defaultWin32SelfUpgradeFlags :: Win32SelfUpgradeFlags defaultWin32SelfUpgradeFlags = Win32SelfUpgradeFlags { win32SelfUpgradeVerbosity = toFlag normal } win32SelfUpgradeCommand :: CommandUI Win32SelfUpgradeFlags win32SelfUpgradeCommand = CommandUI { commandName = "win32selfupgrade", commandSynopsis = "Self-upgrade the executable on Windows", commandDescription = Nothing, commandNotes = Nothing, commandUsage = \pname -> "Usage: " ++ pname ++ " win32selfupgrade PID PATH\n", commandDefaultFlags = defaultWin32SelfUpgradeFlags, commandOptions = \_ -> [optionVerbosity win32SelfUpgradeVerbosity (\v flags -> flags { win32SelfUpgradeVerbosity = v}) ] } instance Monoid Win32SelfUpgradeFlags where mempty = Win32SelfUpgradeFlags { win32SelfUpgradeVerbosity = mempty } mappend a b = Win32SelfUpgradeFlags { win32SelfUpgradeVerbosity = combine win32SelfUpgradeVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Sandbox-related flags -- ------------------------------------------------------------ data SandboxFlags = SandboxFlags { sandboxVerbosity :: Flag Verbosity, sandboxSnapshot :: Flag Bool, -- FIXME: this should be an 'add-source'-only -- flag. sandboxLocation :: Flag FilePath } defaultSandboxLocation :: FilePath defaultSandboxLocation = ".cabal-sandbox" defaultSandboxFlags :: SandboxFlags defaultSandboxFlags = SandboxFlags { sandboxVerbosity = toFlag normal, sandboxSnapshot = toFlag False, sandboxLocation = toFlag defaultSandboxLocation } sandboxCommand :: CommandUI SandboxFlags sandboxCommand = CommandUI { commandName = "sandbox", commandSynopsis = "Create/modify/delete a sandbox.", commandDescription = Just $ \pname -> concat [ paragraph $ "Sandboxes are isolated package databases that can be used" ++ " to prevent dependency conflicts that arise when many different" ++ " packages are installed in the same database (i.e. the user's" ++ " database in the home directory)." , paragraph $ "A sandbox in the current directory (created by" ++ " `sandbox init`) will be used instead of the user's database for" ++ " commands such as `install` and `build`. Note that (a directly" ++ " invoked) GHC will not automatically be aware of sandboxes;" ++ " only if called via appropriate " ++ pname ++ " commands, e.g. `repl`, `build`, `exec`." , paragraph $ "Currently, " ++ pname ++ " will not search for a sandbox" ++ " in folders above the current one, so cabal will not see the sandbox" ++ " if you are in a subfolder of a sandboxes." , paragraph "Subcommands:" , headLine "init:" , indentParagraph $ "Initialize a sandbox in the current directory." ++ " An existing package database will not be modified, but settings" ++ " (such as the location of the database) can be modified this way." , headLine "delete:" , indentParagraph $ "Remove the sandbox; deleting all the packages" ++ " installed inside." , headLine "add-source:" , indentParagraph $ "Make one or more local package available in the" ++ " sandbox. PATHS may be relative or absolute." ++ " Typical usecase is when you need" ++ " to make a (temporary) modification to a dependency: You download" ++ " the package into a different directory, make the modification," ++ " and add that directory to the sandbox with `add-source`." , indentParagraph $ "Unless given `--snapshot`, any add-source'd" ++ " dependency that was modified since the last build will be" ++ " re-installed automatically." , headLine "delete-source:" , indentParagraph $ "Remove an add-source dependency; however, this will" ++ " not delete the package(s) that have been installed in the sandbox" ++ " from this dependency. You can either unregister the package(s) via" ++ " `" ++ pname ++ " sandbox hc-pkg unregister` or re-create the" ++ " sandbox (`sandbox delete; sandbox init`)." , headLine "list-sources:" , indentParagraph $ "List the directories of local packages made" ++ " available via `" ++ pname ++ " add-source`." , headLine "hc-pkg:" , indentParagraph $ "Similar to `ghc-pkg`, but for the sandbox package" ++ " database. Can be used to list specific/all packages that are" ++ " installed in the sandbox. For subcommands, see the help for" ++ " ghc-pkg. Affected by the compiler version specified by `configure`." ], commandNotes = Just $ \_ -> relevantConfigValuesText ["require-sandbox" ,"ignore-sandbox"], commandUsage = usageAlternatives "sandbox" [ "init [FLAGS]" , "delete [FLAGS]" , "add-source [FLAGS] PATHS" , "delete-source [FLAGS] PATHS" , "list-sources [FLAGS]" , "hc-pkg [FLAGS] [--] COMMAND [--] [ARGS]" ], commandDefaultFlags = defaultSandboxFlags, commandOptions = \_ -> [ optionVerbosity sandboxVerbosity (\v flags -> flags { sandboxVerbosity = v }) , option [] ["snapshot"] "Take a snapshot instead of creating a link (only applies to 'add-source')" sandboxSnapshot (\v flags -> flags { sandboxSnapshot = v }) trueArg , option [] ["sandbox"] "Sandbox location (default: './.cabal-sandbox')." sandboxLocation (\v flags -> flags { sandboxLocation = v }) (reqArgFlag "DIR") ] } instance Monoid SandboxFlags where mempty = SandboxFlags { sandboxVerbosity = mempty, sandboxSnapshot = mempty, sandboxLocation = mempty } mappend a b = SandboxFlags { sandboxVerbosity = combine sandboxVerbosity, sandboxSnapshot = combine sandboxSnapshot, sandboxLocation = combine sandboxLocation } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * Exec Flags -- ------------------------------------------------------------ data ExecFlags = ExecFlags { execVerbosity :: Flag Verbosity } defaultExecFlags :: ExecFlags defaultExecFlags = ExecFlags { execVerbosity = toFlag normal } execCommand :: CommandUI ExecFlags execCommand = CommandUI { commandName = "exec", commandSynopsis = "Give a command access to the sandbox package repository.", commandDescription = Just $ \pname -> wrapText $ -- TODO: this is too GHC-focused for my liking.. "A directly invoked GHC will not automatically be aware of any" ++ " sandboxes: the GHC_PACKAGE_PATH environment variable controls what" ++ " GHC uses. `" ++ pname ++ " exec` can be used to modify this variable:" ++ " COMMAND will be executed in a modified environment and thereby uses" ++ " the sandbox package database.\n" ++ "\n" ++ "If there is no sandbox, behaves as identity (executing COMMAND).\n" ++ "\n" ++ "Note that other " ++ pname ++ " commands change the environment" ++ " variable appropriately already, so there is no need to wrap those" ++ " in `" ++ pname ++ " exec`. But with `" ++ pname ++ " exec`, the user" ++ " has more control and can, for example, execute custom scripts which" ++ " indirectly execute GHC.\n" ++ "\n" ++ "See `" ++ pname ++ " sandbox`.", commandNotes = Just $ \pname -> "Examples:\n" ++ " Install the executable package pandoc into a sandbox and run it:\n" ++ " " ++ pname ++ " sandbox init\n" ++ " " ++ pname ++ " install pandoc\n" ++ " " ++ pname ++ " exec pandoc foo.md\n\n" ++ " Install the executable package hlint into the user package database\n" ++ " and run it:\n" ++ " " ++ pname ++ " install --user hlint\n" ++ " " ++ pname ++ " exec hlint Foo.hs\n\n" ++ " Execute runghc on Foo.hs with runghc configured to use the\n" ++ " sandbox package database (if a sandbox is being used):\n" ++ " " ++ pname ++ " exec runghc Foo.hs\n", commandUsage = \pname -> "Usage: " ++ pname ++ " exec [FLAGS] [--] COMMAND [--] [ARGS]\n", commandDefaultFlags = defaultExecFlags, commandOptions = \_ -> [ optionVerbosity execVerbosity (\v flags -> flags { execVerbosity = v }) ] } instance Monoid ExecFlags where mempty = ExecFlags { execVerbosity = mempty } mappend a b = ExecFlags { execVerbosity = combine execVerbosity } where combine field = field a `mappend` field b -- ------------------------------------------------------------ -- * UserConfig flags -- ------------------------------------------------------------ data UserConfigFlags = UserConfigFlags { userConfigVerbosity :: Flag Verbosity } instance Monoid UserConfigFlags where mempty = UserConfigFlags { userConfigVerbosity = toFlag normal } mappend a b = UserConfigFlags { userConfigVerbosity = combine userConfigVerbosity } where combine field = field a `mappend` field b userConfigCommand :: CommandUI UserConfigFlags userConfigCommand = CommandUI { commandName = "user-config", commandSynopsis = "Display and update the user's global cabal configuration.", commandDescription = Just $ \_ -> wrapText $ "When upgrading cabal, the set of configuration keys and their default" ++ " values may change. This command provides means to merge the existing" ++ " config in ~/.cabal/config" ++ " (i.e. all bindings that are actually defined and not commented out)" ++ " and the default config of the new version.\n" ++ "\n" ++ "diff: Shows a pseudo-diff of the user's ~/.cabal/config file and" ++ " the default configuration that would be created by cabal if the" ++ " config file did not exist.\n" ++ "update: Applies the pseudo-diff to the configuration that would be" ++ " created by default, and write the result back to ~/.cabal/config.", commandNotes = Nothing, commandUsage = usageAlternatives "user-config" ["diff", "update"], commandDefaultFlags = mempty, commandOptions = \ _ -> [ optionVerbosity userConfigVerbosity (\v flags -> flags { userConfigVerbosity = v }) ] } -- ------------------------------------------------------------ -- * GetOpt Utils -- ------------------------------------------------------------ reqArgFlag :: ArgPlaceHolder -> MkOptDescr (b -> Flag String) (Flag String -> b -> b) b reqArgFlag ad = reqArg ad (succeedReadE Flag) flagToList liftOptions :: (b -> a) -> (a -> b -> b) -> [OptionField a] -> [OptionField b] liftOptions get set = map (liftOption get set) yesNoOpt :: ShowOrParseArgs -> MkOptDescr (b -> Flag Bool) (Flag Bool -> b -> b) b yesNoOpt ShowArgs sf lf = trueArg sf lf yesNoOpt _ sf lf = Command.boolOpt' flagToMaybe Flag (sf, lf) ([], map ("no-" ++) lf) sf lf optionSolver :: (flags -> Flag PreSolver) -> (Flag PreSolver -> flags -> flags) -> OptionField flags optionSolver get set = option [] ["solver"] ("Select dependency solver to use (default: " ++ display defaultSolver ++ "). Choices: " ++ allSolvers ++ ", where 'choose' chooses between 'topdown' and 'modular' based on compiler version.") get set (reqArg "SOLVER" (readP_to_E (const $ "solver must be one of: " ++ allSolvers) (toFlag `fmap` parse)) (flagToList . fmap display)) optionSolverFlags :: ShowOrParseArgs -> (flags -> Flag Int ) -> (Flag Int -> flags -> flags) -> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags) -> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags) -> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags) -> (flags -> Flag Bool ) -> (Flag Bool -> flags -> flags) -> [OptionField flags] optionSolverFlags showOrParseArgs getmbj setmbj getrg setrg _getig _setig getsip setsip getstrfl setstrfl = [ option [] ["max-backjumps"] ("Maximum number of backjumps allowed while solving (default: " ++ show defaultMaxBackjumps ++ "). Use a negative number to enable unlimited backtracking. Use 0 to disable backtracking completely.") getmbj setmbj (reqArg "NUM" (readP_to_E ("Cannot parse number: "++) (fmap toFlag (Parse.readS_to_P reads))) (map show . flagToList)) , option [] ["reorder-goals"] "Try to reorder goals according to certain heuristics. Slows things down on average, but may make backtracking faster for some packages." getrg setrg (yesNoOpt showOrParseArgs) -- TODO: Disabled for now because it does not work as advertised (yet). {- , option [] ["independent-goals"] "Treat several goals on the command line as independent. If several goals depend on the same package, different versions can be chosen." getig setig (yesNoOpt showOrParseArgs) -} , option [] ["shadow-installed-packages"] "If multiple package instances of the same version are installed, treat all but one as shadowed." getsip setsip (yesNoOpt showOrParseArgs) , option [] ["strong-flags"] "Do not defer flag choices (this used to be the default in cabal-install <= 1.20)." getstrfl setstrfl (yesNoOpt showOrParseArgs) ] usageFlagsOrPackages :: String -> String -> String usageFlagsOrPackages name pname = "Usage: " ++ pname ++ " " ++ name ++ " [FLAGS]\n" ++ " or: " ++ pname ++ " " ++ name ++ " [PACKAGES]\n" usagePackages :: String -> String -> String usagePackages name pname = "Usage: " ++ pname ++ " " ++ name ++ " [PACKAGES]\n" usageFlags :: String -> String -> String usageFlags name pname = "Usage: " ++ pname ++ " " ++ name ++ " [FLAGS]\n" --TODO: do we want to allow per-package flags? parsePackageArgs :: [String] -> Either String [Dependency] parsePackageArgs = parsePkgArgs [] where parsePkgArgs ds [] = Right (reverse ds) parsePkgArgs ds (arg:args) = case readPToMaybe parseDependencyOrPackageId arg of Just dep -> parsePkgArgs (dep:ds) args Nothing -> Left $ show arg ++ " is not valid syntax for a package name or" ++ " package dependency." readPToMaybe :: Parse.ReadP a a -> String -> Maybe a readPToMaybe p str = listToMaybe [ r | (r,s) <- Parse.readP_to_S p str , all isSpace s ] parseDependencyOrPackageId :: Parse.ReadP r Dependency parseDependencyOrPackageId = parse Parse.+++ liftM pkgidToDependency parse where pkgidToDependency :: PackageIdentifier -> Dependency pkgidToDependency p = case packageVersion p of Version [] _ -> Dependency (packageName p) anyVersion version -> Dependency (packageName p) (thisVersion version) showRepo :: RemoteRepo -> String showRepo repo = remoteRepoName repo ++ ":" ++ uriToString id (remoteRepoURI repo) [] readRepo :: String -> Maybe RemoteRepo readRepo = readPToMaybe parseRepo parseRepo :: Parse.ReadP r RemoteRepo parseRepo = do name <- Parse.munch1 (\c -> isAlphaNum c || c `elem` "_-.") _ <- Parse.char ':' uriStr <- Parse.munch1 (\c -> isAlphaNum c || c `elem` "+-=._/*()@'$:;&!?~") uri <- maybe Parse.pfail return (parseAbsoluteURI uriStr) return $ RemoteRepo { remoteRepoName = name, remoteRepoURI = uri } -- ------------------------------------------------------------ -- * Helpers for Documentation -- ------------------------------------------------------------ headLine :: String -> String headLine = unlines . map unwords . wrapLine 79 . words paragraph :: String -> String paragraph = (++"\n") . unlines . map unwords . wrapLine 79 . words indentParagraph :: String -> String indentParagraph = unlines . map ((" "++).unwords) . wrapLine 77 . words relevantConfigValuesText :: [String] -> String relevantConfigValuesText vs = "Relevant global configuration keys:\n" ++ concat [" " ++ v ++ "\n" |v <- vs]
Helkafen/cabal
cabal-install/Distribution/Client/Setup.hs
bsd-3-clause
86,289
0
37
24,085
17,818
10,049
7,769
1,676
5
------------------------------------------------------------------------------------- -- | -- Copyright : (c) Hans Hoglund 2012 -- -- License : BSD-style -- -- Maintainer : hans@hanshoglund.se -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------------- module Data.Music.MusicXml.Write ( WriteMusicXml(..) ) where import Text.XML.Light (Element) class WriteMusicXml a where write :: a -> [Element]
FranklinChen/musicxml2
src/Data/Music/MusicXml/Write.hs
bsd-3-clause
506
0
8
72
60
41
19
5
0
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN" "http://java.sun.com/products/javahelp/helpset_1_0.dtd"> <helpset version="1.0"> <title>Process Dashboard</title> <maps> <mapref location="Map.xml"/> <homeID>QuickOverview</homeID> </maps> <view mergetype="javax.help.UniteAppendMerge"> <name>TOC</name> <label>Process Dashboard Help TOC</label> <type>javax.help.TOCView</type> <data>TOC.xml</data> </view> <view> <name>Index</name> <label>Process Dashboard Help Index</label> <type>javax.help.IndexView</type> <data>Index.xml</data> </view> <view> <name>Search</name> <label>Process Dashboard Help Word Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch</data> </view> </helpset>
superzadeh/processdash
Templates/help/PSPDash.hs
gpl-3.0
970
69
56
186
376
190
186
-1
-1
import qualified Data.Vector as U import Data.Bits main = print . U.sum . U.takeWhile (< (7::Int)). U.enumFromTo 1 $ 10000000 -- U.replicate 1000000 $ (7 :: Int) -- gets removed entirely!
hvr/vector
old-testsuite/microsuite/takeWhile.hs
bsd-3-clause
199
0
10
42
59
34
25
3
1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, PatternGuards #-} module Idris.Core.Typecheck where import Control.Monad.State import Debug.Trace import qualified Data.Vector.Unboxed as V (length) import Idris.Core.TT import Idris.Core.Evaluate -- To check conversion, normalise each term wrt the current environment. -- Since we haven't converted everything to de Bruijn indices yet, we'll have to -- deal with alpha conversion - we do this by making each inner term de Bruijn -- indexed with 'finalise' convertsC :: Context -> Env -> Term -> Term -> StateT UCs TC () convertsC ctxt env x y = do let hs = map fst (filter isHole env) c1 <- convEq ctxt hs x y if c1 then return () else do c2 <- convEq ctxt hs (finalise (normalise ctxt env x)) (finalise (normalise ctxt env y)) if c2 then return () else lift $ tfail (CantConvert (finalise (normalise ctxt env x)) (finalise (normalise ctxt env y)) (errEnv env)) converts :: Context -> Env -> Term -> Term -> TC () converts ctxt env x y = let hs = map fst (filter isHole env) in case convEq' ctxt hs x y of OK True -> return () _ -> case convEq' ctxt hs (finalise (normalise ctxt env x)) (finalise (normalise ctxt env y)) of OK True -> return () _ -> tfail (CantConvert (finalise (normalise ctxt env x)) (finalise (normalise ctxt env y)) (errEnv env)) isHole (n, Hole _) = True isHole _ = False errEnv = map (\(x, b) -> (x, binderTy b)) isType :: Context -> Env -> Term -> TC () isType ctxt env tm = isType' (normalise ctxt env tm) where isType' tm | isUniverse tm = return () | otherwise = fail (showEnv env tm ++ " is not a Type") recheck :: Context -> Env -> Raw -> Term -> TC (Term, Type, UCs) recheck = recheck_borrowing False [] recheck_borrowing :: Bool -> [Name] -> Context -> Env -> Raw -> Term -> TC (Term, Type, UCs) recheck_borrowing uniq_check bs ctxt env tm orig = let v = next_tvar ctxt in case runStateT (check' False ctxt env tm) (v, []) of -- holes banned Error (IncompleteTerm _) -> Error $ IncompleteTerm orig Error e -> Error e OK ((tm, ty), constraints) -> do when uniq_check $ checkUnique bs ctxt env tm return (tm, ty, constraints) check :: Context -> Env -> Raw -> TC (Term, Type) check ctxt env tm = evalStateT (check' True ctxt env tm) (0, []) -- Holes allowed check' :: Bool -> Context -> Env -> Raw -> StateT UCs TC (Term, Type) check' holes ctxt env top = chk (TType (UVar (-5))) env top where smaller (UType NullType) _ = UType NullType smaller _ (UType NullType) = UType NullType smaller (UType u) _ = UType u smaller _ (UType u) = UType u smaller x _ = x astate | holes = MaybeHoles | otherwise = Complete chk :: Type -> -- uniqueness level Env -> Raw -> StateT UCs TC (Term, Type) chk u env (Var n) | Just (i, ty) <- lookupTyEnv n env = return (P Bound n ty, ty) -- If we're elaborating, we don't want the private names; if we're -- checking an already elaborated term, we do | [P nt n' ty] <- lookupP_all (not holes) False n ctxt = return (P nt n' ty, ty) -- If the names are ambiguous, require it to be fully qualified | [P nt n' ty] <- lookupP_all (not holes) True n ctxt = return (P nt n' ty, ty) | otherwise = do lift $ tfail $ NoSuchVariable n chk u env ap@(RApp f RType) | not holes -- special case to reduce constraintss = do (fv, fty) <- chk u env f let fty' = case uniqueBinders (map fst env) (finalise fty) of ty@(Bind x (Pi i s k) t) -> ty _ -> uniqueBinders (map fst env) $ case hnf ctxt env fty of ty@(Bind x (Pi i s k) t) -> ty _ -> normalise ctxt env fty case fty' of Bind x (Pi i (TType v') k) t -> do (v, cs) <- get put (v+1, ULT (UVar v) v' : cs) let apty = simplify initContext env (Bind x (Let (TType v') (TType (UVar v))) t) return (App Complete fv (TType (UVar v)), apty) Bind x (Pi i s k) t -> do (av, aty) <- chk u env RType convertsC ctxt env aty s let apty = simplify initContext env (Bind x (Let aty av) t) return (App astate fv av, apty) t -> lift $ tfail $ NonFunctionType fv fty chk u env ap@(RApp f a) = do (fv, fty) <- chk u env f let fty' = case uniqueBinders (map fst env) (finalise fty) of ty@(Bind x (Pi i s k) t) -> ty _ -> uniqueBinders (map fst env) $ case hnf ctxt env fty of ty@(Bind x (Pi i s k) t) -> ty _ -> normalise ctxt env fty (av, aty) <- chk u env a case fty' of Bind x (Pi i s k) t -> do convertsC ctxt env aty s let apty = simplify initContext env (Bind x (Let aty av) t) return (App astate fv av, apty) t -> lift $ tfail $ NonFunctionType fv fty chk u env RType | holes = return (TType (UVal 0), TType (UVal 0)) | otherwise = do (v, cs) <- get let c = ULT (UVar v) (UVar (v+1)) put (v+2, (c:cs)) return (TType (UVar v), TType (UVar (v+1))) chk u env (RUType un) | holes = return (UType un, TType (UVal 0)) | otherwise = do -- TODO! Issue #1715 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1715 -- (v, cs) <- get -- let c = ULT (UVar v) (UVar (v+1)) -- put (v+2, (c:cs)) -- return (TType (UVar v), TType (UVar (v+1))) return (UType un, TType (UVal 0)) chk u env (RConstant Forgot) = return (Erased, Erased) chk u env (RConstant c) = return (Constant c, constType c) where constType (I _) = Constant (AType (ATInt ITNative)) constType (BI _) = Constant (AType (ATInt ITBig)) constType (Fl _) = Constant (AType ATFloat) constType (Ch _) = Constant (AType (ATInt ITChar)) constType (Str _) = Constant StrType constType (B8 _) = Constant (AType (ATInt (ITFixed IT8))) constType (B16 _) = Constant (AType (ATInt (ITFixed IT16))) constType (B32 _) = Constant (AType (ATInt (ITFixed IT32))) constType (B64 _) = Constant (AType (ATInt (ITFixed IT64))) constType TheWorld = Constant WorldType constType Forgot = Erased constType _ = TType (UVal 0) chk u env (RForce t) = do (_, ty) <- chk u env t return (Erased, ty) chk u env (RBind n (Pi i s k) t) = do (sv, st) <- chk u env s (v, cs) <- get (kv, kt) <- chk u env k -- no need to validate these constraints, they are independent put (v+1, cs) let maxu = UVar v (tv, tt) <- chk st ((n, Pi i sv kv) : env) t case (normalise ctxt env st, normalise ctxt env tt) of (TType su, TType tu) -> do when (not holes) $ do (v, cs) <- get put (v, ULE su maxu : ULE tu maxu : cs) let k' = TType (UVar v) `smaller` st `smaller` kv `smaller` u return (Bind n (Pi i (uniqueBinders (map fst env) sv) k') (pToV n tv), k') (un, un') -> let k' = st `smaller` kv `smaller` un `smaller` un' `smaller` u in return (Bind n (Pi i (uniqueBinders (map fst env) sv) k') (pToV n tv), k') where mkUniquePi kv (Bind n (Pi i s k) sc) = let k' = smaller kv k in Bind n (Pi i s k') (mkUniquePi k' sc) mkUniquePi kv (Bind n (Lam t) sc) = Bind n (Lam (mkUniquePi kv t)) (mkUniquePi kv sc) mkUniquePi kv (Bind n (Let t v) sc) = Bind n (Let (mkUniquePi kv t) v) (mkUniquePi kv sc) mkUniquePi kv t = t -- Kind of the whole thing is the kind of the most unique thing -- in the environment (because uniqueness taints everything...) mostUnique [] k = k mostUnique (Pi _ _ pk : es) k = mostUnique es (smaller pk k) mostUnique (_ : es) k = mostUnique es k chk u env (RBind n b sc) = do (b', bt') <- checkBinder b (scv, sct) <- chk (smaller bt' u) ((n, b'):env) sc discharge n b' bt' (pToV n scv) (pToV n sct) where checkBinder (Lam t) = do (tv, tt) <- chk u env t let tv' = normalise ctxt env tv let tt' = normalise ctxt env tt lift $ isType ctxt env tt' return (Lam tv, tt') checkBinder (Let t v) = do (tv, tt) <- chk u env t (vv, vt) <- chk u env v let tv' = normalise ctxt env tv let tt' = normalise ctxt env tt convertsC ctxt env vt tv lift $ isType ctxt env tt' return (Let tv vv, tt') checkBinder (NLet t v) = do (tv, tt) <- chk u env t (vv, vt) <- chk u env v let tv' = normalise ctxt env tv let tt' = normalise ctxt env tt convertsC ctxt env vt tv lift $ isType ctxt env tt' return (NLet tv vv, tt') checkBinder (Hole t) | not holes = lift $ tfail (IncompleteTerm undefined) | otherwise = do (tv, tt) <- chk u env t let tv' = normalise ctxt env tv let tt' = normalise ctxt env tt lift $ isType ctxt env tt' return (Hole tv, tt') checkBinder (GHole i ns t) = do (tv, tt) <- chk u env t let tv' = normalise ctxt env tv let tt' = normalise ctxt env tt lift $ isType ctxt env tt' return (GHole i ns tv, tt') checkBinder (Guess t v) | not holes = lift $ tfail (IncompleteTerm undefined) | otherwise = do (tv, tt) <- chk u env t (vv, vt) <- chk u env v let tv' = normalise ctxt env tv let tt' = normalise ctxt env tt convertsC ctxt env vt tv lift $ isType ctxt env tt' return (Guess tv vv, tt') checkBinder (PVar t) = do (tv, tt) <- chk u env t let tv' = normalise ctxt env tv let tt' = normalise ctxt env tt lift $ isType ctxt env tt' -- Normalised version, for erasure purposes (it's easier -- to tell if it's a collapsible variable) return (PVar tv, tt') checkBinder (PVTy t) = do (tv, tt) <- chk u env t let tv' = normalise ctxt env tv let tt' = normalise ctxt env tt lift $ isType ctxt env tt' return (PVTy tv, tt') discharge n (Lam t) bt scv sct = return (Bind n (Lam t) scv, Bind n (Pi Nothing t bt) sct) discharge n (Pi i t k) bt scv sct = return (Bind n (Pi i t k) scv, sct) discharge n (Let t v) bt scv sct = return (Bind n (Let t v) scv, Bind n (Let t v) sct) discharge n (NLet t v) bt scv sct = return (Bind n (NLet t v) scv, Bind n (Let t v) sct) discharge n (Hole t) bt scv sct = return (Bind n (Hole t) scv, sct) discharge n (GHole i ns t) bt scv sct = return (Bind n (GHole i ns t) scv, sct) discharge n (Guess t v) bt scv sct = return (Bind n (Guess t v) scv, sct) discharge n (PVar t) bt scv sct = return (Bind n (PVar t) scv, Bind n (PVTy t) sct) discharge n (PVTy t) bt scv sct = return (Bind n (PVTy t) scv, sct) -- Number of times a name can be used data UniqueUse = Never -- no more times | Once -- at most once more | LendOnly -- only under 'lend' | Many -- unlimited deriving Eq -- If any binders are of kind 'UniqueType' or 'AllTypes' and the name appears -- in the scope more than once, this is an error. checkUnique :: [Name] -> Context -> Env -> Term -> TC () checkUnique borrowed ctxt env tm = evalStateT (chkBinders env (explicitNames tm)) [] where isVar (P _ _ _) = True isVar (V _) = True isVar _ = False chkBinders :: Env -> Term -> StateT [(Name, (UniqueUse, Universe))] TC () chkBinders env (V i) | length env > i = chkName (fst (env!!i)) chkBinders env (P _ n _) = chkName n -- 'lending' a unique or nulltype variable doesn't count as a use, -- but we still can't lend something that's already been used. chkBinders env (App _ (App _ (P _ (NS (UN lend) [owner]) _) t) a) | isVar a && owner == txt "Ownership" && (lend == txt "lend" || lend == txt "Read") = do chkBinders env t -- Check the type normally st <- get -- Remove the 'LendOnly' names from the unusable set put (filter (\(n, (ok, _)) -> ok /= LendOnly) st) chkBinders env a put st -- Reset the old state after checking the argument chkBinders env (App _ f a) = do chkBinders env f; chkBinders env a chkBinders env (Bind n b t) = do chkBinderName env n b st <- get case b of Let t v -> chkBinders env v _ -> return () chkBinders ((n, b) : env) t chkBinders env t = return () chkBinderName :: Env -> Name -> Binder Term -> StateT [(Name, (UniqueUse, Universe))] TC () chkBinderName env n b = do let rawty = forgetEnv (map fst env) (binderTy b) (_, kind) <- lift $ check ctxt env rawty -- FIXME: Cache in binder? -- Issue #1714 on the issue tracker -- https://github.com/idris-lang/Idris-dev/issues/1714 case kind of UType UniqueType -> do ns <- get if n `elem` borrowed then put ((n, (LendOnly, NullType)) : ns) else put ((n, (Once, UniqueType)) : ns) UType NullType -> do ns <- get put ((n, (Many, NullType)) : ns) UType AllTypes -> do ns <- get put ((n, (Once, AllTypes)) : ns) _ -> return () chkName n = do ns <- get case lookup n ns of Nothing -> return () Just (Many, k) -> return () Just (Never, k) -> lift $ tfail (UniqueError k n) Just (LendOnly, k) -> lift $ tfail (UniqueError k n) Just (Once, k) -> put ((n, (Never, k)) : filter (\x -> fst x /= n) ns)
ExNexu/Idris-dev
src/Idris/Core/Typecheck.hs
bsd-3-clause
16,213
0
26
6,787
6,053
2,983
3,070
300
53
{-# LANGUAGE Safe #-} -- | Import unsafe module Unsafe.Coerce to make sure it fails module Main where import Unsafe.Coerce f :: Int f = 2 main :: IO () main = putStrLn $ "X is: " ++ show f
urbanslug/ghc
testsuite/tests/safeHaskell/unsafeLibs/BadImport07.hs
bsd-3-clause
193
0
6
44
47
27
20
7
1
{-# LANGUAGE TemplateHaskell #-} module T5126 where import Language.Haskell.TH import Language.Haskell.TH.Syntax f :: Q [Dec] f = [d| x2 :: $(conT ''Int) x2 = undefined |]
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/th/T5126.hs
bsd-3-clause
198
0
6
52
38
26
12
9
1
import Control.Monad.Random import Test.Hspec import Game.Game.Poker import Game.Implement.Card import Game.Implement.Card.Standard import Game.Implement.Card.Standard.Poker allHandsCount :: Int allHandsCount = length allPossibleHands allHandsCountExpected :: Int allHandsCountExpected = 2598960 allRoyalFlushCountExpected :: Int allRoyalFlushCountExpected = 4 allStraightFlushCountExpected :: Int allStraightFlushCountExpected = 36 allFourOfAKindCountExpected :: Int allFourOfAKindCountExpected = 624 allFullHouseCountExpected :: Int allFullHouseCountExpected = 3744 allFlushCountExpected :: Int allFlushCountExpected = 5108 allStraightCountExpected :: Int allStraightCountExpected = 10200 allThreeOfAKindCountExpected :: Int allThreeOfAKindCountExpected = 54912 allTwoPairCountExpected :: Int allTwoPairCountExpected = 123552 allPairCountExpected :: Int allPairCountExpected = 1098240 allHighCardCountExpected :: Int allHighCardCountExpected = 1302540 royalFlush :: [PlayingCard] royalFlush = [PlayingCard Ace Hearts, PlayingCard Queen Hearts, PlayingCard King Hearts, PlayingCard Jack Hearts, PlayingCard Ten Hearts] royalFlushNot :: [PlayingCard] royalFlushNot = [PlayingCard Ace Hearts, PlayingCard Queen Hearts, PlayingCard Eight Hearts, PlayingCard Jack Hearts, PlayingCard Ten Hearts] drawDeck :: [PlayingCard] drawDeck = [PlayingCard Five Diamonds, PlayingCard Seven Clubs, PlayingCard Two Spades, PlayingCard King Spades, PlayingCard King Hearts, PlayingCard Ace Diamonds, PlayingCard Seven Diamonds, PlayingCard Three Clubs, PlayingCard Four Clubs] drawDeckSizes :: [Int] drawDeckSizes = [1,4,2] drawDeckSizesFail :: [Int] drawDeckSizesFail = [5,9] drawDeckSizesFailNeg :: [Int] drawDeckSizesFailNeg = [-3,4] drawDeckExpectedOutput :: Maybe ([[PlayingCard]],[PlayingCard]) drawDeckExpectedOutput = Just ([[PlayingCard Five Diamonds], [PlayingCard Seven Clubs, PlayingCard Two Spades, PlayingCard King Spades, PlayingCard King Hearts], [PlayingCard Ace Diamonds, PlayingCard Seven Diamonds]], [PlayingCard Three Clubs, PlayingCard Four Clubs]) confirmDisjoint :: (Int, Bool) confirmDisjoint = let mfunc1 hand = [mkRoyalFlush hand, mkStraightFlush hand, mkFourOfAKind hand, mkFullHouse hand, mkFlush hand, mkStraight hand, mkThreeOfAKind hand, mkTwoPair hand, mkPair hand, mkHighCard hand] maybem (Just _) = 1 maybem Nothing = 0 countJust hand = sum $ map maybem $ mfunc1 hand allSums = map countJust allPossibleHands collect _ (outsum, False) = (outsum, False) collect (x:xs) (outsum, _) = collect xs (x+outsum, if x==0 || x==1 then True else False) collect [] output = output in collect allSums (0, True) isUnique :: Eq a => [a] -> Bool isUnique lst = f lst True where f _ False = False f [] result = result f (x:xs) _ = if x `elem` xs then f xs False else f xs True shuffledDeck :: RandomGen g => Rand g [PlayingCard] shuffledDeck = shuffle $ fullDeck clubsDefaultSortAceLow :: [PlayingCard] clubsDefaultSortAceLow = let clubs = flip PlayingCard Clubs <$> ranks in sortCardsBy AceLowRankOrder $ clubs clubsDefaultSortAceHigh :: [PlayingCard] clubsDefaultSortAceHigh = let clubs = flip PlayingCard Clubs <$> ranks in sortCardsBy AceHighRankOrder $ clubs main :: IO () main = do randdecks <- evalRandIO $ replicateM 10000 shuffledDeck; randHighCards <- let r = do h <- randomHighCard return (h, isHighCard $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r randPairs <- let r = do h <- randomPair return (h, isPair $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r randTwoPairs <- let r = do h <- randomTwoPair return (h, isTwoPair $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r randThreeOfAKinds <- let r = do h <- randomThreeOfAKind return (h, isThreeOfAKind $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r randStraights <- let r = do h <- randomStraight return (h, isStraight $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r randFlushes <- let r = do h <- randomFlush return (h, isFlush $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r randFullHouses <- let r = do h <- randomFullHouse return (h, isFullHouse $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r randFourOfAKinds <- let r = do h <- randomFourOfAKind return (h, isFourOfAKind $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r randStraightFlushes <- let r = do h <- randomStraightFlush return (h, isStraightFlush $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r randRoyalFlushes <- let r = do h <- randomRoyalFlush return (h, isRoyalFlush $ cardsOfPokerHand h) in evalRandIO $ replicateM 100000 r hspec $ do describe "Game.Implement.Card.draw (PlayingCard)" $ do it "returns drawn hands from a deck, plus the remaining deck" $ do (draw drawDeckSizes drawDeck) `shouldBe` drawDeckExpectedOutput it "returns Nothing when trying to return more cards than in deck" $ do (draw drawDeckSizesFail drawDeck) `shouldBe` Nothing it "returns Nothing when trying to return negative cards" $ do (draw drawDeckSizesFailNeg drawDeck) `shouldBe` Nothing describe "Game.Implement.Card.fullDeck (PlayingCard)" $ do it "returns 52 cards" $ do length (fullDeck :: [PlayingCard]) `shouldBe` 52 it "returns unique cards" $ do isUnique (fullDeck :: [PlayingCard]) `shouldBe` True describe "Game.Game.Poker.compareCardBy" $ do it "orders low to high by default, check ace low" $ do clubsDefaultSortAceLow `shouldBe` [PlayingCard Ace Clubs, PlayingCard Two Clubs, PlayingCard Three Clubs, PlayingCard Four Clubs, PlayingCard Five Clubs, PlayingCard Six Clubs, PlayingCard Seven Clubs, PlayingCard Eight Clubs, PlayingCard Nine Clubs, PlayingCard Ten Clubs, PlayingCard Jack Clubs, PlayingCard Queen Clubs, PlayingCard King Clubs] it "orders low to high by default, check ace high" $ do clubsDefaultSortAceHigh `shouldBe` [PlayingCard Two Clubs, PlayingCard Three Clubs, PlayingCard Four Clubs, PlayingCard Five Clubs, PlayingCard Six Clubs, PlayingCard Seven Clubs, PlayingCard Eight Clubs, PlayingCard Nine Clubs, PlayingCard Ten Clubs, PlayingCard Jack Clubs, PlayingCard Queen Clubs, PlayingCard King Clubs, PlayingCard Ace Clubs] describe "Game.Game.Poker.isHand" $ do it "confirms that an Ace low straight flush exists" $ do isHand (StraightFlush AceLow) [PlayingCard Ace Spades, PlayingCard Two Spades, PlayingCard Three Spades, PlayingCard Four Spades, PlayingCard Five Spades] `shouldBe` True it "confirms that an Ace high straight flush is not Ace low" $ do isHand (StraightFlush AceLow) [PlayingCard Six Spades, PlayingCard Two Spades, PlayingCard Three Spades, PlayingCard Four Spades, PlayingCard Five Spades] `shouldBe` False it "confirms that an Ace high straight flush exists" $ do isHand (StraightFlush AceHigh) [PlayingCard Six Spades, PlayingCard Two Spades, PlayingCard Three Spades, PlayingCard Four Spades, PlayingCard Five Spades] `shouldBe` True describe "Game.Implement.Card.Standard.Poker.isRoyalFlush" $ do it "confirms that [AH, QH, KH, JH, TH] is a Royal Flush" $ do (isRoyalFlush royalFlush) `shouldBe` True it "confirms that [AH, QH, 8H, JH, TH] is not a Royal Flush" $ do (isRoyalFlush royalFlushNot) `shouldBe` False describe "Game.Game.Poker.randomHighCard" $ do it "returns a HighCard of typeOfPokerHand HighCard" $ do hand <- evalRandIO randomHighCard typeOfPokerHand hand `shouldBe` HighCard it "returns 100000 random HighCards" $ do randHighCards `shouldBe` (map (\(h,_) -> (h,True)) randHighCards) describe "Game.Game.Poker.randomPair" $ do it "returns a Pair of typeOfPokerHand Pair" $ do hand <- evalRandIO randomPair typeOfPokerHand hand `shouldBe` Pair it "returns 100000 random Pairs" $ do randPairs `shouldBe` (map (\(h,_) -> (h,True)) randPairs) describe "Game.Game.Poker.randomTwoPair" $ do it "returns a TwoPair of typeOfPokerHand TwoPair" $ do hand <- evalRandIO randomTwoPair typeOfPokerHand hand `shouldBe` TwoPair it "returns 100000 random TwoPairs" $ do randTwoPairs `shouldBe` (map (\(h,_) -> (h,True)) randTwoPairs) describe "Game.Game.Poker.randomThreeOfAKind" $ do it "returns a ThreeOfAKind of typeOfPokerHand ThreeOfAKind" $ do hand <- evalRandIO randomThreeOfAKind typeOfPokerHand hand `shouldBe` ThreeOfAKind it "returns 100000 random ThreeOfAKinds" $ do randThreeOfAKinds `shouldBe` (map (\(h,_) -> (h,True)) randThreeOfAKinds) describe "Game.Game.Poker.randomStraight" $ do it "returns a Straight of typeOfPokerHand Straight" $ do hand <- evalRandIO randomStraight typeOfPokerHand hand `shouldSatisfy` \t -> t == Straight AceHigh || t == Straight AceLow it "returns 100000 random Straights" $ do randStraights `shouldBe` (map (\(h,_) -> (h,True)) randStraights) describe "Game.Game.Poker.randomFlush" $ do it "returns a Flush of typeOfPokerHand Flush" $ do hand <- evalRandIO randomFlush typeOfPokerHand hand `shouldBe` Flush it "returns 100000 random Flushes" $ do randFlushes `shouldBe` (map (\(h,_) -> (h,True)) randFlushes) describe "Game.Game.Poker.randomFullHouse" $ do it "returns a FullHouse of typeOfPokerHand FullHouse" $ do hand <- evalRandIO randomFullHouse typeOfPokerHand hand `shouldBe` FullHouse it "returns 100000 random Full Houses" $ do randFullHouses `shouldBe` (map (\(h,_) -> (h,True)) randFullHouses) describe "Game.Game.Poker.randomFourOfAKind" $ do it "returns a FourOfAKind of typeOfPokerHand FourOfAKind" $ do hand <- evalRandIO randomFourOfAKind typeOfPokerHand hand `shouldBe` FourOfAKind it "returns 100000 random Four-of-a-Kinds" $ do randFourOfAKinds `shouldBe` (map (\(h,_) -> (h,True)) randFourOfAKinds) describe "Game.Game.Poker.randomStraightFlush" $ do it "returns a StraightFlush of typeOfPokerHand StraightFlush" $ do hand <- evalRandIO randomStraightFlush typeOfPokerHand hand `shouldSatisfy` \t -> t == StraightFlush AceHigh || t == StraightFlush AceLow it "returns 100000 random Straight Flushes" $ do randStraightFlushes `shouldBe` (map (\(h,_) -> (h,True)) randStraightFlushes) describe "Game.Game.Poker.randomRoyalFlush" $ do it "returns a RoyalFlush of typeOfPokerHand RoyalFlush" $ do hand <- evalRandIO randomRoyalFlush typeOfPokerHand hand `shouldBe` RoyalFlush it "returns 100000 random Royal Flushes" $ do randRoyalFlushes `shouldBe` (map (\(h,_) -> (h,True)) randRoyalFlushes) describe "Game.Implement.Card.shuffle (PlayingCard)" $ do it "returns 10000 different fullDeck shuffles using the global random generator" $ do (isUnique randdecks) `shouldBe` True describe "Game.Game.Poker allPossibleHands / mkHand / isHand functions" $ do it "confirms that sets of each hand are disjoint and that total count correct" $ do confirmDisjoint `shouldBe` (allHandsCountExpected, True) it "confirms the total number of poker hands" $ do allHandsCount `shouldBe` allHandsCountExpected it "confirms the total number of royal flushes" $ do (length allRoyalFlush) `shouldBe` allRoyalFlushCountExpected it "confirms the total number of straight flushes" $ do (length allStraightFlush) `shouldBe` allStraightFlushCountExpected it "confirms the total number of four-of-a-kinds" $ do (length allFourOfAKind) `shouldBe` allFourOfAKindCountExpected it "confirms the total number of full houses" $ do (length allFullHouse) `shouldBe` allFullHouseCountExpected it "confirms the total number of flushes" $ do (length allFlush) `shouldBe` allFlushCountExpected it "confirms the total number of straights" $ do (length allStraight) `shouldBe` allStraightCountExpected it "confirms the total number of three-of-a-kinds" $ do (length allThreeOfAKind) `shouldBe` allThreeOfAKindCountExpected it "confirms the total number of two-pairs" $ do (length allTwoPair) `shouldBe` allTwoPairCountExpected it "confirms the total number of pairs" $ do (length allPair) `shouldBe` allPairCountExpected it "confirms the total number of high card hands" $ do (length allHighCard) `shouldBe` allHighCardCountExpected
cgorski/general-games
test/Spec.hs
mit
13,703
0
21
3,511
3,529
1,758
1,771
292
5
module VirtualArrow.ElectionSpec (main, spec) where import Test.Hspec import VirtualArrow.Factory import VirtualArrow.Election import qualified Data.Map as M main :: IO () main = hspec spec spec :: Spec spec = do describe "VirtualArrow.Election.oneDistrictProportionality" $ it "returns the resulting parliament" $ oneDistrictProportionality input `shouldBe` oneDistrictProportionalityResult describe "VirtualArrow.Election.bordaCount" $ it "returns the resulting parliament" $ bordaCount input `shouldBe` bordaCountResult describe "VirtualArrow.Election.plurality" $ it "returns the resulting parliament" $ plurality input `shouldBe` pluralityResult describe "VirtualArrow.Election.runOffPlurality" $ it "returns the resulting parliament" $ runOffPlurality input `shouldBe` runOffPluralityResult describe "VirtualArrow.Election.multiDistrictProportionality" $ it "returns the resulting parliament" $ multiDistrictProportionality input `shouldBe` multiDistrictProportionalityResult describe "VirtualArrow.Election.mixedMember1 with 0" $ it "returns the resulting parliament" $ mixedMember1 input 0 `shouldBe` multiDistrictProportionalityResult describe "VirtualArrow.Election.mixedMember1 with 1" $ it "returns the resulting parliament" $ mixedMember1 input 1 `shouldBe` pluralityResult describe "VirtualArrow.Election.mixedMember1 with 0.5" $ it "returns the resulting parliament" $ mixedMember1 input 0.5 `shouldBe` mixedMember1Result05 describe "VirtualArrow.Election.mixedMember2" $ it "returns the resulting parliament" $ mixedMember2 input 0.5 `shouldBe` mixedMember2Result describe "VirtualArrow.Election.thresholdProportionality" $ it "returns the resulting parliament" $ do thresholdProportionality input 0.5 `shouldBe` thresholdProportionalityResult05 thresholdProportionality input 0.2 `shouldBe` thresholdProportionalityResult02 describe "VirtualArrow.Election.singleTransferableVote" $ it "returns the resulting parliament" $ singleTransferableVote input2 (M.fromList [(0, 0), (1, 0), (2, 1)]) `shouldBe` singleTransferableVoteResult
olya-d/virtual-arrow
test/VirtualArrow/ElectionSpec.hs
mit
2,336
0
13
486
415
207
208
43
1
module Rebase.Data.Semigroupoid.Dual ( module Data.Semigroupoid.Dual ) where import Data.Semigroupoid.Dual
nikita-volkov/rebase
library/Rebase/Data/Semigroupoid/Dual.hs
mit
110
0
5
12
23
16
7
4
0
module Sockets where import Network.Socket import Control.Exception withSocket::Family -> SocketType -> ProtocolNumber -> (Socket -> IO a) -> IO a withSocket family sktType protocol = bracket (socket family sktType protocol) (\s -> shutdown s ShutdownBoth >> close s) withAccept :: Socket -> ((Socket, SockAddr) -> IO a) -> IO a withAccept skt = bracket (accept skt) (\(connSkt, _ ) -> do shutdown connSkt ShutdownBoth close connSkt)
danplubell/dicom-network
library/Dicom/Network/Sockets.hs
mit
534
0
11
166
174
89
85
12
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances #-} module Core.AnnotAST where import Common import Core.AST type ExprF f a = f (ExprF' f a) data ExprF' f a = EVarF Name | ENumF Int | EConstrF Int Int -- tag, arity | EApF (ExprF f a) (ExprF f a) | ELetF Bool [(a, ExprF f a)] (ExprF f a) | ECaseF (ExprF f a) [AlterF f a] | EAbsF [a] (ExprF f a) deriving Functor deriving instance (Show a, Show (ExprF f a)) => Show (ExprF' f a) data AlterF f a = AlterF Int [a] (ExprF f a) deriving Functor deriving instance (Show a, Show (ExprF f a)) => Show (AlterF f a) data SupercombF f a = SupercombF Name [a] (ExprF f a) deriving Functor deriving instance (Show a, Show (ExprF f a)) => Show (SupercombF f a) newtype ProgramF f a = ProgramF { getProgramF :: [SupercombF f a] } deriving (Functor, Monoid) deriving instance (Show a, Show (ExprF f a)) => Show (ProgramF f a) toExpr :: (ExprF f a -> ExprF' f a) -> ExprF f a -> Expr a toExpr f e = case f e of EVarF v -> EVar v ENumF n -> ENum n EConstrF tag arity -> EConstr tag arity EApF e1 e2 -> EAp (toExpr f e1) (toExpr f e2) ELetF rec defs body -> ELet rec (zip xs exps) (toExpr f body) where xs = map fst defs exps = map (toExpr f . snd) defs ECaseF e alts -> ECase (toExpr f e) (map (toAlter f) alts) EAbsF args body -> EAbs args (toExpr f body) toAlter :: (ExprF f a -> ExprF' f a) -> AlterF f a -> Alter a toAlter f (AlterF tag xs body) = Alter tag xs (toExpr f body) newtype Annot a b = Annot { runAnnot :: (a, b) } deriving (Show, Functor) getAnnot :: Annot a b -> a getAnnot = fst . runAnnot unAnnot :: Annot a b -> b unAnnot = snd . runAnnot type AnnotExpr a b = ExprF (Annot a) b removeAnnot :: AnnotExpr a b -> Expr b removeAnnot = toExpr unAnnot type AnnotAlter a b = AlterF (Annot a) b type AnnotSupercomb a b = SupercombF (Annot a) b type AnnotProgram a b = ProgramF (Annot a) b
meimisaki/Rin
src/Core/AnnotAST.hs
mit
2,039
0
13
471
917
484
433
53
7
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.AnimationEvent (js_getAnimationName, getAnimationName, js_getElapsedTime, getElapsedTime, AnimationEvent, castToAnimationEvent, gTypeAnimationEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"animationName\"]" js_getAnimationName :: JSRef AnimationEvent -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent.animationName Mozilla AnimationEvent.animationName documentation> getAnimationName :: (MonadIO m, FromJSString result) => AnimationEvent -> m result getAnimationName self = liftIO (fromJSString <$> (js_getAnimationName (unAnimationEvent self))) foreign import javascript unsafe "$1[\"elapsedTime\"]" js_getElapsedTime :: JSRef AnimationEvent -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent.elapsedTime Mozilla AnimationEvent.elapsedTime documentation> getElapsedTime :: (MonadIO m) => AnimationEvent -> m Double getElapsedTime self = liftIO (js_getElapsedTime (unAnimationEvent self))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/AnimationEvent.hs
mit
1,889
12
11
237
446
274
172
31
1
{-# LANGUAGE OverloadedStrings #-} module Data.FixedWidth.Examples where import Data.Aeson import Data.Attoparsec.Text as StrictText import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BLC import Data.Char (isDigit, isSpace) import Data.FixedWidth (lineIterator, withFile) import qualified Data.Text as T import Text.Printf (printf) data Date = Date {dYear :: Int, dMonth :: Int, dDay :: Int} data Month = Month {mYear :: Int, mMonth :: Int} instance Show Date where show (Date y m d) = printf "%04d-%02d-%02d" y m d data Entry = Entry {eDate :: Date, eNames :: [T.Text], eValue :: Int} deriving Show isDigitOrSpace :: Char -> Bool isDigitOrSpace c = (isDigit c) || (isSpace c) fixInt :: Int -> Parser Int fixInt n = fmap (read . dropWhile isSpace) $ count n (satisfy isDigitOrSpace) date :: Parser Date date = do year <- fixInt 4 month <- fixInt 2 day <- fixInt 2 return $ Date year month day entry :: Parser Entry entry = do eDate <- date names <- count 4 (StrictText.take 4) value <- fixInt 3 return $ Entry eDate names value instance ToJSON Date where toJSON date = toJSON $ show date instance ToJSON Entry where toJSON (Entry date names value) = object ["date" .= date, "names" .= names, "value" .= value] defaultLineIterator :: T.Text -> IO () defaultLineIterator = lineIterator entry (putStrLn "Unparseable line.") (BLC.putStrLn . encode)
avantcredit/fixedwidth-hs
Data/FixedWidth/Examples.hs
mit
1,568
0
11
405
520
280
240
48
1
{- | Module : Summoner.License Copyright : (c) 2017-2022 Kowainik SPDX-License-Identifier : MPL-2.0 Maintainer : Kowainik <xrom.xkov@gmail.com> Stability : Stable Portability : Portable Data types that represent license names and license content and functions to work with them. -} module Summoner.License ( LicenseName (..) , License (..) , customizeLicense , githubLicenseQueryNames , parseLicenseName , fetchLicense , fetchLicenseCustom , licenseShortDesc , showLicenseWithDesc ) where import Colourista (errorMessage) import Data.Aeson.Micro (FromJSON (..), decodeStrict, withObject, (.:)) import Shellmet (($|)) import qualified Data.Text as T import qualified Text.Show as TS -- | Licenses supported by @summoner@. data LicenseName = MIT | BSD2 | BSD3 | GPL2 | GPL3 | LGPL21 | LGPL3 | AGPL3 | Apache20 | MPL20 | ISC | NONE deriving stock (Eq, Ord, Enum, Bounded, Generic) instance Show LicenseName where show MIT = "MIT" show BSD2 = "BSD-2-Clause" show BSD3 = "BSD-3-Clause" show GPL2 = "GPL-2.0-only" show GPL3 = "GPL-3.0-only" show LGPL21 = "LGPL-2.1-only" show LGPL3 = "LGPL-3.0-only" show AGPL3 = "AGPL-3.0-only" show Apache20 = "Apache-2.0" show MPL20 = "MPL-2.0" show ISC = "ISC" show NONE = "NONE" newtype License = License { unLicense :: Text } deriving stock (Show, Generic) deriving newtype (IsString) instance FromJSON License where parseJSON = withObject "License" $ \o -> License <$> o .: "body" -- | Used for downloading the license text form @Github@. githubLicenseQueryNames :: LicenseName -> Text githubLicenseQueryNames = \case MIT -> "mit" BSD2 -> "bsd-2-clause" BSD3 -> "bsd-3-clause" GPL2 -> "gpl-2.0" GPL3 -> "gpl-3.0" LGPL21 -> "lgpl-2.1" LGPL3 -> "lgpl-3.0" AGPL3 -> "agpl-3.0" Apache20 -> "apache-2.0" MPL20 -> "mpl-2.0" ISC -> "isc" NONE -> "none" parseLicenseName :: Text -> Maybe LicenseName parseLicenseName = inverseMap show -- | Replaces name/year placeholders with the actual data. customizeLicense :: LicenseName -> License -> Text -> Text -> License customizeLicense l license@(License licenseText) nm year | l `elem` [MIT, BSD2, BSD3, ISC] = License updatedLicenseText | otherwise = license where updatedLicenseText :: Text updatedLicenseText = let (beforeY, withY) = T.span (/= '[') licenseText afterY = T.tail $ T.dropWhile (/= ']') withY (beforeN, withN) = T.span (/= '[') afterY afterN = T.tail $ T.dropWhile (/= ']') withN in beforeY <> year <> beforeN <> nm <> afterN -- | Download the given LICENSE text as it is from GitHub API. fetchLicense :: LicenseName -> IO License fetchLicense NONE = pure $ License $ licenseShortDesc NONE fetchLicense name = do let licenseLink = "https://api.github.com/licenses/" <> githubLicenseQueryNames name licenseJson <- "curl" $| [ licenseLink , "-H" , "Accept: application/vnd.github.drax-preview+json" , "--silent" , "--fail" ] whenNothing (decodeStrict @License $ encodeUtf8 licenseJson) $ do errorMessage $ "Error downloading license: " <> show name putTextLn $ "Fetched content:\n" <> licenseJson exitFailure {- | Fetches the license by given name and customises user information where applicable. -} fetchLicenseCustom :: LicenseName -> Text -> Text -> IO License fetchLicenseCustom license fullName year = do licenseText <- fetchLicense license pure $ customizeLicense license licenseText fullName year -- | Show short information for the 'LicenseName'. licenseShortDesc :: LicenseName -> Text licenseShortDesc = \case MIT -> "MIT license" BSD2 -> "2-clause BSD license" BSD3 -> "3-clause BSD license" GPL2 -> "GNU General Public License, version 2" GPL3 -> "GNU General Public License, version 3" LGPL21 -> "GNU Lesser General Public License, version 2.1" LGPL3 -> "GNU Lesser General Public License, version 3" AGPL3 -> "GNU Affero General Public License, version 3" Apache20 -> "Apache License, version 2.0" MPL20 -> "Mozilla Public License, version 2.0" ISC -> "Internet Systems Consortium" NONE -> "License file won't be added. The package may not be legally \ \modified or redistributed by anyone but the rightsholder" -- | Show license name along with its short description. showLicenseWithDesc :: LicenseName -> Text showLicenseWithDesc l = show l <> ": " <> licenseShortDesc l
vrom911/hs-init
summoner-cli/src/Summoner/License.hs
mit
4,843
0
13
1,288
971
523
448
-1
-1
{-| Module : Repl.State Description : A type for managing REPL state. Copyright : (c) Michael Lopez, 2017 License : MIT Maintainer : m-lopez (github) Stability : unstable Portability : non-portable -} module Repl.State ( CompilerState(..) ) where import Context ( Ctx ) -- | Compiler state. newtype CompilerState = CompilerState { getCtx :: Ctx }
m-lopez/jack
src/Repl/State.hs
mit
366
0
6
75
38
26
12
4
0
module Command ( command ) where import Text.Parsec hiding (State) import Text.Parsec.String (Parser) import UniversalMachine (State, Symbol, Transition) import UniversalMachine.Parser (machineStateParser, symbolParser, transitionParser) data Command = Save | Load | Next | Previous | Continue | AddState State | AddSymbol Symbol | AddTransition Transition | AddFinalState State | AddBreakpoint State | RemoveState State | RemoveSymbol Symbol | RemoveTransition Transition | RemoveFinalState State | RemoveBreakpoint State | UpdateBlankSymbol Symbol | UpdateInitialState State | UpdateTapeAppend Symbol | UpdateTapePrepend Symbol | UpdateTape Symbol | ViewMachine | ViewStates | ViewAlphabet | ViewTransitions | ViewInitialState | ViewFinalStates | ViewBlankSymbol | ViewState State | ViewBreakpoints deriving Show instructionWithArgs :: String -> Parser a -> (a -> Command) -> Parser Command instructionWithArgs str p f = try $ string str >> spaces >> p >>= return . f instruction :: String -> Command -> Parser Command instruction str cmd = try $ string str >> return cmd stateInstruction :: String -> (State -> Command) -> Parser Command stateInstruction str f = instructionWithArgs str machineStateParser f symbolInstruction :: String -> (Symbol -> Command) -> Parser Command symbolInstruction str f = instructionWithArgs str symbolParser f transitionInstruction :: (Transition -> Command) -> Parser Command transitionInstruction f = instructionWithArgs "transition" transitionParser f add :: Parser Command add = string "add" >> spaces >> choice [ stateInstruction "state" AddState , symbolInstruction "symbol" AddSymbol , transitionInstruction AddTransition , stateInstruction "final" AddFinalState , stateInstruction "breakpoint" AddBreakpoint ] remove :: Parser Command remove = string "remove" >> spaces >> choice [ stateInstruction "state" RemoveState , symbolInstruction "symbol" RemoveSymbol , transitionInstruction RemoveTransition , stateInstruction "final" RemoveFinalState , stateInstruction "breakpoint" RemoveBreakpoint ] tape :: Parser Command tape = string "tape" >> spaces >> choice [ symbolInstruction "prepend" UpdateTapePrepend , symbolInstruction "append" UpdateTapeAppend , symbolParser >>= return . UpdateTape ] update :: Parser Command update = string "update" >> spaces >> choice [ symbolInstruction "blank" UpdateBlankSymbol , stateInstruction "initial" UpdateInitialState , tape ] view :: Parser Command view = string "view" >> spaces >> choice [ instruction "machine" ViewMachine , instruction "states" ViewStates , instruction "alphabet" ViewAlphabet , instruction "transitions" ViewTransitions , instruction "initial" ViewInitialState , instruction "finals" ViewFinalStates , instruction "blank" ViewBlankSymbol , stateInstruction "state" ViewState , instruction "breakpoints" ViewBreakpoints ] command :: Parser Command command = spaces >> choice [ instruction "save" Save , instruction "load" Load , instruction "next" Next , instruction "previous" Previous , instruction "continue" Continue , add , remove , update , view ]
jean-lopes/universal-machine
app/Command.hs
mit
3,817
0
10
1,158
807
426
381
91
1
module Euler.Problems.Euler004 ( euler004 ) where euler004 :: () -> Int euler004 _ = maximum [z | x <- [1..999], y <- [x..999], let z = x*y, isPalindrome z] where isPalindrome n = let reverse' x y | y == 0 = x | otherwise = reverse' (x * 10 + y `mod` 10) (y `div` 10) in n == reverse' 0 n
b52/projecteuler
src/Euler/Problems/Euler004.hs
mit
375
0
16
149
169
87
82
8
1
-- main = print answer answer = sum $ filter even $ take maxN fibs maxN = 32 fibs = 1:2:(zipWith (+) fibs $ tail fibs) -- map ((-) 4000000) $ take 33 fibs
yuto-matsum/contest-util-hs
src/Euler/002.hs
mit
155
0
8
34
59
31
28
3
1
module Main where import Control.Monad.ST import Data.Maybe import Data.Char import Data.List import Data.Graph import qualified Data.Set as S import Control.Monad import Data.Array import qualified Data.Array.Unboxed as U import Data.Array.ST hiding (unsafeFreeze) import Data.Array.Unsafe import qualified Data.ByteString.Char8 as BS type Weights = U.UArray (Int, Int) Int loop :: Int -> STUArray s (Int, Int) Int -> STArray s Int [Int] -> [Int] -> ST s [Int] loop 0 _ _ s = return s loop n w g s = let ([f, t, p], rest) = splitAt 3 s in do writeArray w (f, t) p e <- readArray g f writeArray g f (t:e) loop (n-1) w g rest parseTriples :: Int -> Int -> [Int] -> (Weights, Graph, [Int]) parseTriples n m p = runST $ do w <- newArray ((1, 1), (n, n)) 0 :: ST s (STUArray s (Int, Int) Int) g <- newArray (1, n) [] :: ST s (STArray s Int [Int]) rest <- loop m w g p wf <- unsafeFreeze w wg <- unsafeFreeze g return (wf, wg, rest) parse :: [Int] -> (Int, Int, Int, Int, Weights, Graph) parse p = let (n:m:rest) = p (w, g, rest1) = parseTriples n m rest (s:f:_) = rest1 in (n, m, s, f, w, g) toIntList :: BS.ByteString -> [Int] toIntList s = let trimmed = BS.dropWhile isSpace s (i, rest) = fromJust $ BS.readInt trimmed in i : toIntList rest cutDead :: Vertex -> Vertex -> Graph -> Maybe Graph cutDead s f g = let fromStart = S.fromList $ reachable g s toEnd = S.fromList $ reachable (transposeG g) f workable = S.intersection fromStart toEnd newBounds = (S.findMin workable, S.findMax workable) edgeFilter (f, t) = f `S.member` workable && t `S.member` workable cutGraph = buildG newBounds $ filter edgeFilter $ edges g in if edgeFilter (s, f) then Just cutGraph else Nothing findRoute :: Vertex -> Graph -> Weights -> Int findRoute s g w = let order = reverse $ topSort g paths = runSTUArray $ do p <- newArray (bounds g) 0 forM_ order $ \i -> do let e = g ! i way n = do next <- readArray p n return $ next + (w U.! (i, n)) ways <- forM e way writeArray p i $ foldl' max 0 ways return p in paths U.! s main :: IO () main = do input <- BS.getContents let (n, m, s, f, pipes, graph) = parse $ toIntList input modGraph = cutDead s f graph case modGraph of Nothing -> putStrLn "No solution" Just g -> print $ findRoute s g pipes
ratatosk/zadro
1450_russian_pipelines.hs
mit
2,673
0
24
883
1,148
599
549
71
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.MessageChannel (js_newMessageChannel, newMessageChannel, js_getPort1, getPort1, js_getPort2, getPort2, MessageChannel, castToMessageChannel, gTypeMessageChannel) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "new window[\"MessageChannel\"]()" js_newMessageChannel :: IO MessageChannel -- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel Mozilla MessageChannel documentation> newMessageChannel :: (MonadIO m) => m MessageChannel newMessageChannel = liftIO (js_newMessageChannel) foreign import javascript unsafe "$1[\"port1\"]" js_getPort1 :: MessageChannel -> IO (Nullable MessagePort) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel.port1 Mozilla MessageChannel.port1 documentation> getPort1 :: (MonadIO m) => MessageChannel -> m (Maybe MessagePort) getPort1 self = liftIO (nullableToMaybe <$> (js_getPort1 (self))) foreign import javascript unsafe "$1[\"port2\"]" js_getPort2 :: MessageChannel -> IO (Nullable MessagePort) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel.port2 Mozilla MessageChannel.port2 documentation> getPort2 :: (MonadIO m) => MessageChannel -> m (Maybe MessagePort) getPort2 self = liftIO (nullableToMaybe <$> (js_getPort2 (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MessageChannel.hs
mit
2,131
16
10
250
514
312
202
31
1
-- | Session functions. module Session where import Control.Arrow hiding (app) import Control.Concurrent import Control.Concurrent.STM import Control.Monad import qualified Data.ByteString.Lazy as L import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe import Data.Set (Set) import qualified Data.Set as S import qualified Data.Text as T import Distribution.Text (display) import Stackage.View.Cabal import Stackage.View.Git import Stackage.View.Types import Filesystem as FP import Filesystem.Loc as FL import Filesystem.Path (FilePath) import qualified Filesystem.Path.CurrentOS as FP import IdeSession hiding (errorSpan,errorMsg) import Import hiding (FilePath) import Language.Haskell.Extension import Prelude hiding (FilePath,writeFile,pi) import SharedTypes -- | Continue the session with the given unambiguous targets. continueWith :: [TargetIdent] -> App -> IO () continueWith targets app = do unloadTargets (appSession app) (appLoadedTargets app) targets loadProject (appSession app) (M.fromList (map (\target -> (targetIdent target,any (== targetIdent target) targets)) (appTargets app))) (mapMaybe (\ident -> find ((== ident) . targetIdent) (appTargets app)) targets) (appDataFiles app) (appLoading app) (appLoadedTargets app) -- | Unload targets. unloadTargets :: IdeSession -> TVar [Target] -> [TargetIdent] -> IO () unloadTargets sess loadedTargets except = do targets <- atomically (readTVar loadedTargets) let allTargetFiles = mconcat (map targetFiles (filter (not . flip elem except . targetIdent) targets)) updateSession sess (mconcat (map (updateSourceFileDelete . FL.encodeString) (S.toList allTargetFiles))) (const (return ())) -- | Start the session with the cabal file, will not proceed if the -- targets are unambiguous, in which case it will be continued later -- after prompting the user. startSession :: TVar [Target] -> TVar LoadingStatus -> IO (IdeSession,[Target],Set FilePath) startSession loadedTargets loading = do dir <- FL.getWorkingDir cabalfp <- getCabalFp dir targets <- getTargets mempty cabalfp datafiles <- getGitFiles >>= fmap S.fromList . filterM isFile . S.toList session <- initSession (sessionParams targets) defaultSessionConfig if length (filter (needsMain . targetIdent) targets) > 1 then atomically (writeTVar loading (AmbiguousTargets (map targetIdent targets))) else loadProject session (M.fromList (map (targetIdent &&& const True) targets)) targets datafiles loading loadedTargets return (session,targets,datafiles) where sessionParams targets = defaultSessionInitParams {sessionInitGhcOptions = ["-hide-all-packages"] <> concatMap includePackage (concatMap targetDependencies targets)} where includePackage pkgName = ["-package",display pkgName] -- | Load the project into the ide-backend. loadProject :: IdeSession -> Map TargetIdent Bool -> [Target] -> Set FilePath -> TVar LoadingStatus -> TVar [Target] -> IO () loadProject session targetChoices targets datafiles loading loadedTargets = void (forkIO (do atomically (writeTVar loadedTargets targets) setOpts session targets loadFiles session targetChoices targets datafiles loading)) -- | Set GHC options. setOpts :: IdeSession -> [Target] -> IO () setOpts sess targets = updateSession sess (updateGhcOpts (map showExt (concatMap targetExtensions targets))) (const (return ())) where showExt :: Extension -> String showExt g = case g of EnableExtension e -> "-X" <> show e DisableExtension e -> "-XNo" <> show e UnknownExtension e -> "-X" <> show e -- | Load the package files and update the app state of the progress. loadFiles :: IdeSession -> Map TargetIdent Bool -> [Target] -> Set FilePath -> TVar LoadingStatus -> IO () loadFiles sess targetChoices targets files loading = do updates <- forM loadedFiles (\fp -> do content <- L.readFile (FL.encodeString fp) return (updateSourceFile (FL.encodeString fp) content)) updates' <- forM (S.toList files) (\fp -> do content <- L.readFile (FP.encodeString fp) return (updateDataFile (FP.encodeString fp) content)) atomically (writeTVar loading NotLoading) updateSession sess (mconcat updates <> mconcat updates' <> updateCodeGeneration True) (\progress -> atomically (writeTVar loading (Loading (progressStep progress) (progressNumSteps progress) (fromMaybe (fromMaybe "Unknown step" (progressOrigMsg progress)) (progressParsedMsg progress))))) errs <- fmap (filter isError) (getSourceErrors sess) if null errs then atomically (writeTVar loading (LoadOK (M.toList targetChoices) (map (T.pack . FL.encodeString) (sort loadedFiles)))) else atomically (writeTVar loading (LoadFailed (map toError errs))) where loadedFiles = S.toList (mconcat (map targetFiles targets)) isError (SourceError{errorKind = k}) = case k of KindError -> True KindServerDied -> True KindWarning -> False -- | Convert a source error to either an unhelpful text span or a -- proper span. toError :: SourceError -> Either Text Error toError (SourceError _ espan msg) = case espan of ProperSpan (SourceSpan path sl sc el ec) -> Right (Error {errorFile = T.pack path ,errorSpan = Span sl sc el ec ,errorMsg = msg}) TextSpan e -> Left e
fpco/stackage-view
server/Session.hs
mit
7,066
0
20
2,627
1,712
880
832
163
4
{- | Module : Data.Grib.Raw.ValueSpec Copyright : (c) Mattias Jakobsson 2015 License : GPL-3 Maintainer : mjakob422@gmail.com Stability : unstable Portability : portable Unit and regression tests for Data.Grib.Raw.Value. -} module Data.Grib.Raw.ValueSpec ( main, spec ) where import Foreign ( allocaArray, allocaBytes, nullPtr ) import Test.Hspec import Data.Grib.Exception import Data.Grib.Raw import Data.Grib.Raw.Test main :: IO () main = hspec spec spec :: Spec spec = do describe "gribGetLong" $ do it "should return 16 for numberOfPointsAlongAParallel" $ withRegular1 $ \h -> gribGetLong h "Ni" `shouldReturn` 16 it "should return 31 for numberOfPointsAlongAMeridian" $ withRegular1 $ \h -> gribGetLong h "Nj" `shouldReturn` 31 it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribGetLong h "missingKey" `shouldThrow` isGribException GribNotFound describe "gribGetDouble" $ do it "should return 60 for latitudeOfFirstGridPointInDegrees" $ withRegular1 $ \h -> gribGetDouble h "latitudeOfFirstGridPointInDegrees" `shouldReturn` 60 it "should return 0 for longitudeOfFirstGridPointInDegrees" $ withRegular1 $ \h -> gribGetDouble h "longitudeOfFirstGridPointInDegrees" `shouldReturn` 0 it "should return 0 for latitudeOfLastGridPointInDegrees" $ withRegular1 $ \h -> gribGetDouble h "latitudeOfLastGridPointInDegrees" `shouldReturn` 0 it "should return 30 for longitudeOfLastGridPointInDegrees" $ withRegular1 $ \h -> gribGetDouble h "longitudeOfLastGridPointInDegrees" `shouldReturn` 30 it "should return 2 for jDirectionIncrementInDegrees" $ withRegular1 $ \h -> gribGetDouble h "jDirectionIncrementInDegrees" `shouldReturn` 2 it "should return 2 for iDirectionIncrementInDegrees" $ withRegular1 $ \h -> gribGetDouble h "iDirectionIncrementInDegrees" `shouldReturn` 2 it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribGetDouble h "missingKey" `shouldThrow` isGribException GribNotFound describe "gribGetLongArray" $ do it "should return [16] for numberOfPointsAlongAParallel" $ withRegular1 $ \h -> allocaArray 10 $ \ls -> gribGetLongArray h "Ni" ls 10 `shouldReturn` [16] it "should return [31] for numberOfPointsAlongAMeridian" $ withRegular1 $ \h -> allocaArray 10 $ \ls -> gribGetLongArray h "Nj" ls 10 `shouldReturn` [31] it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> allocaArray 10 $ \ls -> gribGetLongArray h "missingKey" ls 10 `shouldThrow` isGribException GribNotFound it "should fail with GribArrayTooSmall if the array is too small" $ withRegular1 $ \h -> gribGetLongArray h "Ni" nullPtr 0 `shouldThrow` isGribException GribArrayTooSmall describe "gribGetDoubleArray" $ do it "should return 496 values with an average of 291.585" $ withRegular1 $ \h -> allocaArray 500 $ \ds -> do ds' <- gribGetDoubleArray h "values" ds 500 length ds' `shouldBe` 496 sum ds' / 496 `shouldBe` 291.5852483933972 it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> allocaArray 10 $ \ds -> gribGetDoubleArray h "missingKey" ds 10 `shouldThrow` isGribException GribNotFound it "should fail with GribArrayTooSmall if the array is too small" $ withRegular1 $ \h -> gribGetDoubleArray h "values" nullPtr 0 `shouldThrow` isGribException GribArrayTooSmall describe "gribGetDoubleElement" $ do it "should return 279 for the 0th value" $ withRegular1 $ \h -> gribGetDoubleElement h "values" 0 `shouldReturn` 279 it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribGetDoubleElement h "missingKey" 0 `shouldThrow` isGribException GribNotFound describe "gribGetDoubleElements" $ do it "should return [279] for the 0th value" $ withRegular1 $ \h -> gribGetDoubleElements h "values" [0] `shouldReturn` [279] it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribGetDoubleElements h "missingKey" [0] `shouldThrow` isGribException GribNotFound describe "gribGetString" $ do it "should return \"grid_simple\" for packingType" $ withRegular1 $ \h -> allocaBytes 12 $ \bufr -> gribGetString h "packingType" bufr 12 `shouldReturn` "grid_simple" it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> allocaBytes 2 $ \bufr -> gribGetString h "missingKey" bufr 2 `shouldThrow` isGribException GribNotFound it "should fail with GribBufferTooSmall if the buffer is too small" $ withRegular1 $ \h -> allocaBytes 1 $ \bufr -> gribGetString h "packingType" bufr 1 `shouldThrow` isGribException GribBufferTooSmall describe "gribGetBytes" $ do it "should return 2 for numberOfPointsAlongAParallel" $ withRegular1 $ \h -> allocaArray 4 $ \bs -> gribGetBytes h "Ni" bs 4 >>= \(_, n) -> n `shouldBe` 2 it "should return 2 for numberOfPointsAlongAMeridian" $ withRegular1 $ \h -> allocaArray 4 $ \bs -> gribGetBytes h "Nj" bs 4 >>= \(_, n) -> n `shouldBe` 2 it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> allocaArray 1 $ \bs -> gribGetBytes h "missingKey" bs 1 `shouldThrow` isGribException GribNotFound it "should fail with GribArrayTooSmall if the array is too small" $ withRegular1 $ \h -> allocaArray 1 $ \bs -> gribGetBytes h "totalLength" bs 1 `shouldThrow` isGribException GribArrayTooSmall describe "gribGetOffset" $ do it "should return 66 for numberOfPointsAlongAParallel" $ withRegular1 $ \h -> gribGetOffset h "Ni" `shouldReturn` 66 it "should return 68 for numberOfPointsAlongAMeridian" $ withRegular1 $ \h -> gribGetOffset h "Nj" `shouldReturn` 68 it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribGetOffset h "missingKey" `shouldThrow` isGribException GribNotFound describe "gribGetSize" $ do it "should return 496 for the values" $ withRegular1 $ \h -> gribGetSize h "values" `shouldReturn` 496 it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribGetSize h "missingKey" `shouldThrow` isGribException GribNotFound describe "gribGetLength" $ do it "should return 256 for packingType" $ withRegular1 $ \h -> gribGetLength h "packingType" `shouldReturn` 256 it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribGetLength h "missingKey" `shouldThrow` isGribException GribNotFound describe "gribSetLong" $ do it "should update centre to 80" $ withRegular1 $ \h -> let newCentre = 80 in do gribSetLong h "centre" newCentre gribGetLong h "centre" `shouldReturn` newCentre it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribSetLong h "missingKey" 0 `shouldThrow` isGribException GribNotFound it "should fail with GribReadOnly if the key is read-only" $ withRegular1 $ \h -> gribSetLong h "getNumberOfValues" 0 `shouldThrow` isGribException GribReadOnly describe "gribSetDouble" $ do it "should update missingValue to 0" $ withRegular1 $ \h -> let newMissingValue = 0 in do gribSetDouble h "missingValue" newMissingValue gribGetDouble h "missingValue" `shouldReturn` newMissingValue it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribSetDouble h "missingKey" 0 `shouldThrow` isGribException GribNotFound it "should fail with GribReadOnly if the key is read-only" $ withRegular1 $ \h -> gribSetDouble h "referenceValue" 0 `shouldThrow` isGribException GribReadOnly describe "gribSetLongArray" $ do it "should update centre to 80" $ withRegular1 $ \h -> let newCentre = 80 in do gribSetLongArray h "centre" [newCentre] gribGetLong h "centre" `shouldReturn` newCentre it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribSetLongArray h "missingKey" [1] `shouldThrow` isGribException GribNotFound it "should fail with GribReadOnly if the key is read-only" $ withRegular1 $ \h -> gribSetLongArray h "getNumberOfValues" [1] `shouldThrow` isGribException GribReadOnly describe "gribSetDoubleArray" $ do it "should set all values to zero" $ withRegular1 $ \h -> gribGetSize h "values" >>= \n -> allocaArray n $ \ds -> let newVals = replicate n 0 in do gribSetDoubleArray h "values" newVals gribGetDoubleArray h "values" ds n `shouldReturn` newVals it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribSetDoubleArray h "missingKey" [1] `shouldThrow` isGribException GribNotFound it "should fail with GribReadOnly if the key is read-only" $ withRegular1 $ \h -> gribSetDoubleArray h "referenceValue" [1] `shouldThrow` isGribException GribReadOnly describe "gribSetString" $ do it "should set a new file key and return its length" $ withRegular1 $ \h -> let len = length regular1Path in allocaBytes (len + 1) $ \cs -> do gribSetString h "file" regular1Path `shouldReturn` len gribGetString h "file" cs (len + 1) `shouldReturn` regular1Path it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> gribSetString h "missingKey" "" `shouldThrow` isGribException GribNotFound it "should fail with GribReadOnly if the key is read-only" $ withRegular1 $ \h -> gribSetString h "referenceValue" "" `shouldThrow` isGribException GribReadOnly describe "gribSetBytes" $ it "should fail with GribNotFound if the key is missing" $ withRegular1 $ \h -> allocaArray 1 $ \bs -> gribSetBytes h "missingKey" bs 1 `shouldThrow` isGribException GribNotFound describe "gribCopyNamespace" $ it "should succeed to copy namespace ls to itself" $ withRegular1 $ \h -> gribCopyNamespace h (Just "ls") h
mjakob/hgrib
test/Data/Grib/Raw/ValueSpec.hs
gpl-3.0
10,642
0
21
2,640
2,424
1,189
1,235
213
1
module HipSpec.Property.Repr where import HipSpec.Lang.Simple import Text.PrettyPrint -- TODO: Print lists (x:[]) => [x], and tuples (,) x y => (x,y) properly exprRepr' :: Int -> Expr String -> Doc exprRepr' i e0 = case e0 of Lcl x _ -> text x Gbl x _ _ -> text x App{} -> let (fun,args) = collectArgs e0 pp_args = map (exprRepr' 2) args pp_args' = map (exprRepr' 1) args pp_fun = exprRepr' 0 fun in case (oper (render pp_fun),pp_args') of (True,[]) -> parens pp_fun (True,[x]) -> parens (x <> pp_fun) (True,[x,y]) -> parensIf (i >= 1) $ x <> pp_fun <> y (True,x:y:_) -> parensIf (i >= 2) $ parens (x <> pp_fun <> y) <+> hsep (drop 2 pp_args) _ -> parensIf (i >= 2) $ pp_fun <+> hsep pp_args Lit x -> integer x exprRepr :: Expr String -> String exprRepr = render . exprRepr' 0 parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf _ = id oper :: String -> Bool oper s = not (null s') && all (`elem` opSyms) s' where s' = filter (`notElem` ('_':['0'..'9'])) s opSyms :: String opSyms = ":!#$%&*+./<=>?@|^-~\\"
danr/hipspec
src/HipSpec/Property/Repr.hs
gpl-3.0
1,209
0
18
383
489
255
234
29
8
{-# LANGUAGE RecordWildCards #-} module Main ( main ) where import KRPCHS import KRPCHS.SpaceCenter import Control.Monad import Control.Monad.Catch import Control.Monad.Trans import Data.List data TelemetryData = TelemetryData { time :: Double , altitude :: Double , latitude :: Double , longitude :: Double , mass :: Float , thrust :: Float } main :: IO () main = withRPCClient "Flight recorder" "127.0.0.1" "50000" $ \client -> withStreamClient client "127.0.0.1" "50001" $ \streamClient -> runRPCProg client (telemetryProg streamClient) telemetryProg :: StreamClient -> RPCContext () telemetryProg streamClient = do vessel <- getActiveVessel ref <- getVesselSurfaceReferenceFrame vessel flight <- vesselFlight vessel ref -- install streams timeStream <- getUTStream altitudeStream <- getFlightMeanAltitudeStream flight latitudeStream <- getFlightLatitudeStream flight longitudeStream <- getFlightLongitudeStream flight massStream <- getVesselMassStream vessel thrustStream <- getVesselThrustStream vessel -- get results and print csv liftIO $ putStrLn "time;altitude;latitude;longitude;mass;thrust" forever $ do msg <- getStreamMessage streamClient ok <- try (do time <- getStreamResult timeStream msg altitude <- getStreamResult altitudeStream msg latitude <- getStreamResult latitudeStream msg longitude <- getStreamResult longitudeStream msg mass <- getStreamResult massStream msg thrust <- getStreamResult thrustStream msg return TelemetryData{..}) case ok of Right telemetry -> liftIO $ printTelemetryCSV telemetry Left NoSuchStream -> return () -- this can happen during the first few loops Left err -> throwM err printTelemetryCSV :: TelemetryData -> IO () printTelemetryCSV TelemetryData{..} = putStrLn $ intercalate ";" [show time, show altitude, show latitude, show longitude, show mass, show thrust]
Cahu/krpc-hs
examples/FlightRecorderCSV.hs
gpl-3.0
2,193
0
16
610
499
242
257
50
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Vision.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.Vision.Types.Product where import Network.Google.Prelude import Network.Google.Vision.Types.Sum -- | An object representing a latitude\/longitude pair. This is expressed as -- a pair of doubles representing degrees latitude and degrees longitude. -- Unless specified otherwise, this must conform to the -- <http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf WGS84 standard>. -- Values must be within normalized ranges. Example of normalization code -- in Python: def NormalizeLongitude(longitude): \"\"\"Wraps decimal -- degrees longitude to [-180.0, 180.0].\"\"\" q, r = divmod(longitude, -- 360.0) if r > 180.0 or (r == 180.0 and q \<= -1.0): return r - 360.0 -- return r def NormalizeLatLng(latitude, longitude): \"\"\"Wraps decimal -- degrees latitude and longitude to [-90.0, 90.0] and [-180.0, 180.0], -- respectively.\"\"\" r = latitude % 360.0 if r \<= 90.0: return r, -- NormalizeLongitude(longitude) elif r >= 270.0: return r - 360, -- NormalizeLongitude(longitude) else: return 180 - r, -- NormalizeLongitude(longitude + 180.0) assert 180.0 == -- NormalizeLongitude(180.0) assert -180.0 == NormalizeLongitude(-180.0) -- assert -179.0 == NormalizeLongitude(181.0) assert (0.0, 0.0) == -- NormalizeLatLng(360.0, 0.0) assert (0.0, 0.0) == NormalizeLatLng(-360.0, -- 0.0) assert (85.0, 180.0) == NormalizeLatLng(95.0, 0.0) assert (-85.0, -- -170.0) == NormalizeLatLng(-95.0, 10.0) assert (90.0, 10.0) == -- NormalizeLatLng(90.0, 10.0) assert (-90.0, -10.0) == -- NormalizeLatLng(-90.0, -10.0) assert (0.0, -170.0) == -- NormalizeLatLng(-180.0, 10.0) assert (0.0, -170.0) == -- NormalizeLatLng(180.0, 10.0) assert (-90.0, 10.0) == -- NormalizeLatLng(270.0, 10.0) assert (90.0, 10.0) == -- NormalizeLatLng(-270.0, 10.0) The code in -- logs\/storage\/validator\/logs_validator_traits.cc treats this type as -- if it were annotated as ST_LOCATION. -- -- /See:/ 'latLng' smart constructor. data LatLng = LatLng' { _llLatitude :: !(Maybe (Textual Double)) , _llLongitude :: !(Maybe (Textual Double)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LatLng' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'llLatitude' -- -- * 'llLongitude' latLng :: LatLng latLng = LatLng' { _llLatitude = Nothing , _llLongitude = Nothing } -- | The latitude in degrees. It must be in the range [-90.0, +90.0]. llLatitude :: Lens' LatLng (Maybe Double) llLatitude = lens _llLatitude (\ s a -> s{_llLatitude = a}) . mapping _Coerce -- | The longitude in degrees. It must be in the range [-180.0, +180.0]. llLongitude :: Lens' LatLng (Maybe Double) llLongitude = lens _llLongitude (\ s a -> s{_llLongitude = a}) . mapping _Coerce instance FromJSON LatLng where parseJSON = withObject "LatLng" (\ o -> LatLng' <$> (o .:? "latitude") <*> (o .:? "longitude")) instance ToJSON LatLng where toJSON LatLng'{..} = object (catMaybes [("latitude" .=) <$> _llLatitude, ("longitude" .=) <$> _llLongitude]) -- | Users describe the type of Google Cloud Vision API tasks to perform over -- images by using *Feature*s. Each Feature indicates a type of image -- detection task to perform. Features encode the Cloud Vision API vertical -- to operate on and the number of top-scoring results to return. -- -- /See:/ 'feature' smart constructor. data Feature = Feature' { _fType :: !(Maybe FeatureType) , _fMaxResults :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Feature' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fType' -- -- * 'fMaxResults' feature :: Feature feature = Feature' { _fType = Nothing , _fMaxResults = Nothing } -- | The feature type. fType :: Lens' Feature (Maybe FeatureType) fType = lens _fType (\ s a -> s{_fType = a}) -- | Maximum number of results of this type. fMaxResults :: Lens' Feature (Maybe Int32) fMaxResults = lens _fMaxResults (\ s a -> s{_fMaxResults = a}) . mapping _Coerce instance FromJSON Feature where parseJSON = withObject "Feature" (\ o -> Feature' <$> (o .:? "type") <*> (o .:? "maxResults")) instance ToJSON Feature where toJSON Feature'{..} = object (catMaybes [("type" .=) <$> _fType, ("maxResults" .=) <$> _fMaxResults]) -- | The \`Status\` type defines a logical error model that is suitable for -- different programming environments, including REST APIs and RPC APIs. It -- is used by [gRPC](https:\/\/github.com\/grpc). The error model is -- designed to be: - Simple to use and understand for most users - Flexible -- enough to meet unexpected needs # Overview The \`Status\` message -- contains three pieces of data: error code, error message, and error -- details. The error code should be an enum value of google.rpc.Code, but -- it may accept additional error codes if needed. The error message should -- be a developer-facing English message that helps developers *understand* -- and *resolve* the error. If a localized user-facing error message is -- needed, put the localized message in the error details or localize it in -- the client. The optional error details may contain arbitrary information -- about the error. There is a predefined set of error detail types in the -- package \`google.rpc\` which can be used for common error conditions. # -- Language mapping The \`Status\` message is the logical representation of -- the error model, but it is not necessarily the actual wire format. When -- the \`Status\` message is exposed in different client libraries and -- different wire protocols, it can be mapped differently. For example, it -- will likely be mapped to some exceptions in Java, but more likely mapped -- to some error codes in C. # Other uses The error model and the -- \`Status\` message can be used in a variety of environments, either with -- or without APIs, to provide a consistent developer experience across -- different environments. Example uses of this error model include: - -- Partial errors. If a service needs to return partial errors to the -- client, it may embed the \`Status\` in the normal response to indicate -- the partial errors. - Workflow errors. A typical workflow has multiple -- steps. Each step may have a \`Status\` message for error reporting -- purpose. - Batch operations. If a client uses batch request and batch -- response, the \`Status\` message should be used directly inside batch -- response, one for each error sub-response. - Asynchronous operations. If -- an API call embeds asynchronous operation results in its response, the -- status of those operations should be represented directly using the -- \`Status\` message. - Logging. If some API errors are stored in logs, -- the message \`Status\` could be used directly after any stripping needed -- for security\/privacy reasons. -- -- /See:/ 'status' smart constructor. data Status = Status' { _sDetails :: !(Maybe [StatusDetailsItem]) , _sCode :: !(Maybe (Textual Int32)) , _sMessage :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Status' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sDetails' -- -- * 'sCode' -- -- * 'sMessage' status :: Status status = Status' { _sDetails = Nothing , _sCode = Nothing , _sMessage = Nothing } -- | A list of messages that carry the error details. There will be a common -- set of message types for APIs to use. sDetails :: Lens' Status [StatusDetailsItem] sDetails = lens _sDetails (\ s a -> s{_sDetails = a}) . _Default . _Coerce -- | The status code, which should be an enum value of google.rpc.Code. sCode :: Lens' Status (Maybe Int32) sCode = lens _sCode (\ s a -> s{_sCode = a}) . mapping _Coerce -- | A developer-facing error message, which should be in English. Any -- user-facing error message should be localized and sent in the -- google.rpc.Status.details field, or localized by the client. sMessage :: Lens' Status (Maybe Text) sMessage = lens _sMessage (\ s a -> s{_sMessage = a}) instance FromJSON Status where parseJSON = withObject "Status" (\ o -> Status' <$> (o .:? "details" .!= mempty) <*> (o .:? "code") <*> (o .:? "message")) instance ToJSON Status where toJSON Status'{..} = object (catMaybes [("details" .=) <$> _sDetails, ("code" .=) <$> _sCode, ("message" .=) <$> _sMessage]) -- | A \`Property\` consists of a user-supplied name\/value pair. -- -- /See:/ 'property' smart constructor. data Property = Property' { _pValue :: !(Maybe Text) , _pName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Property' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pValue' -- -- * 'pName' property :: Property property = Property' { _pValue = Nothing , _pName = Nothing } -- | Value of the property. pValue :: Lens' Property (Maybe Text) pValue = lens _pValue (\ s a -> s{_pValue = a}) -- | Name of the property. pName :: Lens' Property (Maybe Text) pName = lens _pName (\ s a -> s{_pName = a}) instance FromJSON Property where parseJSON = withObject "Property" (\ o -> Property' <$> (o .:? "value") <*> (o .:? "name")) instance ToJSON Property where toJSON Property'{..} = object (catMaybes [("value" .=) <$> _pValue, ("name" .=) <$> _pName]) -- | Client image to perform Google Cloud Vision API tasks over. -- -- /See:/ 'image' smart constructor. data Image = Image' { _iContent :: !(Maybe Bytes) , _iSource :: !(Maybe ImageSource) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Image' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iContent' -- -- * 'iSource' image :: Image image = Image' { _iContent = Nothing , _iSource = Nothing } -- | Image content, represented as a stream of bytes. Note: as with all -- \`bytes\` fields, protobuffers use a pure binary representation, whereas -- JSON representations use base64. iContent :: Lens' Image (Maybe ByteString) iContent = lens _iContent (\ s a -> s{_iContent = a}) . mapping _Bytes -- | Google Cloud Storage image location. If both \`content\` and \`source\` -- are provided for an image, \`content\` takes precedence and is used to -- perform the image annotation request. iSource :: Lens' Image (Maybe ImageSource) iSource = lens _iSource (\ s a -> s{_iSource = a}) instance FromJSON Image where parseJSON = withObject "Image" (\ o -> Image' <$> (o .:? "content") <*> (o .:? "source")) instance ToJSON Image where toJSON Image'{..} = object (catMaybes [("content" .=) <$> _iContent, ("source" .=) <$> _iSource]) -- | A face-specific landmark (for example, a face feature). Landmark -- positions may fall outside the bounds of the image if the face is near -- one or more edges of the image. Therefore it is NOT guaranteed that \`0 -- \<= x \< width\` or \`0 \<= y \< height\`. -- -- /See:/ 'landmark' smart constructor. data Landmark = Landmark' { _lType :: !(Maybe LandmarkType) , _lPosition :: !(Maybe Position) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Landmark' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lType' -- -- * 'lPosition' landmark :: Landmark landmark = Landmark' { _lType = Nothing , _lPosition = Nothing } -- | Face landmark type. lType :: Lens' Landmark (Maybe LandmarkType) lType = lens _lType (\ s a -> s{_lType = a}) -- | Face landmark position. lPosition :: Lens' Landmark (Maybe Position) lPosition = lens _lPosition (\ s a -> s{_lPosition = a}) instance FromJSON Landmark where parseJSON = withObject "Landmark" (\ o -> Landmark' <$> (o .:? "type") <*> (o .:? "position")) instance ToJSON Landmark where toJSON Landmark'{..} = object (catMaybes [("type" .=) <$> _lType, ("position" .=) <$> _lPosition]) -- | Represents a color in the RGBA color space. This representation is -- designed for simplicity of conversion to\/from color representations in -- various languages over compactness; for example, the fields of this -- representation can be trivially provided to the constructor of -- \"java.awt.Color\" in Java; it can also be trivially provided to -- UIColor\'s \"+colorWithRed:green:blue:alpha\" method in iOS; and, with -- just a little work, it can be easily formatted into a CSS \"rgba()\" -- string in JavaScript, as well. Here are some examples: Example (Java): -- import com.google.type.Color; \/\/ ... public static java.awt.Color -- fromProto(Color protocolor) { float alpha = protocolor.hasAlpha() ? -- protocolor.getAlpha().getValue() : 1.0; return new java.awt.Color( -- protocolor.getRed(), protocolor.getGreen(), protocolor.getBlue(), -- alpha); } public static Color toProto(java.awt.Color color) { float red -- = (float) color.getRed(); float green = (float) color.getGreen(); float -- blue = (float) color.getBlue(); float denominator = 255.0; Color.Builder -- resultBuilder = Color .newBuilder() .setRed(red \/ denominator) -- .setGreen(green \/ denominator) .setBlue(blue \/ denominator); int alpha -- = color.getAlpha(); if (alpha != 255) { result.setAlpha( FloatValue -- .newBuilder() .setValue(((float) alpha) \/ denominator) .build()); } -- return resultBuilder.build(); } \/\/ ... Example (iOS \/ Obj-C): \/\/ -- ... static UIColor* fromProto(Color* protocolor) { float red = -- [protocolor red]; float green = [protocolor green]; float blue = -- [protocolor blue]; FloatValue* alpha_wrapper = [protocolor alpha]; float -- alpha = 1.0; if (alpha_wrapper != nil) { alpha = [alpha_wrapper value]; -- } return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; } -- static Color* toProto(UIColor* color) { CGFloat red, green, blue, alpha; -- if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) { return -- nil; } Color* result = [Color alloc] init]; [result setRed:red]; [result -- setGreen:green]; [result setBlue:blue]; if (alpha \<= 0.9999) { [result -- setAlpha:floatWrapperWithValue(alpha)]; } [result autorelease]; return -- result; } \/\/ ... Example (JavaScript): \/\/ ... var protoToCssColor = -- function(rgb_color) { var redFrac = rgb_color.red || 0.0; var greenFrac -- = rgb_color.green || 0.0; var blueFrac = rgb_color.blue || 0.0; var red -- = Math.floor(redFrac * 255); var green = Math.floor(greenFrac * 255); -- var blue = Math.floor(blueFrac * 255); if (!(\'alpha\' in rgb_color)) { -- return rgbToCssColor_(red, green, blue); } var alphaFrac = -- rgb_color.alpha.value || 0.0; var rgbParams = [red, green, -- blue].join(\',\'); return [\'rgba(\', rgbParams, \',\', alphaFrac, -- \')\'].join(\'\'); }; var rgbToCssColor_ = function(red, green, blue) { -- var rgbNumber = new Number((red \<\< 16) | (green \<\< 8) | blue); var -- hexString = rgbNumber.toString(16); var missingZeros = 6 - -- hexString.length; var resultBuilder = [\'#\']; for (var i = 0; i \< -- missingZeros; i++) { resultBuilder.push(\'0\'); } -- resultBuilder.push(hexString); return resultBuilder.join(\'\'); }; \/\/ -- ... -- -- /See:/ 'color' smart constructor. data Color = Color' { _cRed :: !(Maybe (Textual Double)) , _cAlpha :: !(Maybe (Textual Double)) , _cGreen :: !(Maybe (Textual Double)) , _cBlue :: !(Maybe (Textual Double)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Color' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cRed' -- -- * 'cAlpha' -- -- * 'cGreen' -- -- * 'cBlue' color :: Color color = Color' { _cRed = Nothing , _cAlpha = Nothing , _cGreen = Nothing , _cBlue = Nothing } -- | The amount of red in the color as a value in the interval [0, 1]. cRed :: Lens' Color (Maybe Double) cRed = lens _cRed (\ s a -> s{_cRed = a}) . mapping _Coerce -- | The fraction of this color that should be applied to the pixel. That is, -- the final pixel color is defined by the equation: pixel color = alpha * -- (this color) + (1.0 - alpha) * (background color) This means that a -- value of 1.0 corresponds to a solid color, whereas a value of 0.0 -- corresponds to a completely transparent color. This uses a wrapper -- message rather than a simple float scalar so that it is possible to -- distinguish between a default value and the value being unset. If -- omitted, this color object is to be rendered as a solid color (as if the -- alpha value had been explicitly given with a value of 1.0). cAlpha :: Lens' Color (Maybe Double) cAlpha = lens _cAlpha (\ s a -> s{_cAlpha = a}) . mapping _Coerce -- | The amount of green in the color as a value in the interval [0, 1]. cGreen :: Lens' Color (Maybe Double) cGreen = lens _cGreen (\ s a -> s{_cGreen = a}) . mapping _Coerce -- | The amount of blue in the color as a value in the interval [0, 1]. cBlue :: Lens' Color (Maybe Double) cBlue = lens _cBlue (\ s a -> s{_cBlue = a}) . mapping _Coerce instance FromJSON Color where parseJSON = withObject "Color" (\ o -> Color' <$> (o .:? "red") <*> (o .:? "alpha") <*> (o .:? "green") <*> (o .:? "blue")) instance ToJSON Color where toJSON Color'{..} = object (catMaybes [("red" .=) <$> _cRed, ("alpha" .=) <$> _cAlpha, ("green" .=) <$> _cGreen, ("blue" .=) <$> _cBlue]) -- | A bounding polygon for the detected image annotation. -- -- /See:/ 'boundingPoly' smart constructor. newtype BoundingPoly = BoundingPoly' { _bpVertices :: Maybe [Vertex] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'BoundingPoly' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bpVertices' boundingPoly :: BoundingPoly boundingPoly = BoundingPoly' { _bpVertices = Nothing } -- | The bounding polygon vertices. bpVertices :: Lens' BoundingPoly [Vertex] bpVertices = lens _bpVertices (\ s a -> s{_bpVertices = a}) . _Default . _Coerce instance FromJSON BoundingPoly where parseJSON = withObject "BoundingPoly" (\ o -> BoundingPoly' <$> (o .:? "vertices" .!= mempty)) instance ToJSON BoundingPoly where toJSON BoundingPoly'{..} = object (catMaybes [("vertices" .=) <$> _bpVertices]) -- | A vertex represents a 2D point in the image. NOTE: the vertex -- coordinates are in the same scale as the original image. -- -- /See:/ 'vertex' smart constructor. data Vertex = Vertex' { _vX :: !(Maybe (Textual Int32)) , _vY :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Vertex' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vX' -- -- * 'vY' vertex :: Vertex vertex = Vertex' { _vX = Nothing , _vY = Nothing } -- | X coordinate. vX :: Lens' Vertex (Maybe Int32) vX = lens _vX (\ s a -> s{_vX = a}) . mapping _Coerce -- | Y coordinate. vY :: Lens' Vertex (Maybe Int32) vY = lens _vY (\ s a -> s{_vY = a}) . mapping _Coerce instance FromJSON Vertex where parseJSON = withObject "Vertex" (\ o -> Vertex' <$> (o .:? "x") <*> (o .:? "y")) instance ToJSON Vertex where toJSON Vertex'{..} = object (catMaybes [("x" .=) <$> _vX, ("y" .=) <$> _vY]) -- | Detected entity location information. -- -- /See:/ 'locationInfo' smart constructor. newtype LocationInfo = LocationInfo' { _liLatLng :: Maybe LatLng } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LocationInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'liLatLng' locationInfo :: LocationInfo locationInfo = LocationInfo' { _liLatLng = Nothing } -- | lat\/long location coordinates. liLatLng :: Lens' LocationInfo (Maybe LatLng) liLatLng = lens _liLatLng (\ s a -> s{_liLatLng = a}) instance FromJSON LocationInfo where parseJSON = withObject "LocationInfo" (\ o -> LocationInfo' <$> (o .:? "latLng")) instance ToJSON LocationInfo where toJSON LocationInfo'{..} = object (catMaybes [("latLng" .=) <$> _liLatLng]) -- -- /See:/ 'statusDetailsItem' smart constructor. newtype StatusDetailsItem = StatusDetailsItem' { _sdiAddtional :: HashMap Text JSONValue } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'StatusDetailsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdiAddtional' statusDetailsItem :: HashMap Text JSONValue -- ^ 'sdiAddtional' -> StatusDetailsItem statusDetailsItem pSdiAddtional_ = StatusDetailsItem' { _sdiAddtional = _Coerce # pSdiAddtional_ } -- | Properties of the object. Contains field \'type with type URL. sdiAddtional :: Lens' StatusDetailsItem (HashMap Text JSONValue) sdiAddtional = lens _sdiAddtional (\ s a -> s{_sdiAddtional = a}) . _Coerce instance FromJSON StatusDetailsItem where parseJSON = withObject "StatusDetailsItem" (\ o -> StatusDetailsItem' <$> (parseJSONObject o)) instance ToJSON StatusDetailsItem where toJSON = toJSON . _sdiAddtional -- | Multiple image annotation requests are batched into a single service -- call. -- -- /See:/ 'batchAnnotateImagesRequest' smart constructor. newtype BatchAnnotateImagesRequest = BatchAnnotateImagesRequest' { _bairRequests :: Maybe [AnnotateImageRequest] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'BatchAnnotateImagesRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bairRequests' batchAnnotateImagesRequest :: BatchAnnotateImagesRequest batchAnnotateImagesRequest = BatchAnnotateImagesRequest' { _bairRequests = Nothing } -- | Individual image annotation requests for this batch. bairRequests :: Lens' BatchAnnotateImagesRequest [AnnotateImageRequest] bairRequests = lens _bairRequests (\ s a -> s{_bairRequests = a}) . _Default . _Coerce instance FromJSON BatchAnnotateImagesRequest where parseJSON = withObject "BatchAnnotateImagesRequest" (\ o -> BatchAnnotateImagesRequest' <$> (o .:? "requests" .!= mempty)) instance ToJSON BatchAnnotateImagesRequest where toJSON BatchAnnotateImagesRequest'{..} = object (catMaybes [("requests" .=) <$> _bairRequests]) -- | Color information consists of RGB channels, score, and the fraction of -- the image that the color occupies in the image. -- -- /See:/ 'colorInfo' smart constructor. data ColorInfo = ColorInfo' { _ciColor :: !(Maybe Color) , _ciScore :: !(Maybe (Textual Double)) , _ciPixelFraction :: !(Maybe (Textual Double)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ColorInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ciColor' -- -- * 'ciScore' -- -- * 'ciPixelFraction' colorInfo :: ColorInfo colorInfo = ColorInfo' { _ciColor = Nothing , _ciScore = Nothing , _ciPixelFraction = Nothing } -- | RGB components of the color. ciColor :: Lens' ColorInfo (Maybe Color) ciColor = lens _ciColor (\ s a -> s{_ciColor = a}) -- | Image-specific score for this color. Value in range [0, 1]. ciScore :: Lens' ColorInfo (Maybe Double) ciScore = lens _ciScore (\ s a -> s{_ciScore = a}) . mapping _Coerce -- | The fraction of pixels the color occupies in the image. Value in range -- [0, 1]. ciPixelFraction :: Lens' ColorInfo (Maybe Double) ciPixelFraction = lens _ciPixelFraction (\ s a -> s{_ciPixelFraction = a}) . mapping _Coerce instance FromJSON ColorInfo where parseJSON = withObject "ColorInfo" (\ o -> ColorInfo' <$> (o .:? "color") <*> (o .:? "score") <*> (o .:? "pixelFraction")) instance ToJSON ColorInfo where toJSON ColorInfo'{..} = object (catMaybes [("color" .=) <$> _ciColor, ("score" .=) <$> _ciScore, ("pixelFraction" .=) <$> _ciPixelFraction]) -- | Response to an image annotation request. -- -- /See:/ 'annotateImageResponse' smart constructor. data AnnotateImageResponse = AnnotateImageResponse' { _airLogoAnnotations :: !(Maybe [EntityAnnotation]) , _airLabelAnnotations :: !(Maybe [EntityAnnotation]) , _airFaceAnnotations :: !(Maybe [FaceAnnotation]) , _airError :: !(Maybe Status) , _airSafeSearchAnnotation :: !(Maybe SafeSearchAnnotation) , _airLandmarkAnnotations :: !(Maybe [EntityAnnotation]) , _airTextAnnotations :: !(Maybe [EntityAnnotation]) , _airImagePropertiesAnnotation :: !(Maybe ImageProperties) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AnnotateImageResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'airLogoAnnotations' -- -- * 'airLabelAnnotations' -- -- * 'airFaceAnnotations' -- -- * 'airError' -- -- * 'airSafeSearchAnnotation' -- -- * 'airLandmarkAnnotations' -- -- * 'airTextAnnotations' -- -- * 'airImagePropertiesAnnotation' annotateImageResponse :: AnnotateImageResponse annotateImageResponse = AnnotateImageResponse' { _airLogoAnnotations = Nothing , _airLabelAnnotations = Nothing , _airFaceAnnotations = Nothing , _airError = Nothing , _airSafeSearchAnnotation = Nothing , _airLandmarkAnnotations = Nothing , _airTextAnnotations = Nothing , _airImagePropertiesAnnotation = Nothing } -- | If present, logo detection has completed successfully. airLogoAnnotations :: Lens' AnnotateImageResponse [EntityAnnotation] airLogoAnnotations = lens _airLogoAnnotations (\ s a -> s{_airLogoAnnotations = a}) . _Default . _Coerce -- | If present, label detection has completed successfully. airLabelAnnotations :: Lens' AnnotateImageResponse [EntityAnnotation] airLabelAnnotations = lens _airLabelAnnotations (\ s a -> s{_airLabelAnnotations = a}) . _Default . _Coerce -- | If present, face detection has completed successfully. airFaceAnnotations :: Lens' AnnotateImageResponse [FaceAnnotation] airFaceAnnotations = lens _airFaceAnnotations (\ s a -> s{_airFaceAnnotations = a}) . _Default . _Coerce -- | If set, represents the error message for the operation. Note that -- filled-in image annotations are guaranteed to be correct, even when -- \`error\` is set. airError :: Lens' AnnotateImageResponse (Maybe Status) airError = lens _airError (\ s a -> s{_airError = a}) -- | If present, safe-search annotation has completed successfully. airSafeSearchAnnotation :: Lens' AnnotateImageResponse (Maybe SafeSearchAnnotation) airSafeSearchAnnotation = lens _airSafeSearchAnnotation (\ s a -> s{_airSafeSearchAnnotation = a}) -- | If present, landmark detection has completed successfully. airLandmarkAnnotations :: Lens' AnnotateImageResponse [EntityAnnotation] airLandmarkAnnotations = lens _airLandmarkAnnotations (\ s a -> s{_airLandmarkAnnotations = a}) . _Default . _Coerce -- | If present, text (OCR) detection has completed successfully. airTextAnnotations :: Lens' AnnotateImageResponse [EntityAnnotation] airTextAnnotations = lens _airTextAnnotations (\ s a -> s{_airTextAnnotations = a}) . _Default . _Coerce -- | If present, image properties were extracted successfully. airImagePropertiesAnnotation :: Lens' AnnotateImageResponse (Maybe ImageProperties) airImagePropertiesAnnotation = lens _airImagePropertiesAnnotation (\ s a -> s{_airImagePropertiesAnnotation = a}) instance FromJSON AnnotateImageResponse where parseJSON = withObject "AnnotateImageResponse" (\ o -> AnnotateImageResponse' <$> (o .:? "logoAnnotations" .!= mempty) <*> (o .:? "labelAnnotations" .!= mempty) <*> (o .:? "faceAnnotations" .!= mempty) <*> (o .:? "error") <*> (o .:? "safeSearchAnnotation") <*> (o .:? "landmarkAnnotations" .!= mempty) <*> (o .:? "textAnnotations" .!= mempty) <*> (o .:? "imagePropertiesAnnotation")) instance ToJSON AnnotateImageResponse where toJSON AnnotateImageResponse'{..} = object (catMaybes [("logoAnnotations" .=) <$> _airLogoAnnotations, ("labelAnnotations" .=) <$> _airLabelAnnotations, ("faceAnnotations" .=) <$> _airFaceAnnotations, ("error" .=) <$> _airError, ("safeSearchAnnotation" .=) <$> _airSafeSearchAnnotation, ("landmarkAnnotations" .=) <$> _airLandmarkAnnotations, ("textAnnotations" .=) <$> _airTextAnnotations, ("imagePropertiesAnnotation" .=) <$> _airImagePropertiesAnnotation]) -- | Stores image properties, such as dominant colors. -- -- /See:/ 'imageProperties' smart constructor. newtype ImageProperties = ImageProperties' { _ipDominantColors :: Maybe DominantColorsAnnotation } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ImageProperties' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ipDominantColors' imageProperties :: ImageProperties imageProperties = ImageProperties' { _ipDominantColors = Nothing } -- | If present, dominant colors completed successfully. ipDominantColors :: Lens' ImageProperties (Maybe DominantColorsAnnotation) ipDominantColors = lens _ipDominantColors (\ s a -> s{_ipDominantColors = a}) instance FromJSON ImageProperties where parseJSON = withObject "ImageProperties" (\ o -> ImageProperties' <$> (o .:? "dominantColors")) instance ToJSON ImageProperties where toJSON ImageProperties'{..} = object (catMaybes [("dominantColors" .=) <$> _ipDominantColors]) -- | A face annotation object contains the results of face detection. -- -- /See:/ 'faceAnnotation' smart constructor. data FaceAnnotation = FaceAnnotation' { _faTiltAngle :: !(Maybe (Textual Double)) , _faBlurredLikelihood :: !(Maybe FaceAnnotationBlurredLikelihood) , _faBoundingPoly :: !(Maybe BoundingPoly) , _faSurpriseLikelihood :: !(Maybe FaceAnnotationSurpriseLikelihood) , _faLandmarkingConfidence :: !(Maybe (Textual Double)) , _faPanAngle :: !(Maybe (Textual Double)) , _faRollAngle :: !(Maybe (Textual Double)) , _faUnderExposedLikelihood :: !(Maybe FaceAnnotationUnderExposedLikelihood) , _faFdBoundingPoly :: !(Maybe BoundingPoly) , _faAngerLikelihood :: !(Maybe FaceAnnotationAngerLikelihood) , _faDetectionConfidence :: !(Maybe (Textual Double)) , _faHeadwearLikelihood :: !(Maybe FaceAnnotationHeadwearLikelihood) , _faSorrowLikelihood :: !(Maybe FaceAnnotationSorrowLikelihood) , _faJoyLikelihood :: !(Maybe FaceAnnotationJoyLikelihood) , _faLandmarks :: !(Maybe [Landmark]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'FaceAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'faTiltAngle' -- -- * 'faBlurredLikelihood' -- -- * 'faBoundingPoly' -- -- * 'faSurpriseLikelihood' -- -- * 'faLandmarkingConfidence' -- -- * 'faPanAngle' -- -- * 'faRollAngle' -- -- * 'faUnderExposedLikelihood' -- -- * 'faFdBoundingPoly' -- -- * 'faAngerLikelihood' -- -- * 'faDetectionConfidence' -- -- * 'faHeadwearLikelihood' -- -- * 'faSorrowLikelihood' -- -- * 'faJoyLikelihood' -- -- * 'faLandmarks' faceAnnotation :: FaceAnnotation faceAnnotation = FaceAnnotation' { _faTiltAngle = Nothing , _faBlurredLikelihood = Nothing , _faBoundingPoly = Nothing , _faSurpriseLikelihood = Nothing , _faLandmarkingConfidence = Nothing , _faPanAngle = Nothing , _faRollAngle = Nothing , _faUnderExposedLikelihood = Nothing , _faFdBoundingPoly = Nothing , _faAngerLikelihood = Nothing , _faDetectionConfidence = Nothing , _faHeadwearLikelihood = Nothing , _faSorrowLikelihood = Nothing , _faJoyLikelihood = Nothing , _faLandmarks = Nothing } -- | Pitch angle, which indicates the upwards\/downwards angle that the face -- is pointing relative to the image\'s horizontal plane. Range [-180,180]. faTiltAngle :: Lens' FaceAnnotation (Maybe Double) faTiltAngle = lens _faTiltAngle (\ s a -> s{_faTiltAngle = a}) . mapping _Coerce -- | Blurred likelihood. faBlurredLikelihood :: Lens' FaceAnnotation (Maybe FaceAnnotationBlurredLikelihood) faBlurredLikelihood = lens _faBlurredLikelihood (\ s a -> s{_faBlurredLikelihood = a}) -- | The bounding polygon around the face. The coordinates of the bounding -- box are in the original image\'s scale, as returned in \`ImageParams\`. -- The bounding box is computed to \"frame\" the face in accordance with -- human expectations. It is based on the landmarker results. Note that one -- or more x and\/or y coordinates may not be generated in the -- \`BoundingPoly\` (the polygon will be unbounded) if only a partial face -- appears in the image to be annotated. faBoundingPoly :: Lens' FaceAnnotation (Maybe BoundingPoly) faBoundingPoly = lens _faBoundingPoly (\ s a -> s{_faBoundingPoly = a}) -- | Surprise likelihood. faSurpriseLikelihood :: Lens' FaceAnnotation (Maybe FaceAnnotationSurpriseLikelihood) faSurpriseLikelihood = lens _faSurpriseLikelihood (\ s a -> s{_faSurpriseLikelihood = a}) -- | Face landmarking confidence. Range [0, 1]. faLandmarkingConfidence :: Lens' FaceAnnotation (Maybe Double) faLandmarkingConfidence = lens _faLandmarkingConfidence (\ s a -> s{_faLandmarkingConfidence = a}) . mapping _Coerce -- | Yaw angle, which indicates the leftward\/rightward angle that the face -- is pointing relative to the vertical plane perpendicular to the image. -- Range [-180,180]. faPanAngle :: Lens' FaceAnnotation (Maybe Double) faPanAngle = lens _faPanAngle (\ s a -> s{_faPanAngle = a}) . mapping _Coerce -- | Roll angle, which indicates the amount of clockwise\/anti-clockwise -- rotation of the face relative to the image vertical about the axis -- perpendicular to the face. Range [-180,180]. faRollAngle :: Lens' FaceAnnotation (Maybe Double) faRollAngle = lens _faRollAngle (\ s a -> s{_faRollAngle = a}) . mapping _Coerce -- | Under-exposed likelihood. faUnderExposedLikelihood :: Lens' FaceAnnotation (Maybe FaceAnnotationUnderExposedLikelihood) faUnderExposedLikelihood = lens _faUnderExposedLikelihood (\ s a -> s{_faUnderExposedLikelihood = a}) -- | The \`fd_bounding_poly\` bounding polygon is tighter than the -- \`boundingPoly\`, and encloses only the skin part of the face. -- Typically, it is used to eliminate the face from any image analysis that -- detects the \"amount of skin\" visible in an image. It is not based on -- the landmarker results, only on the initial face detection, hence the -- 'fd' (face detection) prefix. faFdBoundingPoly :: Lens' FaceAnnotation (Maybe BoundingPoly) faFdBoundingPoly = lens _faFdBoundingPoly (\ s a -> s{_faFdBoundingPoly = a}) -- | Anger likelihood. faAngerLikelihood :: Lens' FaceAnnotation (Maybe FaceAnnotationAngerLikelihood) faAngerLikelihood = lens _faAngerLikelihood (\ s a -> s{_faAngerLikelihood = a}) -- | Detection confidence. Range [0, 1]. faDetectionConfidence :: Lens' FaceAnnotation (Maybe Double) faDetectionConfidence = lens _faDetectionConfidence (\ s a -> s{_faDetectionConfidence = a}) . mapping _Coerce -- | Headwear likelihood. faHeadwearLikelihood :: Lens' FaceAnnotation (Maybe FaceAnnotationHeadwearLikelihood) faHeadwearLikelihood = lens _faHeadwearLikelihood (\ s a -> s{_faHeadwearLikelihood = a}) -- | Sorrow likelihood. faSorrowLikelihood :: Lens' FaceAnnotation (Maybe FaceAnnotationSorrowLikelihood) faSorrowLikelihood = lens _faSorrowLikelihood (\ s a -> s{_faSorrowLikelihood = a}) -- | Joy likelihood. faJoyLikelihood :: Lens' FaceAnnotation (Maybe FaceAnnotationJoyLikelihood) faJoyLikelihood = lens _faJoyLikelihood (\ s a -> s{_faJoyLikelihood = a}) -- | Detected face landmarks. faLandmarks :: Lens' FaceAnnotation [Landmark] faLandmarks = lens _faLandmarks (\ s a -> s{_faLandmarks = a}) . _Default . _Coerce instance FromJSON FaceAnnotation where parseJSON = withObject "FaceAnnotation" (\ o -> FaceAnnotation' <$> (o .:? "tiltAngle") <*> (o .:? "blurredLikelihood") <*> (o .:? "boundingPoly") <*> (o .:? "surpriseLikelihood") <*> (o .:? "landmarkingConfidence") <*> (o .:? "panAngle") <*> (o .:? "rollAngle") <*> (o .:? "underExposedLikelihood") <*> (o .:? "fdBoundingPoly") <*> (o .:? "angerLikelihood") <*> (o .:? "detectionConfidence") <*> (o .:? "headwearLikelihood") <*> (o .:? "sorrowLikelihood") <*> (o .:? "joyLikelihood") <*> (o .:? "landmarks" .!= mempty)) instance ToJSON FaceAnnotation where toJSON FaceAnnotation'{..} = object (catMaybes [("tiltAngle" .=) <$> _faTiltAngle, ("blurredLikelihood" .=) <$> _faBlurredLikelihood, ("boundingPoly" .=) <$> _faBoundingPoly, ("surpriseLikelihood" .=) <$> _faSurpriseLikelihood, ("landmarkingConfidence" .=) <$> _faLandmarkingConfidence, ("panAngle" .=) <$> _faPanAngle, ("rollAngle" .=) <$> _faRollAngle, ("underExposedLikelihood" .=) <$> _faUnderExposedLikelihood, ("fdBoundingPoly" .=) <$> _faFdBoundingPoly, ("angerLikelihood" .=) <$> _faAngerLikelihood, ("detectionConfidence" .=) <$> _faDetectionConfidence, ("headwearLikelihood" .=) <$> _faHeadwearLikelihood, ("sorrowLikelihood" .=) <$> _faSorrowLikelihood, ("joyLikelihood" .=) <$> _faJoyLikelihood, ("landmarks" .=) <$> _faLandmarks]) -- | Set of detected entity features. -- -- /See:/ 'entityAnnotation' smart constructor. data EntityAnnotation = EntityAnnotation' { _eaScore :: !(Maybe (Textual Double)) , _eaTopicality :: !(Maybe (Textual Double)) , _eaLocale :: !(Maybe Text) , _eaBoundingPoly :: !(Maybe BoundingPoly) , _eaConfidence :: !(Maybe (Textual Double)) , _eaMid :: !(Maybe Text) , _eaLocations :: !(Maybe [LocationInfo]) , _eaDescription :: !(Maybe Text) , _eaProperties :: !(Maybe [Property]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'EntityAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eaScore' -- -- * 'eaTopicality' -- -- * 'eaLocale' -- -- * 'eaBoundingPoly' -- -- * 'eaConfidence' -- -- * 'eaMid' -- -- * 'eaLocations' -- -- * 'eaDescription' -- -- * 'eaProperties' entityAnnotation :: EntityAnnotation entityAnnotation = EntityAnnotation' { _eaScore = Nothing , _eaTopicality = Nothing , _eaLocale = Nothing , _eaBoundingPoly = Nothing , _eaConfidence = Nothing , _eaMid = Nothing , _eaLocations = Nothing , _eaDescription = Nothing , _eaProperties = Nothing } -- | Overall score of the result. Range [0, 1]. eaScore :: Lens' EntityAnnotation (Maybe Double) eaScore = lens _eaScore (\ s a -> s{_eaScore = a}) . mapping _Coerce -- | The relevancy of the ICA (Image Content Annotation) label to the image. -- For example, the relevancy of \"tower\" is likely higher to an image -- containing the detected \"Eiffel Tower\" than to an image containing a -- detected distant towering building, even though the confidence that -- there is a tower in each image may be the same. Range [0, 1]. eaTopicality :: Lens' EntityAnnotation (Maybe Double) eaTopicality = lens _eaTopicality (\ s a -> s{_eaTopicality = a}) . mapping _Coerce -- | The language code for the locale in which the entity textual -- \`description\` is expressed. eaLocale :: Lens' EntityAnnotation (Maybe Text) eaLocale = lens _eaLocale (\ s a -> s{_eaLocale = a}) -- | Image region to which this entity belongs. Currently not produced for -- \`LABEL_DETECTION\` features. For \`TEXT_DETECTION\` (OCR), -- \`boundingPoly\`s are produced for the entire text detected in an image -- region, followed by \`boundingPoly\`s for each word within the detected -- text. eaBoundingPoly :: Lens' EntityAnnotation (Maybe BoundingPoly) eaBoundingPoly = lens _eaBoundingPoly (\ s a -> s{_eaBoundingPoly = a}) -- | The accuracy of the entity detection in an image. For example, for an -- image in which the \"Eiffel Tower\" entity is detected, this field -- represents the confidence that there is a tower in the query image. -- Range [0, 1]. eaConfidence :: Lens' EntityAnnotation (Maybe Double) eaConfidence = lens _eaConfidence (\ s a -> s{_eaConfidence = a}) . mapping _Coerce -- | Opaque entity ID. Some IDs may be available in [Google Knowledge Graph -- Search API](https:\/\/developers.google.com\/knowledge-graph\/). eaMid :: Lens' EntityAnnotation (Maybe Text) eaMid = lens _eaMid (\ s a -> s{_eaMid = a}) -- | The location information for the detected entity. Multiple -- \`LocationInfo\` elements can be present because one location may -- indicate the location of the scene in the image, and another location -- may indicate the location of the place where the image was taken. -- Location information is usually present for landmarks. eaLocations :: Lens' EntityAnnotation [LocationInfo] eaLocations = lens _eaLocations (\ s a -> s{_eaLocations = a}) . _Default . _Coerce -- | Entity textual description, expressed in its \`locale\` language. eaDescription :: Lens' EntityAnnotation (Maybe Text) eaDescription = lens _eaDescription (\ s a -> s{_eaDescription = a}) -- | Some entities may have optional user-supplied \`Property\` (name\/value) -- fields, such a score or string that qualifies the entity. eaProperties :: Lens' EntityAnnotation [Property] eaProperties = lens _eaProperties (\ s a -> s{_eaProperties = a}) . _Default . _Coerce instance FromJSON EntityAnnotation where parseJSON = withObject "EntityAnnotation" (\ o -> EntityAnnotation' <$> (o .:? "score") <*> (o .:? "topicality") <*> (o .:? "locale") <*> (o .:? "boundingPoly") <*> (o .:? "confidence") <*> (o .:? "mid") <*> (o .:? "locations" .!= mempty) <*> (o .:? "description") <*> (o .:? "properties" .!= mempty)) instance ToJSON EntityAnnotation where toJSON EntityAnnotation'{..} = object (catMaybes [("score" .=) <$> _eaScore, ("topicality" .=) <$> _eaTopicality, ("locale" .=) <$> _eaLocale, ("boundingPoly" .=) <$> _eaBoundingPoly, ("confidence" .=) <$> _eaConfidence, ("mid" .=) <$> _eaMid, ("locations" .=) <$> _eaLocations, ("description" .=) <$> _eaDescription, ("properties" .=) <$> _eaProperties]) -- | Request for performing Google Cloud Vision API tasks over a -- user-provided image, with user-requested features. -- -- /See:/ 'annotateImageRequest' smart constructor. data AnnotateImageRequest = AnnotateImageRequest' { _airImage :: !(Maybe Image) , _airFeatures :: !(Maybe [Feature]) , _airImageContext :: !(Maybe ImageContext) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AnnotateImageRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'airImage' -- -- * 'airFeatures' -- -- * 'airImageContext' annotateImageRequest :: AnnotateImageRequest annotateImageRequest = AnnotateImageRequest' { _airImage = Nothing , _airFeatures = Nothing , _airImageContext = Nothing } -- | The image to be processed. airImage :: Lens' AnnotateImageRequest (Maybe Image) airImage = lens _airImage (\ s a -> s{_airImage = a}) -- | Requested features. airFeatures :: Lens' AnnotateImageRequest [Feature] airFeatures = lens _airFeatures (\ s a -> s{_airFeatures = a}) . _Default . _Coerce -- | Additional context that may accompany the image. airImageContext :: Lens' AnnotateImageRequest (Maybe ImageContext) airImageContext = lens _airImageContext (\ s a -> s{_airImageContext = a}) instance FromJSON AnnotateImageRequest where parseJSON = withObject "AnnotateImageRequest" (\ o -> AnnotateImageRequest' <$> (o .:? "image") <*> (o .:? "features" .!= mempty) <*> (o .:? "imageContext")) instance ToJSON AnnotateImageRequest where toJSON AnnotateImageRequest'{..} = object (catMaybes [("image" .=) <$> _airImage, ("features" .=) <$> _airFeatures, ("imageContext" .=) <$> _airImageContext]) -- | External image source (Google Cloud Storage image location). -- -- /See:/ 'imageSource' smart constructor. newtype ImageSource = ImageSource' { _isGcsImageURI :: Maybe Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ImageSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'isGcsImageURI' imageSource :: ImageSource imageSource = ImageSource' { _isGcsImageURI = Nothing } -- | Google Cloud Storage image URI, which must be in the following form: -- \`gs:\/\/bucket_name\/object_name\` (for details, see [Google Cloud -- Storage Request -- URIs](https:\/\/cloud.google.com\/storage\/docs\/reference-uris)). NOTE: -- Cloud Storage object versioning is not supported. isGcsImageURI :: Lens' ImageSource (Maybe Text) isGcsImageURI = lens _isGcsImageURI (\ s a -> s{_isGcsImageURI = a}) instance FromJSON ImageSource where parseJSON = withObject "ImageSource" (\ o -> ImageSource' <$> (o .:? "gcsImageUri")) instance ToJSON ImageSource where toJSON ImageSource'{..} = object (catMaybes [("gcsImageUri" .=) <$> _isGcsImageURI]) -- -- /See:/ 'safeSearchAnnotation' smart constructor. data SafeSearchAnnotation = SafeSearchAnnotation' { _ssaSpoof :: !(Maybe SafeSearchAnnotationSpoof) , _ssaAdult :: !(Maybe SafeSearchAnnotationAdult) , _ssaMedical :: !(Maybe SafeSearchAnnotationMedical) , _ssaViolence :: !(Maybe SafeSearchAnnotationViolence) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'SafeSearchAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ssaSpoof' -- -- * 'ssaAdult' -- -- * 'ssaMedical' -- -- * 'ssaViolence' safeSearchAnnotation :: SafeSearchAnnotation safeSearchAnnotation = SafeSearchAnnotation' { _ssaSpoof = Nothing , _ssaAdult = Nothing , _ssaMedical = Nothing , _ssaViolence = Nothing } -- | Spoof likelihood. The likelihood that an modification was made to the -- image\'s canonical version to make it appear funny or offensive. ssaSpoof :: Lens' SafeSearchAnnotation (Maybe SafeSearchAnnotationSpoof) ssaSpoof = lens _ssaSpoof (\ s a -> s{_ssaSpoof = a}) -- | Represents the adult content likelihood for the image. ssaAdult :: Lens' SafeSearchAnnotation (Maybe SafeSearchAnnotationAdult) ssaAdult = lens _ssaAdult (\ s a -> s{_ssaAdult = a}) -- | Likelihood that this is a medical image. ssaMedical :: Lens' SafeSearchAnnotation (Maybe SafeSearchAnnotationMedical) ssaMedical = lens _ssaMedical (\ s a -> s{_ssaMedical = a}) -- | Violence likelihood. ssaViolence :: Lens' SafeSearchAnnotation (Maybe SafeSearchAnnotationViolence) ssaViolence = lens _ssaViolence (\ s a -> s{_ssaViolence = a}) instance FromJSON SafeSearchAnnotation where parseJSON = withObject "SafeSearchAnnotation" (\ o -> SafeSearchAnnotation' <$> (o .:? "spoof") <*> (o .:? "adult") <*> (o .:? "medical") <*> (o .:? "violence")) instance ToJSON SafeSearchAnnotation where toJSON SafeSearchAnnotation'{..} = object (catMaybes [("spoof" .=) <$> _ssaSpoof, ("adult" .=) <$> _ssaAdult, ("medical" .=) <$> _ssaMedical, ("violence" .=) <$> _ssaViolence]) -- | Image context and\/or feature-specific parameters. -- -- /See:/ 'imageContext' smart constructor. data ImageContext = ImageContext' { _icLanguageHints :: !(Maybe [Text]) , _icLatLongRect :: !(Maybe LatLongRect) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ImageContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'icLanguageHints' -- -- * 'icLatLongRect' imageContext :: ImageContext imageContext = ImageContext' { _icLanguageHints = Nothing , _icLatLongRect = Nothing } -- | List of languages to use for TEXT_DETECTION. In most cases, an empty -- value yields the best results since it enables automatic language -- detection. For languages based on the Latin alphabet, setting -- \`language_hints\` is not needed. In rare cases, when the language of -- the text in the image is known, setting a hint will help get better -- results (although it will be a significant hindrance if the hint is -- wrong). Text detection returns an error if one or more of the specified -- languages is not one of the [supported -- languages](\/vision\/docs\/languages). icLanguageHints :: Lens' ImageContext [Text] icLanguageHints = lens _icLanguageHints (\ s a -> s{_icLanguageHints = a}) . _Default . _Coerce -- | lat\/long rectangle that specifies the location of the image. icLatLongRect :: Lens' ImageContext (Maybe LatLongRect) icLatLongRect = lens _icLatLongRect (\ s a -> s{_icLatLongRect = a}) instance FromJSON ImageContext where parseJSON = withObject "ImageContext" (\ o -> ImageContext' <$> (o .:? "languageHints" .!= mempty) <*> (o .:? "latLongRect")) instance ToJSON ImageContext where toJSON ImageContext'{..} = object (catMaybes [("languageHints" .=) <$> _icLanguageHints, ("latLongRect" .=) <$> _icLatLongRect]) -- | Set of dominant colors and their corresponding scores. -- -- /See:/ 'dominantColorsAnnotation' smart constructor. newtype DominantColorsAnnotation = DominantColorsAnnotation' { _dcaColors :: Maybe [ColorInfo] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DominantColorsAnnotation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcaColors' dominantColorsAnnotation :: DominantColorsAnnotation dominantColorsAnnotation = DominantColorsAnnotation' { _dcaColors = Nothing } -- | RGB color values with their score and pixel fraction. dcaColors :: Lens' DominantColorsAnnotation [ColorInfo] dcaColors = lens _dcaColors (\ s a -> s{_dcaColors = a}) . _Default . _Coerce instance FromJSON DominantColorsAnnotation where parseJSON = withObject "DominantColorsAnnotation" (\ o -> DominantColorsAnnotation' <$> (o .:? "colors" .!= mempty)) instance ToJSON DominantColorsAnnotation where toJSON DominantColorsAnnotation'{..} = object (catMaybes [("colors" .=) <$> _dcaColors]) -- | Rectangle determined by min and max \`LatLng\` pairs. -- -- /See:/ 'latLongRect' smart constructor. data LatLongRect = LatLongRect' { _llrMaxLatLng :: !(Maybe LatLng) , _llrMinLatLng :: !(Maybe LatLng) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LatLongRect' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'llrMaxLatLng' -- -- * 'llrMinLatLng' latLongRect :: LatLongRect latLongRect = LatLongRect' { _llrMaxLatLng = Nothing , _llrMinLatLng = Nothing } -- | Max lat\/long pair. llrMaxLatLng :: Lens' LatLongRect (Maybe LatLng) llrMaxLatLng = lens _llrMaxLatLng (\ s a -> s{_llrMaxLatLng = a}) -- | Min lat\/long pair. llrMinLatLng :: Lens' LatLongRect (Maybe LatLng) llrMinLatLng = lens _llrMinLatLng (\ s a -> s{_llrMinLatLng = a}) instance FromJSON LatLongRect where parseJSON = withObject "LatLongRect" (\ o -> LatLongRect' <$> (o .:? "maxLatLng") <*> (o .:? "minLatLng")) instance ToJSON LatLongRect where toJSON LatLongRect'{..} = object (catMaybes [("maxLatLng" .=) <$> _llrMaxLatLng, ("minLatLng" .=) <$> _llrMinLatLng]) -- | Response to a batch image annotation request. -- -- /See:/ 'batchAnnotateImagesResponse' smart constructor. newtype BatchAnnotateImagesResponse = BatchAnnotateImagesResponse' { _bairResponses :: Maybe [AnnotateImageResponse] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'BatchAnnotateImagesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bairResponses' batchAnnotateImagesResponse :: BatchAnnotateImagesResponse batchAnnotateImagesResponse = BatchAnnotateImagesResponse' { _bairResponses = Nothing } -- | Individual responses to image annotation requests within the batch. bairResponses :: Lens' BatchAnnotateImagesResponse [AnnotateImageResponse] bairResponses = lens _bairResponses (\ s a -> s{_bairResponses = a}) . _Default . _Coerce instance FromJSON BatchAnnotateImagesResponse where parseJSON = withObject "BatchAnnotateImagesResponse" (\ o -> BatchAnnotateImagesResponse' <$> (o .:? "responses" .!= mempty)) instance ToJSON BatchAnnotateImagesResponse where toJSON BatchAnnotateImagesResponse'{..} = object (catMaybes [("responses" .=) <$> _bairResponses]) -- | A 3D position in the image, used primarily for Face detection landmarks. -- A valid Position must have both x and y coordinates. The position -- coordinates are in the same scale as the original image. -- -- /See:/ 'position' smart constructor. data Position = Position' { _pZ :: !(Maybe (Textual Double)) , _pX :: !(Maybe (Textual Double)) , _pY :: !(Maybe (Textual Double)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Position' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pZ' -- -- * 'pX' -- -- * 'pY' position :: Position position = Position' { _pZ = Nothing , _pX = Nothing , _pY = Nothing } -- | Z coordinate (or depth). pZ :: Lens' Position (Maybe Double) pZ = lens _pZ (\ s a -> s{_pZ = a}) . mapping _Coerce -- | X coordinate. pX :: Lens' Position (Maybe Double) pX = lens _pX (\ s a -> s{_pX = a}) . mapping _Coerce -- | Y coordinate. pY :: Lens' Position (Maybe Double) pY = lens _pY (\ s a -> s{_pY = a}) . mapping _Coerce instance FromJSON Position where parseJSON = withObject "Position" (\ o -> Position' <$> (o .:? "z") <*> (o .:? "x") <*> (o .:? "y")) instance ToJSON Position where toJSON Position'{..} = object (catMaybes [("z" .=) <$> _pZ, ("x" .=) <$> _pX, ("y" .=) <$> _pY])
rueshyna/gogol
gogol-vision/gen/Network/Google/Vision/Types/Product.hs
mpl-2.0
59,418
0
25
13,934
10,017
5,790
4,227
1,070
1
{- ORMOLU_DISABLE -} -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca) -- Released under the GNU GPL, see LICENSE -- FIXME: document why we need each of these. {-# LANGUAGE ScopedTypeVariables #-} import Prelude(IO, Show, String, Int, Maybe(Just,Nothing), Eq, return, ($), show, fmap, (<>), putStrLn, filter, zip, null, undefined, const, Bool(True,False), fst, (.), head, tail, length, (/=), (+), error, print) import Graphics.Implicit.ExtOpenScad.Primitives (primitiveModules) import Graphics.Implicit.ExtOpenScad.Definitions (ArgParser(AP,APFail,APExample,APTest,APTerminator,APBranch), Symbol(Symbol), OVal(ONModule), SourcePosition(SourcePosition), StateC) import qualified Control.Exception as Ex (catch, SomeException) import Control.Monad (forM_) import Data.Traversable (traverse) import Data.Text.Lazy (unpack, pack) -- | Return true if the argument is of type ExampleDoc. isExample :: DocPart -> Bool isExample (ExampleDoc _ ) = True isExample _ = False -- | Return true if the argument is of type ArgumentDoc. isArgument :: DocPart -> Bool isArgument (ArgumentDoc _ _ _) = True isArgument _ = False -- | Return true if the argument is of type Branch. isBranch :: DocPart -> Bool isBranch (Branch _) = True isBranch _ = False dumpPrimitive :: Symbol -> [DocPart] -> Int -> IO () dumpPrimitive (Symbol moduleName) moduleDocList level = do let examples = filter isExample moduleDocList arguments = filter isArgument moduleDocList syntaxes = filter isBranch moduleDocList moduleLabel = unpack moduleName if level /= 0 then putStrLn $ "#" <> moduleLabel else do putStrLn moduleLabel putStrLn (fmap (const '-') moduleLabel) putStrLn "" if null examples then return () else do putStrLn "#Examples:\n" forM_ examples $ \(ExampleDoc example) -> putStrLn $ " * `" <> example <> "`" putStrLn "" if null arguments then return () else do if level /= 0 then putStrLn "##Arguments:\n" else if null syntaxes then putStrLn "#Arguments:\n" else putStrLn "#Shared Arguments:\n" forM_ arguments $ \(ArgumentDoc (Symbol name) posfallback description) -> case (posfallback, description) of (Nothing, "") -> putStrLn $ " * `" <> unpack name <> "`" (Just fallback, "") -> putStrLn $ " * `" <> unpack name <> " = " <> fallback <> "`" (Nothing, _) -> do putStrLn $ " * `" <> unpack name <> "`" putStrLn $ " " <> description (Just fallback, _) -> do putStrLn $ " * `" <> unpack name <> " = " <> fallback <> "`" putStrLn $ " " <> description putStrLn "" if null syntaxes then return () else forM_ syntaxes $ \(Branch syntax) -> dumpPrimitive (Symbol $ pack $ "Syntax " <> show (level+1)) syntax (level+1) -- | Our entrypoint. Generate one document describing all of our primitives. main :: IO () main = do docs <- traverse (getArgParserDocs.getArgParserFrom) primitiveModules let names = fmap fst primitiveModules docname = "ImplicitCAD Primitives" putStrLn (fmap (const '=') docname) putStrLn docname putStrLn (fmap (const '=') docname) putStrLn "" putStrLn "" forM_ (zip names docs) $ \(moduleName, moduleDocList) -> dumpPrimitive moduleName moduleDocList 0 where getArgParserFrom :: (Symbol, OVal) -> ArgParser(StateC [OVal]) getArgParserFrom (_, ONModule _ implementation _) = implementation sourcePosition [] where sourcePosition = SourcePosition 0 0 "docgen" getArgParserFrom (_, _) = error "bad value in primitive array." -- | the format we extract documentation into data Doc = Doc String [DocPart] deriving (Show) data DocPart = ExampleDoc String | ArgumentDoc Symbol (Maybe String) String | Branch [DocPart] | Empty deriving (Show, Eq) -- Here there be dragons! -- Because we made this a Monad instead of applicative functor, there's no sane way to do this. -- We give undefined (= an error) and let laziness prevent if from ever being touched. -- We're using IO so that we can catch an error if this backfires. -- If so, we *back off*. -- | Extract Documentation from an ArgParser getArgParserDocs :: ArgParser a -- ^ ArgParser(s) -> IO [DocPart] -- ^ Docs (sadly IO wrapped) getArgParserDocs (AP name fallback doc fnext) = do otherDocs <- Ex.catch (getArgParserDocs $ fnext undefined) (\(_ :: Ex.SomeException) -> return []) if otherDocs /= [Empty] then return $ ArgumentDoc name (fmap show fallback) (unpack doc) : otherDocs else return [ArgumentDoc name (fmap show fallback) (unpack doc)] getArgParserDocs (APExample str child) = do childResults <- getArgParserDocs child return $ ExampleDoc (unpack str):childResults -- We try to look at as little as possible, to avoid the risk of triggering an error. -- Yay laziness! getArgParserDocs (APTest _ _ child) = getArgParserDocs child -- To look at these would almost certainly be death (exception) getArgParserDocs (APTerminator _) = return [Empty] getArgParserDocs (APFail _) = return [Empty] -- This one confuses me. getArgParserDocs (APBranch children) = do print (length children) otherDocs <- Ex.catch (getArgParserDocs (APBranch $ tail children)) (\(_ :: Ex.SomeException) -> return []) aResults <- getArgParserDocs $ head children if otherDocs /= [Empty] then return [Branch (aResults <> otherDocs)] else return aResults
colah/ImplicitCAD
programs/docgen.hs
agpl-3.0
5,805
0
21
1,481
1,573
832
741
107
10
module Main where import Data.List -- | String split in style of python string.split() split :: String -> String -> [String] split tok splitme = unfoldr (sp1 tok) splitme where sp1 _ "" = Nothing sp1 t s = case find (t `isSuffixOf`) (inits s) of Nothing -> Just (s, "") Just p -> Just (take ((length p) - (length t)) p, drop (length p) s) toint x = read x :: Int prob99 input = show (maximum values ) where exp [a,b] = a^b mylines = lines input mynumbers = map ((map toint).split ",") mylines values = map exp mynumbers main = interact (prob99)
jdavidberger/project-euler
prob99.hs
lgpl-3.0
673
0
16
233
262
136
126
16
3
mergeSort :: (Ord a) => [a] -> [a] mergeSort [] = [] mergeSort [x] = [x] mergeSort xs = merge (mergeSort part1) (mergeSort part2) where midIndex = (length xs) `div` 2 part1 = take midIndex xs part2 = drop midIndex xs merge :: (Ord a) => [a] -> [a] -> [a] merge [] [] = [] merge xs [] = xs merge [] ys = ys merge xs@(x:restOfX) ys@(y:restOfY) | x < y = x : (merge restOfX ys) | otherwise = y : (merge xs restOfY) main = do putStrLn $ mergeSort [] putStrLn $ show $ mergeSort [1] putStrLn $ show $ mergeSort [1, 2] putStrLn $ show $ mergeSort [2, 1] putStrLn $ show $ mergeSort [1, 2, 3] putStrLn $ show $ mergeSort [1, 3, 2] putStrLn $ show $ mergeSort [2, 1, 3] putStrLn $ show $ mergeSort [2, 3, 1] putStrLn $ show $ mergeSort [3, 1, 2] putStrLn $ show $ mergeSort [3, 2, 1]
dkandalov/katas
haskell/sort/merge-sort/merge-sort2.hs
unlicense
850
0
9
236
471
244
227
25
1
{-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Main where import ClassyPrelude hiding ((</>), (<>)) import Data.Monoid import qualified Data.Text as T import Filesystem (getHomeDirectory) import qualified Filesystem.Path.CurrentOS as FS import Options.Applicative (execParser) import Shelly import CabalNew.Cabal import CabalNew.Common import CabalNew.Files import CabalNew.Git import CabalNew.Opts import CabalNew.Sandbox import CabalNew.Types import CabalNew.Yesod default (T.Text) main :: IO () main = do config@CabalNew{..} <- execParser opts shelly $ verbosely $ do rootDir <- configDir projectRootDir let config' = config { projectRootDir = FS.encodeString rootDir } projectDir = rootDir </> T.pack projectName mkdir_p projectDir chdir projectDir $ do init config patch <- case projectTarget of Executable -> cabalProject config' projectDir Library -> cabalProject config' projectDir Yesod -> yesodProject config' projectDir GhcJs -> cabalProject config' projectDir Sandbox -> sandboxProject config' projectDir withCommit projectGitLevel "apply hs project" $ do patch unless (projectTarget == Sandbox) $ patchProject config' agIgnore config' publish privateProject projectGitLevel $ T.pack projectSynopsis gitVogue projectGitLevel when projectTmuxifier $ tmuxLayout config echo "done."
erochest/cabal-new
CabalNew.hs
apache-2.0
1,956
0
19
691
378
193
185
48
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE GADTs #-} --{-# LANGUAGE OverloadedRecordFields #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} module GLWidgetPP where import GHC.Generics import Linear import Control.Monad import Control.Monad.IO.Class import Control.Monad.State.Strict hiding (forM) import Language.Haskell.TH import Graphics.Rendering.OpenGL hiding (position,get) import Graphics.Rendering.OpenGL.GLU import qualified Graphics.Rendering.FTGL as FTGL import Foreign.C.Types import GHC.Generics import Data.List.Split import Prelude hiding ((.)) import Control.Category import GLUtil import Util import qualified Config import SDL.Input.Keyboard import qualified Control.Monad.Identity as I import Lens --data GLWidget s = forall w . Widget w => GLWidget (w s) --data GLWidget s = GLText (Text s) -- | GLPanel (Panel s) data GLWidget = forall w . Widget w => GLWidget w -- WidgetPack :: Widget a => a -> GLWidget --withGLWidget :: (Monad m, Widget a) => StateT (a s) m r -> StateT GLWidget m r --withGLWidget comp = do -- GLWidget w <- get -- (ret, new_w) <- lift $ runStateT comp w -- put $ GLWidget new_w -- return ret type WidgetHandlerT statetype widgettype eventtype m = eventtype -> Lens statetype widgettype -> StateT statetype m () type WidgetHandler s w e = WidgetHandlerT s w e I.Identity type KeyInput = Either Keycode Scancode type TextInput = String type KeyHandlerT statetype widgettype m = WidgetHandlerT statetype widgettype KeyInput m type TextHandlerT statetype widgettype m = WidgetHandlerT statetype widgettype TextInput m type KeyHandler s w = KeyHandlerT s w I.Identity type TextHandler s w = TextHandlerT s w I.Identity data KeyHandlerD w = MkKeyHandlerD (Monad m => KeyInput -> Lens s w -> StateT s m ()) data TextHandlerD w = MkTextHandlerD (Monad m => TextInput -> Lens s w -> StateT s m ()) --type KeyHandler w = forall m . Monad m => Either Keycode Scancode -> StateT w m () --type ChangeHandler w = forall m . Monad m => StateT w m () data Base w = Base {focused :: Bool ,position :: V2 CFloat ,padding :: V2 CFloat ,size :: V2 CFloat ,bounds :: (V2 CFloat, V2 CFloat) ,content_size :: V2 CFloat ,handler_key :: KeyHandlerD w ,handler_change :: TextHandlerD w } --temp :: Lens Base (ChangeHandler Base) --temp = Lens -- (handler_change :: Base -> ChangeHandler Base) -- (\ old_data -- -> \ (new_value :: ChangeHandler Base) -- -> old_data {handler_change = new_value}) data Text = Text {text_base :: Base Text ,text_content :: [String] ,text_font :: FTGL.Font ,text_cursor :: V2 Int } data Arrangement = Horizontal | Vertical | None deriving (Eq, Ord, Show, Generic) data Panel = Panel {panel_base :: Base Panel ,panel_focus_index :: Int ,panel_wrap_focus :: Bool ,panel_arrange :: Arrangement ,panel_content :: [GLWidget]} --data GLWidget s = GLText (Text s) -- | GLPanel (Panel s) -- deriving (Generic) class Widget t where widget_super :: t -> GLWidget widget_position :: Lens t (V2 GLfloat) widget_size :: Lens t (V2 GLfloat) widget_content_size :: Lens t (V2 GLfloat) widget_bounds :: Lens t (V2 GLfloat, V2 GLfloat) widget_handler_key :: Lens t (KeyHandlerD t) widget_handler_change :: Lens t (TextHandlerD t) widget_render :: MonadIO m => StateT t m () widget_refit :: Monad m => StateT t m () widget_create :: Monad m => m t widget_has_focus :: Monad m => StateT t m Bool widget_next_focus :: Monad m => StateT t m (Maybe Int) widget_handle_key :: (Monad m) => KeyHandlerT s t m widget_handle_change :: (Monad m) => TextHandlerT s t m --inWidget :: forall s . Lens (GLWidget s) (Widget w => (w s)) --inWidget f = Lens -- (\ (GLWidget w) -> (f w)) -- (\ (GLWidget w) w' -> GLWidget (f w')) makeInWidget f = [e| do GLWidget w <- get (ret, w') <- runStateT $(varE f) w put $ GLWidget w' return ret |] -- Lens w r -> Lens GLWidget r --makeInWidgetLens l = -- [| \ f glw -> fmap ( -- ( \ (GLWidget w) -> (lens_getter $(varE l)) w ) -- ( \ (GLWidget w) p -> GLWidget ((lens_putter $(varE l)) w p) ) -- |] ---- Lens s (w s) -> Lens s (GLWidget s) --makeOutWidgetLens l = -- [| Lens -- ( \ s -> widget_super ((lens_getter $(varE l)) s ) ) -- ( \ s p -> widget_super ((lens_putter $(varE l)) s p) ) -- |] -- Lens s (GLWidget s) -> Lens s (w s) --makeOutWidgetLens l t = do -- s <- newName "s" -- p <- newName "p" -- w <- newName "s" -- casein1 <- [e| (lens_getter $(varE l)) $(varE s) |] -- casein2 <- [e| (lens_putter $(varE l)) $(varE s) $(varE p) |] -- let caseexp1 = return $ LamE [VarP s] ( CaseE casein1 -- [Match (ConP t [VarP w]) (NormalB (VarE w)) []] ) -- let caseexp2 = return $ LamE [VarP s, VarP p] ( CaseE casein1 -- [Match (ConP t [VarP w]) (NormalB (VarE w)) []] ) -- [| Lens $(caseexp1) $(caseexp2) |] -- Lens s (w s) -> Lens s (GLWidget s) --makeOutHandlerLens l t = -- [| Lens -- ( \ s -> widget_super ((lens_getter $(varE l)) s) ) -- ( \ s w -> (lens_putter $(varE l)) s (widget_super w) ) |] -- HandlerT (w s) -> HandlerT (GLWidget s) --makeInHandler h t et = -- [| (\ e l -> $(varE h) e $(makeOutWidgetLens 'l t)) :: (WidgetHandler s (GLWidget s) $(conT et)) |] -- HandlerT (GLWidget s) -> HandlerT (t s) --makeOutHandler h t = do -- s <- newName "s" -- [| (\ e linside -> $(varE h) e $(makeOutHandlerLens 'linside t)) :: (WidgetHandler s ($(conT t) s) e) |] -- [| (\ e linside -> $(varE h) e $(makeOutHandlerLens 'linside t)) |] -- ( \ s -> case ((lens_getter $(varE l)) s ) of -- GLText w -> w -- GLPanel w -> w -- ) -- ( \ s p -> case ((lens_putter $(varE l)) s p) of -- GLText w -> w -- GLPanel w -> w -- )) :: Lens s ($(conT t) w) -- |] --makeInWidget f = -- [e| do -- GLWidget w <- get -- (ret, w') <- runStateT $(varE f) w -- put $ GLWidget w' -- return ret -- |] -- ---- Lens (w s) r -> Lens (GLWidget s) r --makeInWidgetLens l = -- [| Lens -- ( \ (GLWidget w) -> (lens_getter $(varE l)) w ) -- ( \ (GLWidget w) p -> GLWidget ((lens_putter $(varE l)) w p) ) -- |] -- ---- Lens (GLWidget w) r -> Lens (w s) r --makeOutWidgetLens l = -- [| Lens -- ( \ w -> (lens_getter $(varE l)) (GLWidget w) ) -- ( \ w p -> case ((lens_putter $(varE l)) (GLWidget w) p) of -- GLWidget w' -> w' -- ) -- |] --inWidget f = do -- GLWidget w <- get -- (ret, w') <- runStateT f w -- put $ GLWidget w' -- return ret --handler_change_in_base :: Lens (Base s) (TextHandler s (Base s)) --handler_change_in_base = Lens -- ( \ (b :: (Base s)) -> handler_change b ) -- (\ old_data_arZS -- -> \ new_value_arZT -- -> old_data_arZS {handler_change = new_value_arZT}) --instance (Widget a, Widget b) => Widget (a :+: b) where -- widget_position (L1 x) = widget_position x --handler_key_in_base :: Lens (Base s w) (TestKeyHandlerT w) --handler_key_in_base = Lens -- ( \ b -> handler_key b ) -- (\ old_data_arZS -- -> \ new_value_arZT -- -> old_data_arZS {handler_key = new_value_arZT}) make_lenses_record "base" ''GLWidgetPP.Base make_lenses_record "panel" ''GLWidgetPP.Panel make_lenses_record "text" ''GLWidgetPP.Text
piotrm0/planar
GLWidgetPP.hs
artistic-2.0
8,414
0
12
2,432
1,028
632
396
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module Orbat where import Data.Aeson import GHC.Generics (Generic) import Control.Lens import Unit import Color data Orbat = Orbat { _orbatColor :: Color , _orbatUnits :: [Unit] , _orbatSpottedUnits :: [UnitProjection] } deriving (Eq, Show, Generic) makeLenses ''Orbat instance FromJSON Orbat instance ToJSON Orbat orbatFindUnit :: UnitId -> Orbat -> Maybe Unit orbatFindUnit uid ob = let filt = filter (\u -> (u ^. unitId) == uid) us = ob ^. orbatUnits in case filt us of [u] -> Just u _ -> Nothing orbatRemoveUnit :: UnitId -> Orbat -> Orbat orbatRemoveUnit uid ob = ob & orbatUnits %~ filter (\u -> (u ^. unitId) /= uid) orbatReplaceUnit :: Unit -> Orbat -> Orbat orbatReplaceUnit u ob = let ob' = orbatRemoveUnit (u ^. unitId) ob in ob' & orbatUnits %~ (++) [u]
nbrk/ld
library/Orbat.hs
bsd-2-clause
888
0
14
198
310
166
144
30
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} -- | Jenkins REST API methods module Jenkins.Rest.Method ( -- * Construct URLs -- ** Path text , int , (-/-) -- ** Query , (-=-) , (-&-) , query -- ** Put together the segments and the query , (-?-) -- ** Format , Formatter , json , xml , python , plain , -- * Shortcuts job , build , view , queue , overallLoad , computer -- * Types , Method , Type(..) , Format(..) ) where import Data.Text (Text) import Jenkins.Rest.Method.Internal -- $setup -- >>> :set -XDataKinds -- >>> :set -XOverloadedStrings -- >>> class P t where pp :: Method t f -> Data.ByteString.ByteString -- >>> instance P Complete where pp = render -- >>> instance P Query where pp = renderQ' -- >>> let pp' = render infix 1 -?- infix 7 -=- infixr 5 -/-, -&- -- | Use a string as an URI segment -- -- >>> pp (text "foo") -- "foo" -- -- /Note:/ with @-XOverloadedStrings@ extension enabled it's possible to use string -- literals as segments of the Jenkins API method URL -- -- >>> pp' "foo" -- "foo" -- -- /Note:/ don't put @/@ in the string literal unless you want it URL-encoded, -- use @(-/-)@ instead -- -- >>> pp' "foo/bar" -- "foo%2Fbar" text :: Text -> Method 'Complete f text = Text -- | Use an integer as an URI segment -- -- >>> pp (int 4) -- "4" int :: Int -> Method 'Complete f int = fromIntegral -- | Combine two paths -- -- >>> pp ("foo" -/- "bar" -/- "baz") -- "foo/bar/baz" (-/-) :: Method 'Complete f -> Method 'Complete f -> Method 'Complete f (-/-) = (:/) -- | Make a key-value pair -- -- >>> pp ("foo" -=- "bar") -- "foo=bar" (-=-) :: Text -> Text -> Method 'Query f x -=- y = x := Just y -- | Create the union of two queries -- -- >>> pp ("foo" -=- "bar" -&- "baz") -- "foo=bar&baz" (-&-) :: Method 'Query f -> Method 'Query f -> Method 'Query f (-&-) = (:&) -- | Take a list of key-value pairs and render them as a query -- -- >>> pp (query [("foo", Nothing), ("bar", Just "baz"), ("quux", Nothing)]) -- "foo&bar=baz&quux" -- -- >>> pp (query []) -- "" query :: [(Text, Maybe Text)] -> Method 'Query f query = foldr ((:&) . uncurry (:=)) Empty -- | Put path and query together -- -- >>> pp ("qux" -/- "quux" -?- "foo" -=- "bar" -&- "baz") -- "qux/quux?foo=bar&baz" -- -- >>> pp ("" -?- "foo" -=- "bar") -- "foo=bar" -- -- >>> pp ("/" -?- "foo" -=- "bar") -- "%2F?foo=bar" (-?-) :: Method 'Complete f -> Method 'Query f -> Method 'Complete f (-?-) = (:?) -- | Append the JSON formatting request to the method URL -- -- >>> format json "foo" -- "foo/api/json" json :: Formatter 'Json json = Formatter (\m -> m :@ SJson) {-# ANN json ("HLint: ignore Avoid lambda" :: String) #-} -- | Append the XML formatting request to the method URL -- -- >>> format xml "foo" -- "foo/api/xml" xml :: Formatter 'Xml xml = Formatter (\m -> m :@ SXml) {-# ANN xml ("HLint: ignore Avoid lambda" :: String) #-} -- | Append the Python formatting request to the method URL -- -- >>> format python "foo" -- "foo/api/python" python :: Formatter 'Python python = Formatter (\m -> m :@ SPython) {-# ANN python ("HLint: ignore Avoid lambda" :: String) #-} -- | The formatter that does exactly nothing -- -- >>> format plain "foo" -- "foo" plain :: Formatter f plain = Formatter (\m -> m) {-# ANN plain ("HLint: ignore Use id" :: String) #-} -- | Job data -- -- >>> format json (job "name") -- "job/name/api/json" -- -- >>> pp (job "name" -/- "config.xml") -- "job/name/config.xml" job :: Text -> Method 'Complete f job name = "job" -/- text name -- | Job build data -- -- >>> format json (build "name" 4) -- "job/name/4/api/json" build :: Text -> Int -> Method 'Complete f build name num = "job" -/- text name -/- int num -- | View data -- -- >>> format xml (view "name") -- "view/name/api/xml" view :: Text -> Method 'Complete f view name = "view" -/- text name -- | Build queue data -- -- >>> format python queue -- "queue/api/python" queue :: Method 'Complete f queue = "queue" -- | Server statistics -- -- >>> format xml overallLoad -- "overallLoad/api/xml" overallLoad :: Method 'Complete f overallLoad = "overallLoad" -- | Nodes data -- -- >>> format python computer -- "computer/api/python" computer :: Method 'Complete f computer = "computer"
supki/libjenkins
src/Jenkins/Rest/Method.hs
bsd-2-clause
4,304
0
8
896
777
483
294
69
1
{-# LANGUAGE PatternGuards #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.BinarySpacePartition -- Description : New windows split the focused window in half; based off of BSPWM. -- Copyright : (c) 2013 Ben Weitzman <benweitzman@gmail.com> -- 2015 Anton Pirogov <anton.pirogov@gmail.com> -- 2019 Mateusz Karbowy <obszczymucha@gmail.com -- License : BSD3-style (see LICENSE) -- -- Maintainer : Ben Weitzman <benweitzman@gmail.com> -- Stability : unstable -- Portability : unportable -- -- Layout where new windows will split the focused window in half, based off of BSPWM -- ----------------------------------------------------------------------------- module XMonad.Layout.BinarySpacePartition ( -- * Usage -- $usage emptyBSP , BinarySpacePartition , Rotate(..) , Swap(..) , ResizeDirectional(.., ExpandTowards, ShrinkFrom, MoveSplit) , TreeRotate(..) , TreeBalance(..) , FocusParent(..) , SelectMoveNode(..) , Direction2D(..) , SplitShiftDirectional(..) ) where import XMonad import XMonad.Prelude hiding (insert) import qualified XMonad.StackSet as W import XMonad.Hooks.ManageHelpers (isMinimized) import XMonad.Util.Stack hiding (Zipper) import XMonad.Util.Types -- for mouse resizing import XMonad.Layout.WindowArranger (WindowArrangerMsg(SetGeometry)) -- for "focus parent" node border import XMonad.Util.XUtils import qualified Data.Map as M import qualified Data.Set as S import Data.Ratio ((%)) -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.BinarySpacePartition -- -- Then add the layout, using the default BSP (BinarySpacePartition) -- -- > myLayout = emptyBSP ||| etc .. -- -- It may be a good idea to use "XMonad.Actions.Navigation2D" to move between the windows. -- -- This layout responds to SetGeometry and is compatible with e.g. "XMonad.Actions.MouseResize" -- or "XMonad.Layout.BorderResize". You should probably try both to decide which is better for you, -- if you want to be able to resize the splits with the mouse. -- -- If you don't want to use the mouse, add the following key bindings to resize the splits with the keyboard: -- -- > , ((modm .|. altMask, xK_l ), sendMessage $ ExpandTowards R) -- > , ((modm .|. altMask, xK_h ), sendMessage $ ExpandTowards L) -- > , ((modm .|. altMask, xK_j ), sendMessage $ ExpandTowards D) -- > , ((modm .|. altMask, xK_k ), sendMessage $ ExpandTowards U) -- > , ((modm .|. altMask .|. ctrlMask , xK_l ), sendMessage $ ShrinkFrom R) -- > , ((modm .|. altMask .|. ctrlMask , xK_h ), sendMessage $ ShrinkFrom L) -- > , ((modm .|. altMask .|. ctrlMask , xK_j ), sendMessage $ ShrinkFrom D) -- > , ((modm .|. altMask .|. ctrlMask , xK_k ), sendMessage $ ShrinkFrom U) -- > , ((modm, xK_r ), sendMessage Rotate) -- > , ((modm, xK_s ), sendMessage Swap) -- > , ((modm, xK_n ), sendMessage FocusParent) -- > , ((modm .|. ctrlMask, xK_n ), sendMessage SelectNode) -- > , ((modm .|. shiftMask, xK_n ), sendMessage MoveNode) -- > , ((modm .|. shiftMask .|. ctrlMask , xK_j ), sendMessage $ SplitShift Prev) -- > , ((modm .|. shiftMask .|. ctrlMask , xK_k ), sendMessage $ SplitShift Next) -- -- Here's an alternative key mapping, this time using additionalKeysP, -- arrow keys, and slightly different behavior when resizing windows -- -- > , ("M-M1-<Left>", sendMessage $ ExpandTowards L) -- > , ("M-M1-<Right>", sendMessage $ ShrinkFrom L) -- > , ("M-M1-<Up>", sendMessage $ ExpandTowards U) -- > , ("M-M1-<Down>", sendMessage $ ShrinkFrom U) -- > , ("M-M1-C-<Left>", sendMessage $ ShrinkFrom R) -- > , ("M-M1-C-<Right>", sendMessage $ ExpandTowards R) -- > , ("M-M1-C-<Up>", sendMessage $ ShrinkFrom D) -- > , ("M-M1-C-<Down>", sendMessage $ ExpandTowards D) -- > , ("M-s", sendMessage $ Swap) -- > , ("M-M1-s", sendMessage $ Rotate) -- > , ("M-S-C-j", sendMessage $ SplitShift Prev) -- > , ("M-S-C-k", sendMessage $ SplitShift Next) -- -- Note that @ExpandTowards x@, @ShrinkFrom x@, and @MoveSplit x@ are -- the same as respectively @ExpandTowardsBy x 0.05@, @ShrinkFromBy x 0.05@ -- and @MoveSplitBy x 0.05@. -- -- If you have many windows open and the layout begins to look too hard to manage, you can 'Balance' -- the layout, so that the current splittings are discarded and windows are tiled freshly in a way that -- the split depth is minimized. You can combine this with 'Equalize', which does not change your tree, -- but tunes the split ratios in a way that each window gets the same amount of space: -- -- > , ((myModMask, xK_a), sendMessage Balance) -- > , ((myModMask .|. shiftMask, xK_a), sendMessage Equalize) -- -- | Message for rotating the binary tree around the parent node of the window to the left or right data TreeRotate = RotateL | RotateR instance Message TreeRotate -- | Message to balance the tree in some way (Balance retiles the windows, Equalize changes ratios) data TreeBalance = Balance | Equalize instance Message TreeBalance -- | Message for resizing one of the cells in the BSP data ResizeDirectional = ExpandTowardsBy Direction2D Rational | ShrinkFromBy Direction2D Rational | MoveSplitBy Direction2D Rational instance Message ResizeDirectional -- | @ExpandTowards x@ is now the equivalent of @ExpandTowardsBy x 0.05@ pattern ExpandTowards :: Direction2D -> ResizeDirectional pattern ExpandTowards d = ExpandTowardsBy d 0.05 -- | @ShrinkFrom x@ is now the equivalent of @ShrinkFromBy x 0.05@ pattern ShrinkFrom :: Direction2D -> ResizeDirectional pattern ShrinkFrom d = ShrinkFromBy d 0.05 -- | @MoveSplit x@ is now the equivalent of @MoveSplitBy x 0.05@ pattern MoveSplit :: Direction2D -> ResizeDirectional pattern MoveSplit d = MoveSplitBy d 0.05 -- | Message for rotating a split (horizontal/vertical) in the BSP data Rotate = Rotate instance Message Rotate -- | Message for swapping the left child of a split with the right child of split data Swap = Swap instance Message Swap -- | Message to cyclically select the parent node instead of the leaf data FocusParent = FocusParent instance Message FocusParent -- | Message to move nodes inside the tree data SelectMoveNode = SelectNode | MoveNode instance Message SelectMoveNode data Axis = Horizontal | Vertical deriving (Show, Read, Eq) -- | Message for shifting window by splitting its neighbour newtype SplitShiftDirectional = SplitShift Direction1D instance Message SplitShiftDirectional oppositeDirection :: Direction2D -> Direction2D oppositeDirection U = D oppositeDirection D = U oppositeDirection L = R oppositeDirection R = L oppositeAxis :: Axis -> Axis oppositeAxis Vertical = Horizontal oppositeAxis Horizontal = Vertical toAxis :: Direction2D -> Axis toAxis U = Horizontal toAxis D = Horizontal toAxis L = Vertical toAxis R = Vertical split :: Axis -> Rational -> Rectangle -> (Rectangle, Rectangle) split Horizontal r (Rectangle sx sy sw sh) = (r1, r2) where r1 = Rectangle sx sy sw sh' r2 = Rectangle sx (sy + fromIntegral sh') sw (sh - sh') sh' = floor $ fromIntegral sh * r split Vertical r (Rectangle sx sy sw sh) = (r1, r2) where r1 = Rectangle sx sy sw' sh r2 = Rectangle (sx + fromIntegral sw') sy (sw - sw') sh sw' = floor $ fromIntegral sw * r data Split = Split { axis :: Axis , ratio :: Rational } deriving (Show, Read, Eq) oppositeSplit :: Split -> Split oppositeSplit (Split d r) = Split (oppositeAxis d) r increaseRatio :: Split -> Rational -> Split increaseRatio (Split d r) delta = Split d (min 0.9 (max 0.1 (r + delta))) data Tree a = Leaf Int | Node { value :: a , left :: Tree a , right :: Tree a } deriving (Show, Read, Eq) numLeaves :: Tree a -> Int numLeaves (Leaf _) = 1 numLeaves (Node _ l r) = numLeaves l + numLeaves r -- right or left rotation of a (sub)tree, no effect if rotation not possible rotTree :: Direction2D -> Tree a -> Tree a rotTree _ (Leaf n) = Leaf n rotTree R n@(Node _ (Leaf _) _) = n rotTree L n@(Node _ _ (Leaf _)) = n rotTree R (Node sp (Node sp2 l2 r2) r) = Node sp2 l2 (Node sp r2 r) rotTree L (Node sp l (Node sp2 l2 r2)) = Node sp2 (Node sp l l2) r2 rotTree _ t = t data Crumb a = LeftCrumb a (Tree a) | RightCrumb a (Tree a) deriving (Show, Read, Eq) swapCrumb :: Crumb a -> Crumb a swapCrumb (LeftCrumb s t) = RightCrumb s t swapCrumb (RightCrumb s t) = LeftCrumb s t parentVal :: Crumb a -> a parentVal (LeftCrumb s _) = s parentVal (RightCrumb s _) = s modifyParentVal :: (a -> a) -> Crumb a -> Crumb a modifyParentVal f (LeftCrumb s t) = LeftCrumb (f s) t modifyParentVal f (RightCrumb s t) = RightCrumb (f s) t type Zipper a = (Tree a, [Crumb a]) toZipper :: Tree a -> Zipper a toZipper t = (t, []) goLeft :: Zipper a -> Maybe (Zipper a) goLeft (Leaf _, _) = Nothing goLeft (Node x l r, bs) = Just (l, LeftCrumb x r:bs) goRight :: Zipper a -> Maybe (Zipper a) goRight (Leaf _, _) = Nothing goRight (Node x l r, bs) = Just (r, RightCrumb x l:bs) goUp :: Zipper a -> Maybe (Zipper a) goUp (_, []) = Nothing goUp (t, LeftCrumb x r:cs) = Just (Node x t r, cs) goUp (t, RightCrumb x l:cs) = Just (Node x l t, cs) goSibling :: Zipper a -> Maybe (Zipper a) goSibling (_, []) = Nothing goSibling z@(_, LeftCrumb _ _:_) = Just z >>= goUp >>= goRight goSibling z@(_, RightCrumb _ _:_) = Just z >>= goUp >>= goLeft top :: Zipper a -> Zipper a top z = maybe z top (goUp z) toTree :: Zipper a -> Tree a toTree = fst . top goToNthLeaf :: Int -> Zipper a -> Maybe (Zipper a) goToNthLeaf _ z@(Leaf _, _) = Just z goToNthLeaf n z@(t, _) = if numLeaves (left t) > n then do z' <- goLeft z goToNthLeaf n z' else do z' <- goRight z goToNthLeaf (n - (numLeaves . left $ t)) z' toggleSplits :: Tree Split -> Tree Split toggleSplits (Leaf l) = Leaf l toggleSplits (Node s l r) = Node (oppositeSplit s) (toggleSplits l) (toggleSplits r) splitCurrent :: Zipper Split -> Maybe (Zipper Split) splitCurrent (Leaf _, []) = Just (Node (Split Vertical 0.5) (Leaf 0) (Leaf 0), []) splitCurrent (Leaf _, crumb:cs) = Just (Node (Split (oppositeAxis . axis . parentVal $ crumb) 0.5) (Leaf 0) (Leaf 0), crumb:cs) splitCurrent (n, []) = Just (Node (Split Vertical 0.5) (Leaf 0) (toggleSplits n), []) splitCurrent (n, crumb:cs) = Just (Node (Split (oppositeAxis . axis . parentVal $ crumb) 0.5) (Leaf 0) (toggleSplits n), crumb:cs) removeCurrent :: Zipper a -> Maybe (Zipper a) removeCurrent (Leaf _, LeftCrumb _ r:cs) = Just (r, cs) removeCurrent (Leaf _, RightCrumb _ l:cs) = Just (l, cs) removeCurrent (Leaf _, []) = Nothing removeCurrent (Node _ (Leaf _) r@Node{}, cs) = Just (r, cs) removeCurrent (Node _ l@Node{} (Leaf _), cs) = Just (l, cs) removeCurrent (Node _ (Leaf _) (Leaf _), cs) = Just (Leaf 0, cs) removeCurrent z@(Node{}, _) = goLeft z >>= removeCurrent rotateCurrent :: Zipper Split -> Maybe (Zipper Split) rotateCurrent l@(_, []) = Just l rotateCurrent (n, c:cs) = Just (n, modifyParentVal oppositeSplit c:cs) swapCurrent :: Zipper a -> Maybe (Zipper a) swapCurrent l@(_, []) = Just l swapCurrent (n, c:cs) = Just (n, swapCrumb c:cs) insertLeftLeaf :: Tree Split -> Zipper Split -> Maybe (Zipper Split) insertLeftLeaf (Leaf n) (Node x l r, crumb:cs) = Just (Node (Split (oppositeAxis . axis . parentVal $ crumb) 0.5) (Leaf n) (Node x l r), crumb:cs) insertLeftLeaf (Leaf n) (Leaf x, crumb:cs) = Just (Node (Split (oppositeAxis . axis . parentVal $ crumb) 0.5) (Leaf n) (Leaf x), crumb:cs) insertLeftLeaf Node{} z = Just z insertLeftLeaf _ _ = Nothing insertRightLeaf :: Tree Split -> Zipper Split -> Maybe (Zipper Split) insertRightLeaf (Leaf n) (Node x l r, crumb:cs) = Just (Node (Split (oppositeAxis . axis . parentVal $ crumb) 0.5) (Node x l r) (Leaf n), crumb:cs) insertRightLeaf (Leaf n) (Leaf x, crumb:cs) = Just (Node (Split (oppositeAxis . axis . parentVal $ crumb) 0.5) (Leaf x) (Leaf n), crumb:cs) insertRightLeaf Node{} z = Just z insertRightLeaf _ _ = Nothing findRightLeaf :: Zipper Split -> Maybe (Zipper Split) findRightLeaf n@(Node{}, _) = goRight n >>= findRightLeaf findRightLeaf l@(Leaf _, _) = Just l findLeftLeaf :: Zipper Split -> Maybe (Zipper Split) findLeftLeaf n@(Node{}, _) = goLeft n findLeftLeaf l@(Leaf _, _) = Just l findTheClosestLeftmostLeaf :: Zipper Split -> Maybe (Zipper Split) findTheClosestLeftmostLeaf s@(_, (RightCrumb _ _):_) = goUp s >>= goLeft >>= findRightLeaf findTheClosestLeftmostLeaf s@(_, (LeftCrumb _ _):_) = goUp s >>= findTheClosestLeftmostLeaf findTheClosestLeftmostLeaf _ = Nothing findTheClosestRightmostLeaf :: Zipper Split -> Maybe (Zipper Split) findTheClosestRightmostLeaf s@(_, (RightCrumb _ _):_) = goUp s >>= findTheClosestRightmostLeaf findTheClosestRightmostLeaf s@(_, (LeftCrumb _ _):_) = goUp s >>= goRight >>= findLeftLeaf findTheClosestRightmostLeaf _ = Nothing splitShiftLeftCurrent :: Zipper Split -> Maybe (Zipper Split) splitShiftLeftCurrent l@(_, []) = Just l splitShiftLeftCurrent l@(_, (RightCrumb _ _):_) = Just l -- Do nothing. We can swap windows instead. splitShiftLeftCurrent l@(n, _) = removeCurrent l >>= findTheClosestLeftmostLeaf >>= insertRightLeaf n splitShiftRightCurrent :: Zipper Split -> Maybe (Zipper Split) splitShiftRightCurrent l@(_, []) = Just l splitShiftRightCurrent l@(_, (LeftCrumb _ _):_) = Just l -- Do nothing. We can swap windows instead. splitShiftRightCurrent l@(n, _) = removeCurrent l >>= findTheClosestRightmostLeaf >>= insertLeftLeaf n isAllTheWay :: Direction2D -> Rational -> Zipper Split -> Bool isAllTheWay _ _ (_, []) = True isAllTheWay R _ (_, LeftCrumb s _:_) | axis s == Vertical = False isAllTheWay L _ (_, RightCrumb s _:_) | axis s == Vertical = False isAllTheWay D _ (_, LeftCrumb s _:_) | axis s == Horizontal = False isAllTheWay U _ (_, RightCrumb s _:_) | axis s == Horizontal = False isAllTheWay dir diff z = fromMaybe False $ goUp z >>= Just . isAllTheWay dir diff expandTreeTowards :: Direction2D -> Rational -> Zipper Split -> Maybe (Zipper Split) expandTreeTowards _ _ z@(_, []) = Just z expandTreeTowards dir diff z | isAllTheWay dir diff z = shrinkTreeFrom (oppositeDirection dir) diff z expandTreeTowards R diff (t, LeftCrumb s r:cs) | axis s == Vertical = Just (t, LeftCrumb (increaseRatio s diff) r:cs) expandTreeTowards L diff (t, RightCrumb s l:cs) | axis s == Vertical = Just (t, RightCrumb (increaseRatio s (-diff)) l:cs) expandTreeTowards D diff (t, LeftCrumb s r:cs) | axis s == Horizontal = Just (t, LeftCrumb (increaseRatio s diff) r:cs) expandTreeTowards U diff (t, RightCrumb s l:cs) | axis s == Horizontal = Just (t, RightCrumb (increaseRatio s (-diff)) l:cs) expandTreeTowards dir diff z = goUp z >>= expandTreeTowards dir diff shrinkTreeFrom :: Direction2D -> Rational -> Zipper Split -> Maybe (Zipper Split) shrinkTreeFrom _ _ z@(_, []) = Just z shrinkTreeFrom R diff z@(_, LeftCrumb s _:_) | axis s == Vertical = Just z >>= goSibling >>= expandTreeTowards L diff shrinkTreeFrom L diff z@(_, RightCrumb s _:_) | axis s == Vertical = Just z >>= goSibling >>= expandTreeTowards R diff shrinkTreeFrom D diff z@(_, LeftCrumb s _:_) | axis s == Horizontal = Just z >>= goSibling >>= expandTreeTowards U diff shrinkTreeFrom U diff z@(_, RightCrumb s _:_) | axis s == Horizontal = Just z >>= goSibling >>= expandTreeTowards D diff shrinkTreeFrom dir diff z = goUp z >>= shrinkTreeFrom dir diff -- Direction2D refers to which direction the divider should move. autoSizeTree :: Direction2D -> Rational -> Zipper Split -> Maybe (Zipper Split) autoSizeTree _ _ z@(_, []) = Just z autoSizeTree d f z = Just z >>= getSplit (toAxis d) >>= resizeTree d f -- resizing once found the correct split. YOU MUST FIND THE RIGHT SPLIT FIRST. resizeTree :: Direction2D -> Rational -> Zipper Split -> Maybe (Zipper Split) resizeTree _ _ z@(_, []) = Just z resizeTree R diff z@(_, LeftCrumb _ _:_) = Just z >>= expandTreeTowards R diff resizeTree L diff z@(_, LeftCrumb _ _:_) = Just z >>= shrinkTreeFrom R diff resizeTree U diff z@(_, LeftCrumb _ _:_) = Just z >>= shrinkTreeFrom D diff resizeTree D diff z@(_, LeftCrumb _ _:_) = Just z >>= expandTreeTowards D diff resizeTree R diff z@(_, RightCrumb _ _:_) = Just z >>= shrinkTreeFrom L diff resizeTree L diff z@(_, RightCrumb _ _:_) = Just z >>= expandTreeTowards L diff resizeTree U diff z@(_, RightCrumb _ _:_) = Just z >>= expandTreeTowards U diff resizeTree D diff z@(_, RightCrumb _ _:_) = Just z >>= shrinkTreeFrom U diff getSplit :: Axis -> Zipper Split -> Maybe (Zipper Split) getSplit _ (_, []) = Nothing getSplit d z = do let fs = findSplit d z if isNothing fs then findClosest d z else fs findClosest :: Axis -> Zipper Split -> Maybe (Zipper Split) findClosest _ z@(_, []) = Just z findClosest d z@(_, LeftCrumb s _:_) | axis s == d = Just z findClosest d z@(_, RightCrumb s _:_) | axis s == d = Just z findClosest d z = goUp z >>= findClosest d findSplit :: Axis -> Zipper Split -> Maybe (Zipper Split) findSplit _ (_, []) = Nothing findSplit d z@(_, LeftCrumb s _:_) | axis s == d = Just z findSplit d z = goUp z >>= findSplit d resizeSplit :: Direction2D -> (Rational,Rational) -> Zipper Split -> Maybe (Zipper Split) resizeSplit _ _ z@(_, []) = Just z resizeSplit dir (xsc,ysc) z = case goToBorder dir z of Nothing -> Just z Just (t@Node{}, crumb) -> Just $ case dir of R -> (t{value=sp{ratio=scaleRatio (ratio sp) xsc}}, crumb) D -> (t{value=sp{ratio=scaleRatio (ratio sp) ysc}}, crumb) L -> (t{value=sp{ratio=1-scaleRatio (1-ratio sp) xsc}}, crumb) U -> (t{value=sp{ratio=1-scaleRatio (1-ratio sp) ysc}}, crumb) where sp = value t scaleRatio r fac = min 0.9 $ max 0.1 $ r*fac Just (Leaf{}, _) -> undefined -- silence -Wincomplete-uni-patterns (goToBorder/goUp never return a Leaf) -- starting from a leaf, go to node representing a border of the according window goToBorder :: Direction2D -> Zipper Split -> Maybe (Zipper Split) goToBorder L z@(_, RightCrumb (Split Vertical _) _:_) = goUp z goToBorder L z = goUp z >>= goToBorder L goToBorder R z@(_, LeftCrumb (Split Vertical _) _:_) = goUp z goToBorder R z = goUp z >>= goToBorder R goToBorder U z@(_, RightCrumb (Split Horizontal _) _:_) = goUp z goToBorder U z = goUp z >>= goToBorder U goToBorder D z@(_, LeftCrumb (Split Horizontal _) _:_) = goUp z goToBorder D z = goUp z >>= goToBorder D -- takes a list of indices and numerates the leaves of a given tree numerate :: [Int] -> Tree a -> Tree a numerate ns t = snd $ num ns t where num (n:nns) (Leaf _) = (nns, Leaf n) num [] (Leaf _) = ([], Leaf 0) num n (Node s l r) = (n'', Node s nl nr) where (n', nl) = num n l (n'', nr) = num n' r -- return values of leaves from left to right as list flatten :: Tree a -> [Int] flatten (Leaf n) = [n] flatten (Node _ l r) = flatten l++flatten r -- adjust ratios to make window areas equal equalize :: Zipper Split -> Maybe (Zipper Split) equalize (t, cs) = Just (eql t, cs) where eql (Leaf n) = Leaf n eql n@(Node s l r) = Node s{ratio=fromIntegral (numLeaves l) % fromIntegral (numLeaves n)} (eql l) (eql r) -- generate a symmetrical balanced tree for n leaves from given tree, preserving leaf labels balancedTree :: Zipper Split -> Maybe (Zipper Split) balancedTree (t, cs) = Just (numerate (flatten t) $ balanced (numLeaves t), cs) where balanced 1 = Leaf 0 balanced 2 = Node (Split Horizontal 0.5) (Leaf 0) (Leaf 0) balanced m = Node (Split Horizontal 0.5) (balanced (m`div`2)) (balanced (m-m`div`2)) -- attempt to rotate splits optimally in order choose more quad-like rects optimizeOrientation :: Rectangle -> Zipper Split -> Maybe (Zipper Split) optimizeOrientation rct (t, cs) = Just (opt t rct, cs) where opt (Leaf v) _ = Leaf v opt (Node sp l r) rect = Node sp' (opt l lrect) (opt r rrect) where (Rectangle _ _ w1 h1,Rectangle _ _ w2 h2) = split (axis sp) (ratio sp) rect (Rectangle _ _ w3 h3,Rectangle _ _ w4 h4) = split (axis $ oppositeSplit sp) (ratio sp) rect f w h = if w > h then w'/h' else h'/w' where (w',h') = (fromIntegral w :: Double, fromIntegral h :: Double) wratio = min (f w1 h1) (f w2 h2) wratio' = min (f w3 h3) (f w4 h4) sp' = if wratio<wratio' then sp else oppositeSplit sp (lrect, rrect) = split (axis sp') (ratio sp') rect -- initially focused leaf, path from root to selected node, window ids of borders highlighting the selection data NodeRef = NodeRef { refLeaf :: Int, refPath :: [Direction2D], refWins :: [Window] } deriving (Show,Read,Eq) noRef :: NodeRef noRef = NodeRef (-1) [] [] goToNode :: NodeRef -> Zipper a -> Maybe (Zipper a) goToNode (NodeRef _ dirs _) z = foldM gofun z dirs where gofun z' L = goLeft z' gofun z' R = goRight z' gofun _ _ = Nothing toNodeRef :: Int -> Maybe (Zipper Split) -> NodeRef toNodeRef _ Nothing = noRef toNodeRef l (Just (_, cs)) = NodeRef l (reverse $ map crumbToDir cs) [] where crumbToDir (LeftCrumb _ _) = L crumbToDir (RightCrumb _ _) = R -- returns the leaf a noderef is leading to, if any nodeRefToLeaf :: NodeRef -> Maybe (Zipper a) -> Maybe Int nodeRefToLeaf n (Just z) = case goToNode n z of Just (Leaf l, _) -> Just l Just (Node{}, _) -> Nothing Nothing -> Nothing nodeRefToLeaf _ Nothing = Nothing leafToNodeRef :: Int -> BinarySpacePartition a -> NodeRef leafToNodeRef l b = toNodeRef l (makeZipper b >>= goToNthLeaf l) data BinarySpacePartition a = BinarySpacePartition { getOldRects :: [(Window,Rectangle)] , getFocusedNode :: NodeRef , getSelectedNode :: NodeRef , getTree :: Maybe (Tree Split) } deriving (Show, Read,Eq) -- | an empty BinarySpacePartition to use as a default for adding windows to. emptyBSP :: BinarySpacePartition a emptyBSP = BinarySpacePartition [] noRef noRef Nothing makeBSP :: Tree Split -> BinarySpacePartition a makeBSP = BinarySpacePartition [] noRef noRef . Just makeZipper :: BinarySpacePartition a -> Maybe (Zipper Split) makeZipper (BinarySpacePartition _ _ _ Nothing) = Nothing makeZipper (BinarySpacePartition _ _ _ (Just t)) = Just . toZipper $ t size :: BinarySpacePartition a -> Int size = maybe 0 numLeaves . getTree zipperToBinarySpacePartition :: Maybe (Zipper Split) -> BinarySpacePartition b zipperToBinarySpacePartition Nothing = emptyBSP zipperToBinarySpacePartition (Just z) = BinarySpacePartition [] noRef noRef . Just . toTree . top $ z rectangles :: BinarySpacePartition a -> Rectangle -> [Rectangle] rectangles (BinarySpacePartition _ _ _ Nothing) _ = [] rectangles (BinarySpacePartition _ _ _ (Just (Leaf _))) rootRect = [rootRect] rectangles (BinarySpacePartition _ _ _ (Just node)) rootRect = rectangles (makeBSP . left $ node) leftBox ++ rectangles (makeBSP . right $ node) rightBox where (leftBox, rightBox) = split (axis info) (ratio info) rootRect info = value node getNodeRect :: BinarySpacePartition a -> Rectangle -> NodeRef -> Rectangle getNodeRect b r n = fromMaybe (Rectangle 0 0 1 1) (makeZipper b >>= goToNode n >>= getRect []) where getRect ls (_, []) = Just $ foldl (\r' (s,f) -> f $ split' s r') r ls getRect ls z@(_, LeftCrumb s _:_) = goUp z >>= getRect ((s,fst):ls) getRect ls z@(_, RightCrumb s _:_) = goUp z >>= getRect ((s,snd):ls) split' s = split (axis s) (ratio s) doToNth :: (Zipper Split -> Maybe (Zipper Split)) -> BinarySpacePartition a -> BinarySpacePartition a doToNth f b = b{getTree=getTree $ zipperToBinarySpacePartition $ makeZipper b >>= goToNode (getFocusedNode b) >>= f} splitNth :: BinarySpacePartition a -> BinarySpacePartition a splitNth (BinarySpacePartition _ _ _ Nothing) = makeBSP (Leaf 0) splitNth b = doToNth splitCurrent b removeNth :: BinarySpacePartition a -> BinarySpacePartition a removeNth (BinarySpacePartition _ _ _ Nothing) = emptyBSP removeNth (BinarySpacePartition _ _ _ (Just (Leaf _))) = emptyBSP removeNth b = doToNth removeCurrent b rotateNth :: BinarySpacePartition a -> BinarySpacePartition a rotateNth (BinarySpacePartition _ _ _ Nothing) = emptyBSP rotateNth b@(BinarySpacePartition _ _ _ (Just (Leaf _))) = b rotateNth b = doToNth rotateCurrent b swapNth :: BinarySpacePartition a -> BinarySpacePartition a swapNth (BinarySpacePartition _ _ _ Nothing) = emptyBSP swapNth b@(BinarySpacePartition _ _ _ (Just (Leaf _))) = b swapNth b = doToNth swapCurrent b splitShiftNth :: Direction1D -> BinarySpacePartition a -> BinarySpacePartition a splitShiftNth _ (BinarySpacePartition _ _ _ Nothing) = emptyBSP splitShiftNth _ b@(BinarySpacePartition _ _ _ (Just (Leaf _))) = b splitShiftNth Prev b = doToNth splitShiftLeftCurrent b splitShiftNth Next b = doToNth splitShiftRightCurrent b growNthTowards :: Direction2D -> Rational -> BinarySpacePartition a -> BinarySpacePartition a growNthTowards _ _ (BinarySpacePartition _ _ _ Nothing) = emptyBSP growNthTowards _ _ b@(BinarySpacePartition _ _ _ (Just (Leaf _))) = b growNthTowards dir diff b = doToNth (expandTreeTowards dir diff) b shrinkNthFrom :: Direction2D -> Rational -> BinarySpacePartition a -> BinarySpacePartition a shrinkNthFrom _ _ (BinarySpacePartition _ _ _ Nothing)= emptyBSP shrinkNthFrom _ _ b@(BinarySpacePartition _ _ _ (Just (Leaf _))) = b shrinkNthFrom dir diff b = doToNth (shrinkTreeFrom dir diff) b autoSizeNth :: Direction2D -> Rational -> BinarySpacePartition a -> BinarySpacePartition a autoSizeNth _ _ (BinarySpacePartition _ _ _ Nothing) = emptyBSP autoSizeNth _ _ b@(BinarySpacePartition _ _ _ (Just (Leaf _))) = b autoSizeNth dir diff b = doToNth (autoSizeTree dir diff) b resizeSplitNth :: Direction2D -> (Rational,Rational) -> BinarySpacePartition a -> BinarySpacePartition a resizeSplitNth _ _ (BinarySpacePartition _ _ _ Nothing) = emptyBSP resizeSplitNth _ _ b@(BinarySpacePartition _ _ _ (Just (Leaf _))) = b resizeSplitNth dir sc b = doToNth (resizeSplit dir sc) b -- rotate tree left or right around parent of nth leaf rotateTreeNth :: Direction2D -> BinarySpacePartition a -> BinarySpacePartition a rotateTreeNth _ (BinarySpacePartition _ _ _ Nothing) = emptyBSP rotateTreeNth U b = b rotateTreeNth D b = b rotateTreeNth dir b@(BinarySpacePartition _ _ _ (Just _)) = doToNth (\t -> case goUp t of Nothing -> Just t Just (t', c) -> Just (rotTree dir t', c)) b equalizeNth :: BinarySpacePartition a -> BinarySpacePartition a equalizeNth (BinarySpacePartition _ _ _ Nothing) = emptyBSP equalizeNth b@(BinarySpacePartition _ _ _ (Just (Leaf _))) = b equalizeNth b = doToNth equalize b rebalanceNth :: BinarySpacePartition a -> Rectangle -> BinarySpacePartition a rebalanceNth (BinarySpacePartition _ _ _ Nothing) _ = emptyBSP rebalanceNth b@(BinarySpacePartition _ _ _ (Just (Leaf _))) _ = b rebalanceNth b r = doToNth (balancedTree >=> optimizeOrientation r) b flattenLeaves :: BinarySpacePartition a -> [Int] flattenLeaves (BinarySpacePartition _ _ _ Nothing) = [] flattenLeaves (BinarySpacePartition _ _ _ (Just t)) = flatten t -- we do this before an action to look afterwards which leaves moved where numerateLeaves :: BinarySpacePartition a -> BinarySpacePartition a numerateLeaves b@(BinarySpacePartition _ _ _ Nothing) = b numerateLeaves b@(BinarySpacePartition _ _ _ (Just t)) = b{getTree=Just $ numerate ns t} where ns = [0..(numLeaves t-1)] -- if there is a selected and focused node and the focused is not a part of selected, -- move selected node to be a child of focused node moveNode :: BinarySpacePartition a -> BinarySpacePartition a moveNode b@(BinarySpacePartition _ (NodeRef (-1) _ _) _ _) = b moveNode b@(BinarySpacePartition _ _ (NodeRef (-1) _ _) _) = b moveNode b@(BinarySpacePartition _ _ _ Nothing) = b moveNode b@(BinarySpacePartition _ f s (Just ot)) = case makeZipper b >>= goToNode s of Just (n, LeftCrumb _ t:cs) -> b{getTree=Just $ insert n $ top (t, cs)} Just (n, RightCrumb _ t:cs) -> b{getTree=Just $ insert n $ top (t, cs)} _ -> b where insert t z = case goToNode f z of Nothing -> ot --return original tree (abort) Just (n, c:cs) -> toTree (Node (Split (oppositeAxis . axis . parentVal $ c) 0.5) t n, c:cs) Just (n, []) -> toTree (Node (Split Vertical 0.5) t n, []) ------------------------------------------ -- returns index of focused window or 0 for empty stack index :: W.Stack a -> Int index s = case toIndex (Just s) of (_, Nothing) -> 0 (_, Just int) -> int --move windows to new positions according to tree transformations, keeping focus on originally focused window --CAREFUL here! introduce a bug here and have fun debugging as your windows start to disappear or explode adjustStack :: Maybe (W.Stack Window) --original stack -> Maybe (W.Stack Window) --stack without floating windows -> [Window] --just floating windows of this WS -> Maybe (BinarySpacePartition Window) -- Tree with numbered leaves telling what to move where -> Maybe (W.Stack Window) --resulting stack adjustStack orig Nothing _ _ = orig --no new stack -> no changes adjustStack orig _ _ Nothing = orig --empty tree -> no changes adjustStack orig s fw (Just b) = if length ls<length ws then orig --less leaves than non-floating windows -> tree incomplete, no changes else fromIndex ws' fid' where ws' = mapMaybe (`M.lookup` wsmap) ls ++ fw fid' = fromMaybe 0 $ elemIndex focused ws' wsmap = M.fromList $ zip [0..] ws -- map: old index in list -> window ls = flattenLeaves b -- get new index ordering from tree (ws,fid) = toIndex s focused = ws !! fromMaybe 0 fid --replace the window stack of the managed workspace with our modified stack replaceStack :: Maybe (W.Stack Window) -> X () replaceStack s = do st <- get let wset = windowset st cur = W.current wset wsp = W.workspace cur put st{windowset=wset{W.current=cur{W.workspace=wsp{W.stack=s}}}} replaceFloating :: M.Map Window W.RationalRect -> X () replaceFloating wsm = do st <- get let wset = windowset st put st{windowset=wset{W.floating=wsm}} -- some helpers to filter windows -- getFloating :: X [Window] getFloating = M.keys . W.floating <$> gets windowset -- all floating windows getHidden :: X [Window] getHidden = getStackSet >>= filterM (runQuery isMinimized) . W.integrate' getStackSet :: X (Maybe (W.Stack Window)) getStackSet = W.stack . W.workspace . W.current <$> gets windowset -- windows on this WS (with floating) getScreenRect :: X Rectangle getScreenRect = screenRect . W.screenDetail . W.current <$> gets windowset withoutFloating :: [Window] -> [Window] -> Maybe (W.Stack Window) -> Maybe (W.Stack Window) withoutFloating fs hs = maybe Nothing (unfloat fs hs) -- ignore messages if current focus is on floating window, otherwise return stack without floating unfloat :: [Window] -> [Window] -> W.Stack Window -> Maybe (W.Stack Window) unfloat fs hs s = if W.focus s `elem` fs then Nothing else Just $ s{W.up = W.up s \\ (fs ++ hs), W.down = W.down s \\ (fs ++ hs)} instance LayoutClass BinarySpacePartition Window where doLayout b r s = do let b' = layout b b'' <- updateNodeRef b' (size b/=size b') r let rs = rectangles b'' r wrs = zip ws rs return (wrs, Just b''{getOldRects=wrs}) where ws = W.integrate s l = length ws layout bsp | l == sz = bsp | l > sz = layout $ splitNth bsp | otherwise = layout $ removeNth bsp where sz = size bsp handleMessage b_orig m | Just msg@(SetGeometry _) <- fromMessage m = handleResize b msg | Just FocusParent <- fromMessage m = do let n = getFocusedNode b let n' = toNodeRef (refLeaf n) (makeZipper b >>= goToNode n >>= goUp) return $ Just b{getFocusedNode=n'{refWins=refWins n}} | Just SelectNode <- fromMessage m = do let n = getFocusedNode b let s = getSelectedNode b removeBorder $ refWins s let s' = if refLeaf n == refLeaf s && refPath n == refPath s then noRef else n{refWins=[]} return $ Just b{getSelectedNode=s'} | otherwise = do ws <- getStackSet fs <- getFloating hs <- getHidden r <- getScreenRect -- removeBorder $ refWins $ getSelectedNode b let lws = withoutFloating fs hs ws -- tiled windows on WS lfs = maybe [] W.integrate ws \\ maybe [] W.integrate lws -- untiled windows on WS b' = handleMesg r -- transform tree (concerns only tiled windows) ws' = adjustStack ws lws lfs b' -- apply transformation to window stack, reintegrate floating wins replaceStack ws' return b' where handleMesg r = msum [ fmap resize (fromMessage m) , fmap rotate (fromMessage m) , fmap swap (fromMessage m) , fmap rotateTr (fromMessage m) , fmap (balanceTr r) (fromMessage m) , fmap move (fromMessage m) , fmap splitShift (fromMessage m) ] resize (ExpandTowardsBy dir diff) = growNthTowards dir diff b resize (ShrinkFromBy dir diff) = shrinkNthFrom dir diff b resize (MoveSplitBy dir diff) = autoSizeNth dir diff b rotate Rotate = resetFoc $ rotateNth b swap Swap = resetFoc $ swapNth b rotateTr RotateL = resetFoc $ rotateTreeNth L b rotateTr RotateR = resetFoc $ rotateTreeNth R b balanceTr _ Equalize = resetFoc $ equalizeNth b balanceTr r Balance = resetFoc $ rebalanceNth b r move MoveNode = resetFoc $ moveNode b move SelectNode = b --should not happen here, is done above, as we need X monad splitShift (SplitShift dir) = resetFoc $ splitShiftNth dir b b = numerateLeaves b_orig resetFoc bsp = bsp{getFocusedNode=(getFocusedNode bsp){refLeaf= -1} ,getSelectedNode=(getSelectedNode bsp){refLeaf= -1}} description _ = "BSP" -- React to SetGeometry message to work with BorderResize/MouseResize handleResize :: BinarySpacePartition Window -> WindowArrangerMsg -> X (Maybe (BinarySpacePartition Window)) handleResize b (SetGeometry newrect@(Rectangle _ _ w h)) = do ws <- getStackSet fs <- getFloating hs <- getHidden case W.focus <$> ws of Nothing -> return Nothing Just win -> do (_,_,_,_,_,mx,my,_) <- withDisplay (\d -> io $ queryPointer d win) let oldrect@(Rectangle _ _ ow oh) = fromMaybe (Rectangle 0 0 0 0) $ lookup win $ getOldRects b let (xsc,ysc) = (fi w % fi ow, fi h % fi oh) (xsc',ysc') = (rough xsc, rough ysc) dirs = changedDirs oldrect newrect (fi mx,fi my) n = elemIndex win $ maybe [] W.integrate $ withoutFloating fs hs ws -- unless (isNothing dir) $ debug $ -- show (fi x-fi ox,fi y-fi oy) ++ show (fi w-fi ow,fi h-fi oh) -- ++ show dir ++ " " ++ show win ++ " " ++ show (mx,my) return $ case n of Just _ -> Just $ foldl' (\b' d -> resizeSplitNth d (xsc',ysc') b') b dirs Nothing -> Nothing --focused window is floating -> ignore where rough v = min 1.5 $ max 0.75 v -- extreme scale factors are forbidden handleResize _ _ = return Nothing -- find out which borders have been pulled. We need the old and new rects and the mouse coordinates changedDirs :: Rectangle -> Rectangle -> (Int,Int) -> [Direction2D] changedDirs (Rectangle _ _ ow oh) (Rectangle _ _ w h) (mx,my) = catMaybes [lr, ud] where lr = if ow==w then Nothing else Just (if (fi mx :: Double) > (fi ow :: Double)/2 then R else L) ud = if oh==h then Nothing else Just (if (fi my :: Double) > (fi oh :: Double)/2 then D else U) -- node focus border helpers ---------------------------- updateNodeRef :: BinarySpacePartition Window -> Bool -> Rectangle -> X (BinarySpacePartition Window) updateNodeRef b force r = do let n = getFocusedNode b let s = getSelectedNode b removeBorder (refWins n++refWins s) l <- getCurrFocused b' <- if refLeaf n /= l || refLeaf n == (-1) || force then return b{getFocusedNode=leafToNodeRef l b} else return b b'' <- if force then return b'{getSelectedNode=noRef} else return b' renderBorders r b'' where getCurrFocused = maybe 0 index <$> (withoutFloating <$> getFloating <*> getHidden <*> getStackSet) -- create border around focused node if necessary renderBorders :: Rectangle -> BinarySpacePartition a -> X (BinarySpacePartition a) renderBorders r b = do let l = nodeRefToLeaf (getFocusedNode b) $ makeZipper b wssel <- if refLeaf (getSelectedNode b)/=(-1) then createBorder (getNodeRect b r (getSelectedNode b)) $ Just "#00ff00" else return [] let b' = b{getSelectedNode=(getSelectedNode b){refWins=wssel}} if refLeaf (getFocusedNode b')==(-1) || isJust l || size b'<2 then return b' else do ws' <- createBorder (getNodeRect b' r (getFocusedNode b')) Nothing return b'{getFocusedNode=(getFocusedNode b'){refWins=ws'}} -- create a window for each border line, show, add into stack and set floating createBorder :: Rectangle -> Maybe String -> X [Window] createBorder (Rectangle wx wy ww wh) c = do bw <- asks (borderWidth.config) bc <- case c of Nothing -> asks (focusedBorderColor.config) Just s -> return s let rects = [ Rectangle wx wy ww (fi bw) , Rectangle wx wy (fi bw) wh , Rectangle wx (wy+fi wh-fi bw) ww (fi bw) , Rectangle (wx+fi ww-fi bw) wy (fi bw) wh ] ws <- mapM (\r -> createNewWindow r Nothing bc False) rects showWindows ws replaceStack . maybe Nothing (\s -> Just s{W.down=W.down s ++ ws}) =<< getStackSet replaceFloating . M.union (M.fromList $ zip ws $ map toRR rects) . W.floating . windowset =<< get modify (\s -> s{mapped=mapped s `S.union` S.fromList ws}) -- show <$> mapM isClient ws >>= debug return ws where toRR (Rectangle x y w h) = W.RationalRect (fi x) (fi y) (fi w) (fi h) -- remove border line windows from stack + floating, kill removeBorder :: [Window] -> X () removeBorder ws = do modify (\s -> s{mapped = mapped s `S.difference` S.fromList ws}) replaceFloating . flip (foldl (flip M.delete)) ws . W.floating . windowset =<< get replaceStack . maybe Nothing (\s -> Just s{W.down=W.down s \\ ws}) =<< getStackSet deleteWindows ws
xmonad/xmonad-contrib
XMonad/Layout/BinarySpacePartition.hs
bsd-3-clause
39,379
2
21
8,847
13,840
7,052
6,788
621
6
-- -- Main: mainroutine of Aya -- module Main ( main ) where import Aya.Renderer main = do writeFile "aya.ppm" (header ++ imageToStr (smoothen image))
eiji-a/aya
src/Main.hs
bsd-3-clause
159
0
12
33
46
26
20
5
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} module Villefort.Server where import Web.Scotty import Control.Monad.Reader import Control.Concurrent import Data.Text.Lazy hiding (splitOn,map,concat,head,replace) import Villefort.Database import Villefort.Todo (deleteTodo,getTodos,updateTodos) import Villefort.Log import Villefort.Definitions import Villefort.Weekly import Paths_Villefort import Villefort.Daily import Villefort.New (makeNewPage) import Villefort.Today import Data.List.Split import System.Environment import System.Process import System.Directory import System.Posix.Process import Data.String.Utils getIndex :: [[Char]] -> Int -> [Char] getIndex str i = (Data.List.Split.splitOn "=" (str !! i)) !! 1 -- | Converts date from Javascript to sqlite date fromat convDate :: String -> String convDate date = newDate where splitDate = Data.List.Split.splitOn "%2F" date newDate = (splitDate !! 2) ++ "-" ++ (splitDate !! 0) ++ "-" ++ (splitDate !! 1) -- | Entry point for server attempts to recompile if needed villefort :: VConfig -> IO () villefort conf = do args <- getArgs case args of ["--custom",_] -> putStrLn "custom" >> launch conf ["--recompile"] -> putStrLn "recompiling" >> recompile _ -> putStrLn "straight starting " >> do if noCustom conf then launch conf >> putStrLn "overload" else checkCustomBuild >> launch conf -- | recompiles villefort by calling ghc expects .villefort/villefort.hs in home directory recompile :: IO () recompile = do dir <- getAppUserDataDirectory "villefort" let execPath = dir ++ "/villefort" sourcePath = dir ++"/villefort.hs" (_,_,_,pid) <- createProcess (proc "/usr/bin/ghc" ["-o",execPath,sourcePath]) _ <- waitForProcess pid return () -- | checks for executable in villefort home folder if so it executes it checkCustomBuild :: IO () checkCustomBuild = do dir <- getAppUserDataDirectory "villefort" let path = dir ++ "/villefort" isBuild <- doesFileExist path dataDir <- getDataDir if isBuild then putStrLn "custom buil detected" >> executeFile path True ["--custom",dataDir] Nothing else putStrLn "no custom build :(" -- | actually launches the scotty server launch :: VConfig -> IO () launch conf = do _ <- forkIO $ dailyCheck conf scotty ( port conf) $ do get "/" $ do todos <- liftIO $ runReaderT getTodos conf html $ pack $ todos get "/new" $ do page <- liftIO $ runReaderT makeNewPage conf html $ pack page post "/delete" $ do rawHtml <- body runReaderT (deleteTodo rawHtml) conf redirect "/" post "/update" $ do rawHtml <- body let da = Data.List.Split.splitOn "&" (show rawHtml) do liftIO $ print $ show da let rawid = Data.List.Split.splitOn "=" $ (Prelude.init (da !! 1)) let sqlId = read (rawid!! 1) :: Int let rawtime = Data.List.Split.splitOn "=" $ (da !! 0) do liftIO $ print rawtime let insertTime = read (rawtime !! 1) :: Int liftIO $ runReaderT (updateTodos sqlId insertTime) conf redirect "/" post "/add" $ do rawBody <-body let parse = Data.List.Split.splitOn "&" (show rawBody) do liftIO $ print parse -- !@#$%^&*()_+ let rep = replace "+" " " . replace "%21" "!" . replace "%40" "@" . replace "%23" "#" . replace "%24" "$" . replace "%25" "%" . replace "%5E" "^" . replace "%26" "&" . replace "%28" "(" . replace "%29" ")" . replace "%2B" "+" let summary = rep $ getIndex parse 0 let date = convDate $ getIndex parse 3 let todoTitle = rep $ getIndex parse 1 let todoSubject = rep $ getIndex parse 2 liftIO $ runReaderT (addTask todoTitle summary date todoSubject) conf redirect "/" get "/today" $ do dat <-liftIO $ runReaderT getSummary conf html $ pack dat get "/templates/:asset" $ do asset <- param "asset" path <- liftIO $ getDataFileName $ "templates/" ++ asset file path get "/weekly" $ do to <- liftIO $ runReaderT weeklyStats conf html $ pack to get "/log" $ do page <- liftIO $runReaderT genStats conf html $ pack page
Chrisr850/Villefort
src/Villefort/Server.hs
bsd-3-clause
4,281
0
26
1,043
1,366
662
704
105
4
module Vandelay.App.Cmd.Make ( makeTables , makeTable ) where import Control.Monad.Trans.RWS hiding (ask, asks) import Rainbow import qualified Rainbow.Translate as RT import System.FilePath import Vandelay.App.Template.ParserT import Vandelay.DSL.Core import Vandelay.DSL.Estimates makeTables ∷ FilePath -- ^ Output directory → [String] -- ^ Vandelay template filepath globs → EIO ErrorMsg () -- ^ Error message or () makeTables dir gs = mapM_ (makeTable dir) =<< globPaths gs -- | Create a LaTeX table from a Vandelay template makeTable ∷ FilePath -- ^ Output directory → String -- ^ Vandelay template filepath → EIO ErrorMsg () -- ^ Error message or () makeTable dir templatePath = addFilepathIfError $ do template <- readTemplate templatePath let outFile = dir </> takeFileName templatePath -<.> "tex" (_,_,res) <- runMakeMonad createOutput template liftIO . RT.putChunk $ Rainbow.chunk (asText "Success: ") & fore green liftIO . putStrLn $ tTemplatePath unsafeWriteFile (Just outFile) res where addFilepathIfError = prependError ("In template: " ++ tTemplatePath ++ "\n") tTemplatePath = pack templatePath -- | Internal data types type MakeMonad = RWST VandelayTemplate Text () (EIO ErrorMsg) runMakeMonad mm vtl = runRWST mm vtl () askTable ∷ MakeMonad [TableCommand] askDesiredModels ∷ MakeMonad [(Maybe FilePath, Text)] askSubstitutions ∷ MakeMonad [(Text, Text)] askEstimatesHM ∷ MakeMonad EstimatesHM askTable = asks table askDesiredModels = hoistEitherError . getDesiredModels =<< ask askSubstitutions = asks substitutions askEstimatesHM = hoistEitherError . getEstimatesHM =<< ask -- | Table output creation functions createOutput ∷ MakeMonad () createOutput = mapM_ doTableCommand =<< askTable doTableCommand ∷ TableCommand → MakeMonad () doTableCommand (Latex l) = tellLn l doTableCommand (Template t) = tellLn =<< doSubstitution <$> (lift . safeReadFile $ t) <*> askSubstitutions doTableCommand (Data or) = tellLn =<< hoistEitherError =<< outputRow or <$> askEstimatesHM <*> askDesiredModels -- | Text utility functions tellLn ∷ Text → MakeMonad () tellLn s = tell $ s ++ "\n"
tumarkin/vandelay
src/Vandelay/App/Cmd/Make.hs
bsd-3-clause
2,347
0
13
521
589
311
278
-1
-1
module Main (main) where main :: IO () main = putStrLn "Do nothing"
rcook/sudoku-solver
src/Main.hs
bsd-3-clause
69
0
6
14
27
15
12
3
1
-- Copyright (c) 2016 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS -- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. {-# OPTIONS_GHC -funbox-strict-fields -Wall #-} {-# LANGUAGE MultiParamTypeClasses, ScopedTypeVariables, FlexibleContexts, FlexibleInstances #-} -- | Implementation of static dictionaries based on FKS hashing schemes. module Data.Dict.Linear( module Data.Dict, LinearDict, dict, ) where import Control.Monad import Data.Bits import Data.Dict import Data.IORef import Data.Maybe import Data.Vector(Vector) import System.IO.Unsafe import System.Random import qualified Data.Vector as Vector import qualified Data.Vector.Mutable as Mutable import qualified Data.Vector.Unboxed as Unboxed -- | Static dictionary based on linear probing with a tabulation hash -- function. data LinearDict keyty elemty = LinearDict { -- | Pointer to the tabulation hash function. dictHash :: !(Unboxed.Vector Int), -- | The entry hash table dictEntries :: !(Vector (Maybe (keyty, elemty))) } hashfuncs :: IORef [Unboxed.Vector Int] hashfuncs = unsafePerformIO $! newIORef [] addhash :: Unboxed.Vector Int -> IO () addhash hashfun = modifyIORef hashfuncs (++ [hashfun]) dict :: Enum keyty => [(keyty, elemty)] -> IO (LinearDict keyty elemty) dict alist = let alpha = 4 arrlen = length alist * alpha -- Try this hash function, succeed if there a tryhash arr hasharr = let addelems (assoc @ (key, _) : rest) = let idx = corehash hasharr arrlen key -- Linear probe insert lininsert offset -- Fix alpha to be the bucket size | offset < alpha = do ent <- Mutable.read arr (idx + offset) -- Check this entry case ent of -- If we collide, try the next index Just _ -> lininsert (offset + 1) -- If we find an open slot, use it Nothing -> do Mutable.write arr (idx + offset) $! Just assoc addelems rest -- If we go to far, fail | otherwise = return Nothing in lininsert 0 -- If we make it here, we're done. addelems [] = do -- Add the hash function addhash hasharr -- Freeze the array and return it frozen <- Vector.unsafeFreeze arr return $! Just (hasharr, frozen) in do -- Clear the array forM_ [0..arrlen - 1] (\i -> Mutable.write arr i Nothing) addelems alist -- Try hash functions until one succeeds genhash arr = do hasharr <- Unboxed.replicateM 0x800 randomIO res <- tryhash arr hasharr case res of Just out -> return out Nothing -> genhash arr -- If we run out of hash functions, switch over to genhash tryall arr [] = genhash arr tryall arr (first : rest) = do -- Try the hash function res <- tryhash arr first case res of -- If it works, return it Just out -> return out -- Otherwise, move on Nothing -> tryall arr rest in do arr <- Mutable.new arrlen hashes <- readIORef hashfuncs (hasharr, entarr) <- tryall arr hashes return LinearDict { dictEntries = entarr, dictHash = hasharr } tabhash :: (Enum keyty) => LinearDict keyty elemty -> keyty -> Int tabhash LinearDict { dictHash = hasharr, dictEntries = ents } key = corehash hasharr (length ents) key corehash :: Enum keyty => Unboxed.Vector Int -> Int -> keyty -> Int corehash hasharr nents key = let keyval = fromEnum key -- Fragment the key k0 = keyval .&. 0xff k1 = (keyval `shiftR` 8) .&. 0xff k2 = (keyval `shiftR` 16) .&. 0xff k3 = (keyval `shiftR` 24) .&. 0xff k4 = (keyval `shiftR` 32) .&. 0xff k5 = (keyval `shiftR` 40) .&. 0xff k6 = (keyval `shiftR` 48) .&. 0xff k7 = (keyval `shiftR` 56) .&. 0xff -- Get the index parts i0 = hasharr Unboxed.! k0 i1 = hasharr Unboxed.! k1 + 0x100 i2 = hasharr Unboxed.! k2 + 0x200 i3 = hasharr Unboxed.! k3 + 0x300 i4 = hasharr Unboxed.! k4 + 0x400 i5 = hasharr Unboxed.! k5 + 0x500 i6 = hasharr Unboxed.! k6 + 0x600 i7 = hasharr Unboxed.! k7 + 0x700 hashcode = i0 `xor` i1 `xor` i2 `xor` i3 `xor` i4 `xor` i5 `xor` i6 `xor` i7 in hashcode `mod` nents instance (Enum keyty, Eq keyty) => Dict keyty LinearDict where member d @ LinearDict { dictEntries = ents } key = let entslen = length ents -- Linear probe function probe idx | idx < entslen = case ents Vector.! idx of -- If we find the key, we're done Just (key', _) | key == key' -> True -- If we find nothing, it's not there Nothing -> False -- Otherwise, check the next slot _ -> probe (idx + 1) | otherwise = False in probe (tabhash d key) lookup d @ LinearDict { dictEntries = ents } key = let entslen = length ents -- Linear probe function probe idx | idx < entslen = case ents Vector.! idx of -- If we find the key, we're done Just (key', ent) | key == key' -> Just ent -- If we find nothing, it's not there Nothing -> Nothing -- Otherwise, check the next slot _ -> probe (idx + 1) | otherwise = Nothing in probe (tabhash d key) assocs = catMaybes . Vector.toList . dictEntries instance Functor (LinearDict keyty) where fmap f LinearDict { dictEntries = ents, dictHash = hasharr } = LinearDict { dictEntries = fmap (fmap (fmap f)) ents, dictHash = hasharr } instance Foldable (LinearDict keyty) where foldMap f = foldMap (foldMap (foldMap f)) . dictEntries instance Traversable (LinearDict keyty) where traverse f l @ LinearDict { dictEntries = ents } = (\ents' -> l { dictEntries = ents' }) <$> traverse (traverse (traverse f)) ents
emc2/static-dict
src/Data/Dict/Linear.hs
bsd-3-clause
7,655
4
28
2,283
1,717
917
800
139
6
---------------------------------------------------------------------- -- | -- Module : Network.HaskellNet.IMAP -- Copyright : (c) Jun Mukai 2006 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : mukai@jmuk.org -- Stability : stable -- Portability : portable -- -- IMAP client implementation -- module Network.HaskellNet.IMAP ( -- * connection type and corresponding actions IMAPConnection , mailbox, exists, recent , flags, permanentFlags, isWritable, isFlagWritable , uidNext, uidValidity , stream , connectIMAP, connectIMAPPort, connectStream -- * IMAP commands -- ** any state commands , noop, capability, logout -- ** not authenticated state commands , login, authenticate -- ** autenticated state commands , select, examine, create, delete, rename , subscribe, unsubscribe , list, lsub, status, append -- ** selected state commands , check, close, expunge , search, store, copy -- * fetch commands , fetch, fetchHeader, fetchSize, fetchHeaderFields, fetchHeaderFieldsNot , fetchFlags, fetchR, fetchByString, fetchByStringR -- * other types , Flag(..), Attribute(..), MailboxStatus(..) , SearchQuery(..), FlagsQuery(..) ) where import Network import Network.HaskellNet.BSStream import Network.HaskellNet.Auth hiding (auth, login) import qualified Network.HaskellNet.Auth as A import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BS import Data.Digest.MD5 import Control.Monad import Control.Monad.Writer import System.IO import System.Time import Data.IORef import Data.Maybe import Data.Word import Data.List hiding (delete) import Data.Char import Text.IMAPParsers hiding (exists, recent) import Text.Packrat.Parse (Result) ---------------------------------------------------------------------- -- connection type and corresponding functions data BSStream s => IMAPConnection s = IMAPC s (IORef MailboxInfo) (IORef Int) mailbox :: BSStream s => IMAPConnection s -> IO Mailbox mailbox (IMAPC _ mbox _) = fmap _mailbox $ readIORef mbox exists, recent :: BSStream s => IMAPConnection s -> IO Integer exists (IMAPC _ mbox _) = fmap _exists $ readIORef mbox recent (IMAPC _ mbox _) = fmap _recent $ readIORef mbox flags, permanentFlags :: BSStream s => IMAPConnection s -> IO [Flag] flags (IMAPC _ mbox _) = fmap _flags $ readIORef mbox permanentFlags (IMAPC _ mbox _) = fmap _permanentFlags $ readIORef mbox isWritable, isFlagWritable :: BSStream s => IMAPConnection s -> IO Bool isWritable (IMAPC _ mbox _) = fmap _isWritable $ readIORef mbox isFlagWritable (IMAPC _ mbox _) = fmap _isFlagWritable $ readIORef mbox uidNext, uidValidity :: BSStream s => IMAPConnection s -> IO UID uidNext (IMAPC _ mbox _) = fmap _uidNext $ readIORef mbox uidValidity (IMAPC _ mbox _) = fmap _uidValidity $ readIORef mbox stream :: BSStream s => IMAPConnection s -> s stream (IMAPC s _ _) = s -- suffixed by `s' data SearchQuery = ALLs | FLAG Flag | UNFLAG Flag | BCCs String | BEFOREs CalendarTime | BODYs String | CCs String | FROMs String | HEADERs String String | LARGERs Integer | NEWs | NOTs SearchQuery | OLDs | ONs CalendarTime | ORs SearchQuery SearchQuery | SENTBEFOREs CalendarTime | SENTONs CalendarTime | SENTSINCEs CalendarTime | SINCEs CalendarTime | SMALLERs Integer | SUBJECTs String | TEXTs String | TOs String | UIDs [UID] instance Show SearchQuery where showsPrec d q = showParen (d>app_prec) $ showString $ showQuery q where app_prec = 10 showQuery ALLs = "ALL" showQuery (FLAG f) = showFlag f showQuery (UNFLAG f) = "UN" ++ showFlag f showQuery (BCCs addr) = "BCC " ++ addr showQuery (BEFOREs t) = "BEFORE " ++ dateToStringIMAP t showQuery (BODYs s) = "BODY " ++ s showQuery (CCs addr) = "CC " ++ addr showQuery (FROMs addr) = "FROM " ++ addr showQuery (HEADERs f v) = "HEADER " ++ f ++ " " ++ v showQuery (LARGERs siz) = "LARGER {" ++ show siz ++ "}" showQuery NEWs = "NEW" showQuery (NOTs q) = "NOT " ++ show q showQuery OLDs = "OLD" showQuery (ONs t) = "ON " ++ dateToStringIMAP t showQuery (ORs q1 q2) = "OR " ++ show q1 ++ " " ++ show q2 showQuery (SENTBEFOREs t) = "SENTBEFORE " ++ dateToStringIMAP t showQuery (SENTONs t) = "SENTON " ++ dateToStringIMAP t showQuery (SENTSINCEs t) = "SENTSINCE " ++ dateToStringIMAP t showQuery (SINCEs t) = "SINCE " ++ dateToStringIMAP t showQuery (SMALLERs siz) = "SMALLER {" ++ show siz ++ "}" showQuery (SUBJECTs s) = "SUBJECT " ++ s showQuery (TEXTs s) = "TEXT " ++ s showQuery (TOs addr) = "TO " ++ addr showQuery (UIDs uids) = concat $ intersperse "," $ map show uids showFlag Seen = "SEEN" showFlag Answered = "ANSWERED" showFlag Flagged = "FLAGGED" showFlag Deleted = "DELETED" showFlag Draft = "DRAFT" showFlag Recent = "RECENT" showFlag (Keyword s) = "KEYWORD " ++ s data FlagsQuery = ReplaceFlags [Flag] | PlusFlags [Flag] | MinusFlags [Flag] ---------------------------------------------------------------------- -- establish connection connectIMAPPort :: String -> PortNumber -> IO (IMAPConnection Handle) connectIMAPPort hostname port = connectTo hostname (PortNumber port) >>= connectStream connectIMAP :: String -> IO (IMAPConnection Handle) connectIMAP hostname = connectIMAPPort hostname 143 connectStream :: BSStream s => s -> IO (IMAPConnection s) connectStream s = do msg <- bsGetLine s unless (and $ BS.zipWith (==) msg (BS.pack "* OK")) $ fail "cannot connect to the server" mbox <- newIORef emptyMboxInfo c <- newIORef 0 return $ IMAPC s mbox c emptyMboxInfo = MboxInfo "" 0 0 [] [] False False 0 0 ---------------------------------------------------------------------- -- normal send commands sendCommand' :: BSStream s => IMAPConnection s -> String -> IO ByteString sendCommand' (IMAPC s mbox nr) cmdstr = do num <- readIORef nr bsPutCrLf s $ BS.pack $ show6 num ++ " " ++ cmdstr modifyIORef nr (+1) getResponse s show6 n | n > 100000 = show n | n > 10000 = '0' : show n | n > 1000 = "00" ++ show n | n > 100 = "000" ++ show n | n > 10 = "0000" ++ show n | otherwise = "00000" ++ show n sendCommand :: BSStream s => IMAPConnection s -> String -> (RespDerivs -> Result RespDerivs (ServerResponse, MboxUpdate, v)) -> IO v sendCommand imapc@(IMAPC _ mbox nr) cmdstr pFunc = do num <- readIORef nr buf <- sendCommand' imapc cmdstr let (resp, mboxUp, value) = eval pFunc (show6 num) buf case resp of OK _ _ -> do mboxUpdate mbox $ mboxUp return value NO _ msg -> fail ("NO: " ++ msg) BAD _ msg -> fail ("BAD: " ++ msg) PREAUTH _ msg -> fail ("preauth: " ++ msg) getResponse :: BSStream s => s -> IO ByteString getResponse s = fmap unlinesCRLF getLs where unlinesCRLF = BS.concat . concatMap (:[crlf]) getLs = do l <- fmap strip $ bsGetLine s case () of _ | isLiteral l -> do l' <- getLiteral l (getLitLen l) ls <- getLs return (l' : ls) | isTagged l -> fmap (l:) getLs | otherwise -> return [l] getLiteral l len = do lit <- bsGet s len l2 <- fmap strip $ bsGetLine s let l' = BS.concat [l, crlf, lit, l2] if isLiteral l2 then getLiteral l' (getLitLen l2) else return l' crlf = BS.pack "\r\n" isLiteral l = BS.last l == '}' && BS.last (fst (BS.spanEnd isDigit (BS.init l))) == '{' getLitLen = read . BS.unpack . snd . BS.spanEnd isDigit . BS.init isTagged l = BS.head l == '*' && BS.head (BS.tail l) == ' ' mboxUpdate :: IORef MailboxInfo -> MboxUpdate -> IO () mboxUpdate mbox (MboxUpdate exists recent) = do when (isJust exists) $ do mb <- readIORef mbox writeIORef mbox (mb { _exists = e }) when (isJust recent) $ do mb <- readIORef mbox writeIORef mbox (mb { _recent = r }) where e = fromJust exists r = fromJust recent ---------------------------------------------------------------------- -- IMAP commands -- noop :: BSStream s => IMAPConnection s -> IO () noop conn@(IMAPC s mbox _) = sendCommand conn "NOOP" pNone capability :: BSStream s => IMAPConnection s -> IO [String] capability conn = sendCommand conn "CAPABILITY" pCapability logout :: BSStream s => IMAPConnection s -> IO () logout conn@(IMAPC s _ _) = do bsPutCrLf s $ BS.pack "a0001 LOGOUT" bsClose s login :: BSStream s => IMAPConnection s -> UserName -> Password -> IO () login conn user pass = sendCommand conn ("LOGIN " ++ user ++ " " ++ pass) pNone select, examine, create, delete :: BSStream s => IMAPConnection s -> Mailbox -> IO () _select cmd conn@(IMAPC s mbox _) mboxName = do mbox' <- sendCommand conn (cmd ++ mboxName) pSelect writeIORef mbox (mbox' { _mailbox = mboxName }) authenticate :: BSStream s => IMAPConnection s -> AuthType -> UserName -> Password -> IO () authenticate conn@(IMAPC s mbox nr) LOGIN user pass = do num <- readIORef nr sendCommand' conn "AUTHENTICATE LOGIN" bsPutCrLf s $ BS.pack userB64 bsGetLine s bsPutCrLf s $ BS.pack passB64 buf <- getResponse s let (resp, mboxUp, value) = eval pNone (show6 num) buf case resp of OK _ _ -> do mboxUpdate mbox $ mboxUp return value NO _ msg -> fail ("NO: " ++ msg) BAD _ msg -> fail ("BAD: " ++ msg) PREAUTH _ msg -> fail ("preauth: " ++ msg) where (userB64, passB64) = A.login user pass authenticate conn@(IMAPC s mbox nr) at user pass = do num <- readIORef nr c <- sendCommand' conn $ "AUTHENTICATE " ++ show at let challenge = if BS.take 2 c == BS.pack "+ " then b64Decode $ BS.unpack $ head $ dropWhile (isSpace . BS.last) $ BS.inits $ BS.drop 2 c else "" bsPutCrLf s $ BS.pack $ A.auth at challenge user pass buf <- getResponse s let (resp, mboxUp, value) = eval pNone (show6 num) buf case resp of OK _ _ -> do mboxUpdate mbox $ mboxUp return value NO _ msg -> fail ("NO: " ++ msg) BAD _ msg -> fail ("BAD: " ++ msg) PREAUTH _ msg -> fail ("preauth: " ++ msg) select = _select "SELECT " examine = _select "EXAMINE " create conn mboxname = sendCommand conn ("CREATE " ++ mboxname) pNone delete conn mboxname = sendCommand conn ("DELETE " ++ mboxname) pNone rename :: BSStream s => IMAPConnection s -> Mailbox -> Mailbox -> IO () rename conn mboxorg mboxnew = sendCommand conn ("RENAME " ++ mboxorg ++ " " ++ mboxnew) pNone subscribe, unsubscribe :: BSStream s => IMAPConnection s -> Mailbox -> IO () subscribe conn mboxname = sendCommand conn ("SUBSCRIBE " ++ mboxname) pNone unsubscribe conn mboxname = sendCommand conn ("UNSUBSCRIBE " ++ mboxname) pNone list, lsub :: BSStream s => IMAPConnection s -> IO [([Attribute], Mailbox)] list conn = fmap (map (\(a, _, m) -> (a, m))) $ listFull conn "\"\"" "*" lsub conn = fmap (map (\(a, _, m) -> (a, m))) $ lsubFull conn "\"\"" "*" listPat, lsubPat :: BSStream s => IMAPConnection s -> String -> IO [([Attribute], String, Mailbox)] listPat conn pat = listFull conn "\"\"" pat lsubPat conn pat = lsubFull conn "\"\"" pat listFull, lsubFull :: BSStream s => IMAPConnection s -> String -> String -> IO [([Attribute], String, Mailbox)] listFull conn ref pat = sendCommand conn (unwords ["LIST", ref, pat]) pList lsubFull conn ref pat = sendCommand conn (unwords ["LSUB", ref, pat]) pLsub status :: BSStream s => IMAPConnection s -> Mailbox -> [MailboxStatus] -> IO [(MailboxStatus, Integer)] status conn mbox stats = sendCommand conn ("STATUS " ++ mbox ++ " (" ++ (unwords $ map show stats) ++ ")") pStatus append :: BSStream s => IMAPConnection s -> Mailbox -> ByteString -> IO () append conn mbox mailData = appendFull conn mbox mailData [] Nothing appendFull :: BSStream s => IMAPConnection s -> Mailbox -> ByteString -> [Flag] -> Maybe CalendarTime -> IO () appendFull conn@(IMAPC s mbInfo nr) mbox mailData flags time = do num <- readIORef nr buf <- sendCommand' conn (unwords ["APPEND", mbox , fstr, tstr, "{" ++ show len ++ "}"]) unless (BS.null buf || (BS.head buf /= '+')) $ fail "illegal server response" mapM_ (bsPutCrLf s) mailLines buf <- getResponse s let (resp, mboxUp, ()) = eval pNone (show6 num) buf case resp of OK _ _ -> mboxUpdate mbInfo mboxUp NO _ msg -> fail ("NO: "++msg) BAD _ msg -> fail ("BAD: "++msg) PREAUTH _ msg -> fail ("PREAUTH: "++msg) where mailLines = BS.lines mailData len = sum $ map ((2+) . BS.length) mailLines tstr = maybe "" show time fstr = unwords $ map show flags check :: BSStream s => IMAPConnection s -> IO () check conn = sendCommand conn "CHECK" pNone close :: BSStream s => IMAPConnection s -> IO () close conn@(IMAPC s mbox _) = do sendCommand conn "CLOSE" pNone writeIORef mbox emptyMboxInfo expunge :: BSStream s => IMAPConnection s -> IO [Integer] expunge conn = sendCommand conn "EXPUNGE" pExpunge search :: BSStream s => IMAPConnection s -> [SearchQuery] -> IO [UID] search conn queries = searchCharset conn "" queries searchCharset :: BSStream s => IMAPConnection s -> Charset -> [SearchQuery] -> IO [UID] searchCharset conn charset queries = sendCommand conn ("UID SEARCH " ++ (if not . null $ charset then charset ++ " " else "") ++ unwords (map show queries)) pSearch fetch, fetchHeader :: BSStream s => IMAPConnection s -> UID -> IO ByteString fetch conn uid = do lst <- fetchByString conn uid "BODY[]" return $ maybe BS.empty BS.pack $ lookup "BODY[]" lst fetchHeader conn uid = do lst <- fetchByString conn uid "BODY[HEADER]" return $ maybe BS.empty BS.pack $ lookup "BODY[HEADER]" lst fetchSize :: BSStream s => IMAPConnection s -> UID -> IO Int fetchSize conn uid = do lst <- fetchByString conn uid "RFC822.SIZE" return $ maybe 0 read $ lookup "RFC822.SIZE" lst fetchHeaderFields, fetchHeaderFieldsNot :: BSStream s => IMAPConnection s -> UID -> [String] -> IO ByteString fetchHeaderFields conn uid hs = do lst <- fetchByString conn uid ("BODY[HEADER.FIELDS "++unwords hs++"]") return $ maybe BS.empty BS.pack $ lookup ("BODY[HEADER.FIELDS "++unwords hs++"]") lst fetchHeaderFieldsNot conn uid hs = do lst <- fetchByString conn uid ("BODY[HEADER.FIELDS.NOT "++unwords hs++"]") return $ maybe BS.empty BS.pack $ lookup ("BODY[HEADER.FIELDS.NOT "++unwords hs++"]") lst fetchFlags :: BSStream s => IMAPConnection s -> UID -> IO [Flag] fetchFlags conn uid = do lst <- fetchByString conn uid "FLAGS" return $ getFlags $ lookup "FLAGS" lst where getFlags Nothing = [] getFlags (Just s) = eval' dvFlags "" s fetchR :: BSStream s => IMAPConnection s -> (UID, UID) -> IO [(UID, ByteString)] fetchR conn r = do lst <- fetchByStringR conn r "BODY[]" return $ map (\(uid, vs) -> (uid, maybe BS.empty BS.pack $ lookup "BODY[]" vs)) lst fetchByString :: BSStream s => IMAPConnection s -> UID -> String -> IO [(String, String)] fetchByString conn uid command = do lst <- fetchCommand conn ("UID FETCH "++show uid++" "++command) id return $ snd $ head lst fetchByStringR :: BSStream s => IMAPConnection s -> (UID, UID) -> String -> IO [(UID, [(String, String)])] fetchByStringR conn (s, e) command = fetchCommand conn ("UID FETCH "++show s++":"++show e++" "++command) proc where proc (n, ps) = (maybe (toEnum (fromIntegral n)) read (lookup "UID" ps), ps) fetchCommand conn command proc = fmap (map proc) $ sendCommand conn command pFetch storeFull :: BSStream s => IMAPConnection s -> String -> FlagsQuery -> Bool -> IO [(UID, [Flag])] storeFull conn uidstr query isSilent = fetchCommand conn ("UID STORE " ++ uidstr ++ flags query) procStore where fstrs fs = "(" ++ (concat $ intersperse " " $ map show fs) ++ ")" toFStr s fstrs = s ++ (if isSilent then ".SILENT" else "") ++ " " ++ fstrs flags (ReplaceFlags fs) = toFStr "FLAGS" $ fstrs fs flags (PlusFlags fs) = toFStr "+FLAGS" $ fstrs fs flags (MinusFlags fs) = toFStr "-FLAGS" $ fstrs fs procStore (n, ps) = (maybe (toEnum (fromIntegral n)) read (lookup "UID" ps) ,maybe [] (eval' dvFlags "") (lookup "FLAG" ps)) store :: BSStream s => IMAPConnection s -> UID -> FlagsQuery -> IO () storeR :: BSStream s => IMAPConnection s -> (UID, UID) -> FlagsQuery -> IO () store conn i q = storeFull conn (show i) q True >> return () storeR conn (s, e) q = storeFull conn (show s++":"++show e) q True >> return () -- storeResults is used without .SILENT, so that its response contains its result flags storeResults :: BSStream s => IMAPConnection s -> UID -> FlagsQuery -> IO [Flag] storeResultsR :: BSStream s => IMAPConnection s -> (UID, UID) -> FlagsQuery -> IO [(UID, [Flag])] storeResults conn i q = storeFull conn (show i) q False >>= return . snd . head storeResultsR conn (s, e) q = storeFull conn (show s++":"++show e) q False copy :: BSStream s => IMAPConnection s -> UID -> Mailbox -> IO () copyR :: BSStream s => IMAPConnection s -> (UID, UID) -> Mailbox -> IO () copyFull conn uidStr mbox = sendCommand conn ("UID COPY " ++ uidStr ++ " " ++ mbox) pNone copy conn uid mbox = copyFull conn (show uid) mbox copyR conn (s, e) mbox = copyFull conn (show s++":"++show e) mbox ---------------------------------------------------------------------- -- auxialiary functions dateToStringIMAP :: CalendarTime -> String dateToStringIMAP date = concat $ intersperse "-" [show2 $ ctDay date , showMonth $ ctMonth date , show $ ctYear date] where show2 n | n < 10 = '0' : show n | otherwise = show n showMonth January = "Jan" showMonth February = "Feb" showMonth March = "Mar" showMonth April = "Apr" showMonth May = "May" showMonth June = "Jun" showMonth July = "Jul" showMonth August = "Aug" showMonth September = "Sep" showMonth October = "Oct" showMonth November = "Nov" showMonth December = "Dec" strip :: ByteString -> ByteString strip = fst . BS.spanEnd isSpace . BS.dropWhile isSpace
d3zd3z/HaskellNet-old
Network/HaskellNet/IMAP.hs
bsd-3-clause
20,159
0
18
6,064
6,904
3,441
3,463
374
12
-- Copyright (c) 2015, Richard Laugesen (richard@tinyrock.com) -- All rights reserved. -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- * Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- * Neither the name of Tiny Rock Pty Ltd nor the names of its -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module Main where import qualified Data.ByteString.Lazy as BL import qualified Data.Vector as V import Control.Monad import Control.Applicative import Data.List import Data.Csv import Text.Printf import System.Environment import System.Random import GR4J import Stats import Verification import Optimisation main :: IO () main = do [file] <- getArgs rows <- parseFile file randG <- newStdGen let obs = V.toList rows params = ParameterSet 400 0 150 5 --params = ParameterSet 224.178126 0.874419 86.495168 1.114065 --params = ParameterSet 873.747803784 0.48279895597 47.6515381972 1.05798738125 init = initialState obs params sim = run obs params init qsim = [q | (q, _) <- sim] qobs = map q obs states = [state | (_, state) <- sim] v1s = map v1 states v2s = map v2 states results = zip3 qsim v1s v2s optResults = take 1000 $ optimise obs params (kge qobs qsim) kge randG (optParams, optObjFunValue) = last optResults putStr "\nRunning GR4J simulation with forcings from test_data.csv\n" putStr $ printf "\nParameterSet: %s\n" (show params) putStr $ printf "Initial conditions: %s\n\n" (show init) putStr $ printf "First 10 time-steps of simulation (q, v1, v2):\n" putStr $ unlines $ take 10 $ map showResults results putStr $ printf "\nMean obs precipitation: %.3f mm\n" (mean (map p obs)) putStr $ printf "Mean obs potential evapotranspiration: %.3f mm\n" (mean (map pe obs)) putStr $ printf "Mean obs streamflow: %.3f mm\n" (mean (map q obs)) putStr $ printf "Median obs precipitation: %.3f mm\n" (median (map p obs)) putStr $ printf "Median obs potential evapotranspiration: %.3f mm\n" (median (map pe obs)) putStr $ printf "Median obs streamflow: %.3f mm\n" (median (map q obs)) putStr $ printf "Mean sim streamflow: %.3f mm\n" (mean qsim) putStr $ printf "Median sim streamflow: %.3f mm\n" (median qsim) putStr $ printf "Standard Deviation sim streamflow: %.3f mm\n" (std qsim) putStr $ printf "\nNSE: %.3f\n" (nse qobs qsim) putStr $ printf "KGE: %.3f\n" (kge qobs qsim) putStr $ printf "RMSE: %.3f mm\n" (rmse qobs qsim) putStr $ printf "MAE: %.3f mm\n" (mae qobs qsim) putStr $ printf "Bias: %.3f mm\n" (bias qobs qsim) putStr $ printf "Bias (Score): %.3f\n" (biasScore qobs qsim) putStr $ printf "Bias (Multiplicative): %.3f\n" (multBias qobs qsim) putStr $ printf "Relative Variance: %.3f\n" (relativeVar qobs qsim) putStr $ printf "Bias (MSE): %.3f mm\n" (biasMse qobs qsim) putStr $ printf "Volume Error: %.3f%%\n" (volumeError qobs qsim) putStr $ printf "Correlation: %.3f\n" (cor qobs qsim) --putStr $ printf "\nObjective Function Trace:\n" --putStr $ unlines $ map (printf "%.3f") [objFunValue | (_, objFunValue) <- optResults] putStr $ printf "\nOptimised Parameters: %s\n" (show optParams) putStr $ printf "Objective Function: %.3f\n" (optObjFunValue) putStr "\nFull time-series written to test_results.csv\n\n" BL.writeFile "test_results.csv" $ encode results showResults :: (Double, Double, Double) -> String showResults (a, b, c) = printf "%.5f, %.5f, %.5f" a b c parseFile = liftM (either (error . show) (V.tail . V.init)) . parseCSVFromFile parseCSVFromFile :: FilePath -> IO (Either String (V.Vector Observation)) parseCSVFromFile = fmap (decode HasHeader) . BL.readFile instance FromRecord Observation where parseRecord v | V.length v == 5 = Observation <$> v .! 0 <*> v .! 3 <*> v .! 4 <*> v .! 1 | otherwise = mzero
tinyrock/gr4j
src/Main.hs
bsd-3-clause
5,285
0
14
1,142
1,079
538
541
74
1
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-} module Protocol.ROC.PointTypes.PointType9 where import GHC.Generics import qualified Data.ByteString as BS import Data.Word import Data.Binary import Data.Binary.Get import Protocol.ROC.Utils data PointType9 = PointType9 { pointType9Line1Text :: !PointType9Line1Text ,pointType9Line2Text :: !PointType9Line2Text ,pointType9Line3Text :: !PointType9Line3Text ,pointType9Line1TLP :: !PointType9Line1TLP ,pointType9Line2TLP :: !PointType9Line2TLP ,pointType9Line3TLP :: !PointType9Line3TLP } deriving (Read,Eq, Show, Generic) type PointType9Line1Text = BS.ByteString type PointType9Line2Text = BS.ByteString type PointType9Line3Text = BS.ByteString type PointType9Line1TLP = [Word8] type PointType9Line2TLP = [Word8] type PointType9Line3TLP = [Word8] pointType9Parser :: Get PointType9 pointType9Parser = do line1Text <- getByteString 10 line2Text <- getByteString 10 line3Text <- getByteString 10 line1TLP <- getTLP line2TLP <- getTLP line3TLP <- getTLP return $ PointType9 line1Text line2Text line3Text line1TLP line2TLP line3TLP
jqpeterson/roc-translator
src/Protocol/ROC/PointTypes/PointType9.hs
bsd-3-clause
1,646
0
9
569
249
139
110
44
1
module Database.Taxi.SegmentSet.Operations where import Control.Applicative ((<$>)) import Control.Concurrent.Async (mapConcurrently) import qualified Data.ByteString.Lazy as LB import Data.Binary (Binary, put, get) import Data.Binary.Get (runGet) import Data.Binary.Put (runPut) import qualified Data.Map.Strict as Map import Data.Maybe (fromJust) import Data.Text (Text) import Data.Set (Set) import qualified Data.Set as Set import Data.UUID (fromString) import System.FilePath ((</>)) import Database.Taxi.Segment.Constants import Database.Taxi.Segment.Types (SegmentId) import qualified Database.Taxi.Segment.InMemorySegment as MemSeg import qualified Database.Taxi.Segment.ExternalSegment as ExtSeg import Database.Taxi.SegmentSet.Types init :: Binary doc => FilePath -> IO (SegmentSet doc p) init baseDir = do delDocs <- readDeletedDocs baseDir segIds <- return [] -- undefined externalSegs <- mapM (ExtSeg.readSegment baseDir) segIds let uuids = map (fromJust . fromString) segIds extSegs = Map.fromList $ zip uuids externalSegs return SegmentSet { segSetBaseDir = baseDir , inMemorySegment = MemSeg.empty , externalSegments = extSegs , deletedDocs = delDocs } insert :: Ord p => SegmentSet doc p -> Text -> p -> SegmentSet doc p insert ss term p = ss { inMemorySegment = MemSeg.insert (inMemorySegment ss) term p } lookup :: (Binary p, Ord p) => SegmentSet doc p -> Text -> (Set doc -> Set p -> Set p) -> IO (Set p) lookup ss term f = do let memVals = MemSeg.lookup (inMemorySegment ss) term extSegs = Map.elems $ externalSegments ss extVals <- mapConcurrently (\seg -> ExtSeg.lookup seg baseDir term) extSegs return . removeDeleted $ foldr Set.union memVals extVals where baseDir = segSetBaseDir ss removeDeleted = f $ deletedDocs ss delete :: Ord doc => SegmentSet doc p -> doc -> SegmentSet doc p delete ss doc = ss { deletedDocs = Set.insert doc (deletedDocs ss) } readDeletedDocs :: Binary doc => FilePath -> IO (Set doc) readDeletedDocs baseDir = runGet get <$> LB.readFile delFilePath where delFilePath = baseDir </> deletedDocsFile writeDeletedDocs :: Binary doc => FilePath -> Set doc -> IO () writeDeletedDocs baseDir delDocs = LB.writeFile delFilePath (runPut . put $ delDocs) where delFilePath = baseDir </> deletedDocsFile getSegmentIds :: SegmentSet doc p -> [SegmentId] getSegmentIds = Map.keys . externalSegments
rabisg/taxi
Database/Taxi/SegmentSet/Operations.hs
bsd-3-clause
2,963
0
12
953
808
433
375
57
1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module UnitTests.Distribution.Client.ProjectConfig (tests) where #if !MIN_VERSION_base(4,8,0) import Data.Monoid import Control.Applicative #endif import Data.Map (Map) import qualified Data.Map as Map import Data.List import Distribution.Package import Distribution.PackageDescription hiding (Flag) import Distribution.Compiler import Distribution.Version import Distribution.ParseUtils import Distribution.Simple.Compiler import Distribution.Simple.Setup import Distribution.Simple.InstallDirs import qualified Distribution.Compat.ReadP as Parse import Distribution.Simple.Utils import Distribution.Simple.Program.Types import Distribution.Simple.Program.Db import Distribution.Client.Types import Distribution.Client.Dependency.Types import Distribution.Client.BuildReports.Types import Distribution.Client.Targets import Distribution.Utils.NubList import Network.URI import Distribution.Solver.Types.PackageConstraint import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.OptionalStanza import Distribution.Solver.Types.Settings import Distribution.Client.ProjectConfig import Distribution.Client.ProjectConfig.Legacy import UnitTests.Distribution.Client.ArbitraryInstances import Test.Tasty import Test.Tasty.QuickCheck tests :: [TestTree] tests = [ testGroup "ProjectConfig <-> LegacyProjectConfig round trip" $ [ testProperty "packages" prop_roundtrip_legacytypes_packages , testProperty "buildonly" prop_roundtrip_legacytypes_buildonly , testProperty "specific" prop_roundtrip_legacytypes_specific ] ++ -- a couple tests seem to trigger a RTS fault in ghc-7.6 and older -- unclear why as of yet concat [ [ testProperty "shared" prop_roundtrip_legacytypes_shared , testProperty "local" prop_roundtrip_legacytypes_local , testProperty "all" prop_roundtrip_legacytypes_all ] | not usingGhc76orOlder ] , testGroup "individual parser tests" [ testProperty "package location" prop_parsePackageLocationTokenQ ] , testGroup "ProjectConfig printing/parsing round trip" [ testProperty "packages" prop_roundtrip_printparse_packages , testProperty "buildonly" prop_roundtrip_printparse_buildonly , testProperty "shared" prop_roundtrip_printparse_shared , testProperty "local" prop_roundtrip_printparse_local , testProperty "specific" prop_roundtrip_printparse_specific , testProperty "all" prop_roundtrip_printparse_all ] ] where usingGhc76orOlder = case buildCompilerId of CompilerId GHC v -> v < mkVersion [7,7] _ -> False ------------------------------------------------ -- Round trip: conversion to/from legacy types -- roundtrip :: Eq a => (a -> b) -> (b -> a) -> a -> Bool roundtrip f f_inv x = (f_inv . f) x == x roundtrip_legacytypes :: ProjectConfig -> Bool roundtrip_legacytypes = roundtrip convertToLegacyProjectConfig convertLegacyProjectConfig prop_roundtrip_legacytypes_all :: ProjectConfig -> Bool prop_roundtrip_legacytypes_all config = roundtrip_legacytypes config { projectConfigProvenance = mempty } prop_roundtrip_legacytypes_packages :: ProjectConfig -> Bool prop_roundtrip_legacytypes_packages config = roundtrip_legacytypes config { projectConfigBuildOnly = mempty, projectConfigShared = mempty, projectConfigProvenance = mempty, projectConfigLocalPackages = mempty, projectConfigSpecificPackage = mempty } prop_roundtrip_legacytypes_buildonly :: ProjectConfigBuildOnly -> Bool prop_roundtrip_legacytypes_buildonly config = roundtrip_legacytypes mempty { projectConfigBuildOnly = config } prop_roundtrip_legacytypes_shared :: ProjectConfigShared -> Bool prop_roundtrip_legacytypes_shared config = roundtrip_legacytypes mempty { projectConfigShared = config } prop_roundtrip_legacytypes_local :: PackageConfig -> Bool prop_roundtrip_legacytypes_local config = roundtrip_legacytypes mempty { projectConfigLocalPackages = config } prop_roundtrip_legacytypes_specific :: Map PackageName PackageConfig -> Bool prop_roundtrip_legacytypes_specific config = roundtrip_legacytypes mempty { projectConfigSpecificPackage = MapMappend config } -------------------------------------------- -- Round trip: printing and parsing config -- roundtrip_printparse :: ProjectConfig -> Bool roundtrip_printparse config = case (fmap convertLegacyProjectConfig . parseLegacyProjectConfig . showLegacyProjectConfig . convertToLegacyProjectConfig) config of ParseOk _ x -> x == config { projectConfigProvenance = mempty } _ -> False prop_roundtrip_printparse_all :: ProjectConfig -> Bool prop_roundtrip_printparse_all config = roundtrip_printparse config { projectConfigBuildOnly = hackProjectConfigBuildOnly (projectConfigBuildOnly config), projectConfigShared = hackProjectConfigShared (projectConfigShared config) } prop_roundtrip_printparse_packages :: [PackageLocationString] -> [PackageLocationString] -> [SourceRepo] -> [Dependency] -> Bool prop_roundtrip_printparse_packages pkglocstrs1 pkglocstrs2 repos named = roundtrip_printparse mempty { projectPackages = map getPackageLocationString pkglocstrs1, projectPackagesOptional = map getPackageLocationString pkglocstrs2, projectPackagesRepo = repos, projectPackagesNamed = named } prop_roundtrip_printparse_buildonly :: ProjectConfigBuildOnly -> Bool prop_roundtrip_printparse_buildonly config = roundtrip_printparse mempty { projectConfigBuildOnly = hackProjectConfigBuildOnly config } hackProjectConfigBuildOnly :: ProjectConfigBuildOnly -> ProjectConfigBuildOnly hackProjectConfigBuildOnly config = config { -- These two fields are only command line transitory things, not -- something to be recorded persistently in a config file projectConfigOnlyDeps = mempty, projectConfigDryRun = mempty } prop_roundtrip_printparse_shared :: ProjectConfigShared -> Bool prop_roundtrip_printparse_shared config = roundtrip_printparse mempty { projectConfigShared = hackProjectConfigShared config } hackProjectConfigShared :: ProjectConfigShared -> ProjectConfigShared hackProjectConfigShared config = config { projectConfigProjectFile = mempty, -- not present within project files projectConfigConstraints = --TODO: [required eventually] parse ambiguity in constraint -- "pkgname -any" as either any version or disabled flag "any". let ambiguous (UserConstraint _ (PackagePropertyFlags flags), _) = (not . null) [ () | (name, False) <- flags , "any" `isPrefixOf` unFlagName name ] ambiguous _ = False in filter (not . ambiguous) (projectConfigConstraints config) } prop_roundtrip_printparse_local :: PackageConfig -> Bool prop_roundtrip_printparse_local config = roundtrip_printparse mempty { projectConfigLocalPackages = config } prop_roundtrip_printparse_specific :: Map PackageName (NonMEmpty PackageConfig) -> Bool prop_roundtrip_printparse_specific config = roundtrip_printparse mempty { projectConfigSpecificPackage = MapMappend (fmap getNonMEmpty config) } ---------------------------- -- Individual Parser tests -- prop_parsePackageLocationTokenQ :: PackageLocationString -> Bool prop_parsePackageLocationTokenQ (PackageLocationString str) = case [ x | (x,"") <- Parse.readP_to_S parsePackageLocationTokenQ (renderPackageLocationToken str) ] of [str'] -> str' == str _ -> False ------------------------ -- Arbitrary instances -- instance Arbitrary ProjectConfig where arbitrary = ProjectConfig <$> (map getPackageLocationString <$> arbitrary) <*> (map getPackageLocationString <$> arbitrary) <*> shortListOf 3 arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> (MapMappend . fmap getNonMEmpty . Map.fromList <$> shortListOf 3 arbitrary) -- package entries with no content are equivalent to -- the entry not existing at all, so exclude empty shrink ProjectConfig { projectPackages = x0 , projectPackagesOptional = x1 , projectPackagesRepo = x2 , projectPackagesNamed = x3 , projectConfigBuildOnly = x4 , projectConfigShared = x5 , projectConfigProvenance = x6 , projectConfigLocalPackages = x7 , projectConfigSpecificPackage = x8 } = [ ProjectConfig { projectPackages = x0' , projectPackagesOptional = x1' , projectPackagesRepo = x2' , projectPackagesNamed = x3' , projectConfigBuildOnly = x4' , projectConfigShared = x5' , projectConfigProvenance = x6' , projectConfigLocalPackages = x7' , projectConfigSpecificPackage = (MapMappend (fmap getNonMEmpty x8')) } | ((x0', x1', x2', x3'), (x4', x5', x6', x7', x8')) <- shrink ((x0, x1, x2, x3), (x4, x5, x6, x7, fmap NonMEmpty (getMapMappend x8))) ] newtype PackageLocationString = PackageLocationString { getPackageLocationString :: String } deriving Show instance Arbitrary PackageLocationString where arbitrary = PackageLocationString <$> oneof [ show . getNonEmpty <$> (arbitrary :: Gen (NonEmptyList String)) , arbitraryGlobLikeStr , show <$> (arbitrary :: Gen URI) ] arbitraryGlobLikeStr :: Gen String arbitraryGlobLikeStr = outerTerm where outerTerm = concat <$> shortListOf1 4 (frequency [ (2, token) , (1, braces <$> innerTerm) ]) innerTerm = intercalate "," <$> shortListOf1 3 (frequency [ (3, token) , (1, braces <$> innerTerm) ]) token = shortListOf1 4 (elements (['#'..'~'] \\ "{,}")) braces s = "{" ++ s ++ "}" instance Arbitrary ProjectConfigBuildOnly where arbitrary = ProjectConfigBuildOnly <$> arbitrary <*> arbitrary <*> arbitrary <*> (toNubList <$> shortListOf 2 arbitrary) -- 4 <*> arbitrary <*> arbitrary <*> arbitrary <*> (fmap getShortToken <$> arbitrary) -- 8 <*> arbitrary <*> arbitraryNumJobs <*> arbitrary <*> arbitrary <*> arbitrary <*> (fmap getShortToken <$> arbitrary) <*> arbitrary <*> (fmap getShortToken <$> arbitrary) <*> (fmap getShortToken <$> arbitrary) where arbitraryNumJobs = fmap (fmap getPositive) <$> arbitrary shrink ProjectConfigBuildOnly { projectConfigVerbosity = x00 , projectConfigDryRun = x01 , projectConfigOnlyDeps = x02 , projectConfigSummaryFile = x03 , projectConfigLogFile = x04 , projectConfigBuildReports = x05 , projectConfigReportPlanningFailure = x06 , projectConfigSymlinkBinDir = x07 , projectConfigOneShot = x08 , projectConfigNumJobs = x09 , projectConfigKeepGoing = x10 , projectConfigOfflineMode = x11 , projectConfigKeepTempFiles = x12 , projectConfigHttpTransport = x13 , projectConfigIgnoreExpiry = x14 , projectConfigCacheDir = x15 , projectConfigLogsDir = x16 } = [ ProjectConfigBuildOnly { projectConfigVerbosity = x00' , projectConfigDryRun = x01' , projectConfigOnlyDeps = x02' , projectConfigSummaryFile = x03' , projectConfigLogFile = x04' , projectConfigBuildReports = x05' , projectConfigReportPlanningFailure = x06' , projectConfigSymlinkBinDir = x07' , projectConfigOneShot = x08' , projectConfigNumJobs = postShrink_NumJobs x09' , projectConfigKeepGoing = x10' , projectConfigOfflineMode = x11' , projectConfigKeepTempFiles = x12' , projectConfigHttpTransport = x13 , projectConfigIgnoreExpiry = x14' , projectConfigCacheDir = x15 , projectConfigLogsDir = x16 } | ((x00', x01', x02', x03', x04'), (x05', x06', x07', x08', x09'), (x10', x11', x12', x14')) <- shrink ((x00, x01, x02, x03, x04), (x05, x06, x07, x08, preShrink_NumJobs x09), (x10, x11, x12, x14)) ] where preShrink_NumJobs = fmap (fmap Positive) postShrink_NumJobs = fmap (fmap getPositive) instance Arbitrary ProjectConfigShared where arbitrary = ProjectConfigShared <$> arbitraryFlag arbitraryShortToken <*> arbitraryFlag arbitraryShortToken <*> arbitrary <*> arbitraryFlag arbitraryShortToken <*> arbitraryFlag arbitraryShortToken <*> arbitrary <*> arbitrary <*> (toNubList <$> listOf arbitraryShortToken) <*> arbitrary <*> arbitraryConstraints <*> shortListOf 2 arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary where arbitraryConstraints :: Gen [(UserConstraint, ConstraintSource)] arbitraryConstraints = fmap (\uc -> (uc, projectConfigConstraintSource)) <$> arbitrary shrink ProjectConfigShared { projectConfigDistDir = x00 , projectConfigProjectFile = x01 , projectConfigHcFlavor = x02 , projectConfigHcPath = x03 , projectConfigHcPkg = x04 , projectConfigHaddockIndex = x05 , projectConfigRemoteRepos = x06 , projectConfigLocalRepos = x07 , projectConfigIndexState = x08 , projectConfigConstraints = x09 , projectConfigPreferences = x10 , projectConfigCabalVersion = x11 , projectConfigSolver = x12 , projectConfigAllowOlder = x13 , projectConfigAllowNewer = x14 , projectConfigMaxBackjumps = x15 , projectConfigReorderGoals = x16 , projectConfigCountConflicts = x17 , projectConfigStrongFlags = x18 , projectConfigAllowBootLibInstalls = x19 , projectConfigPerComponent = x20 , projectConfigIndependentGoals = x21 } = [ ProjectConfigShared { projectConfigDistDir = x00' , projectConfigProjectFile = x01' , projectConfigHcFlavor = x02' , projectConfigHcPath = fmap getNonEmpty x03' , projectConfigHcPkg = fmap getNonEmpty x04' , projectConfigHaddockIndex = x05' , projectConfigRemoteRepos = x06' , projectConfigLocalRepos = x07' , projectConfigIndexState = x08' , projectConfigConstraints = postShrink_Constraints x09' , projectConfigPreferences = x10' , projectConfigCabalVersion = x11' , projectConfigSolver = x12' , projectConfigAllowOlder = x13' , projectConfigAllowNewer = x14' , projectConfigMaxBackjumps = x15' , projectConfigReorderGoals = x16' , projectConfigCountConflicts = x17' , projectConfigStrongFlags = x18' , projectConfigAllowBootLibInstalls = x19' , projectConfigPerComponent = x20' , projectConfigIndependentGoals = x21' } | ((x00', x01', x02', x03', x04'), (x05', x06', x07', x08', x09'), (x10', x11', x12', x13', x14'), (x15', x16', x17', x18', x19'), x20', x21') <- shrink ((x00, x01, x02, fmap NonEmpty x03, fmap NonEmpty x04), (x05, x06, x07, x08, preShrink_Constraints x09), (x10, x11, x12, x13, x14), (x15, x16, x17, x18, x19), x20, x21) ] where preShrink_Constraints = map fst postShrink_Constraints = map (\uc -> (uc, projectConfigConstraintSource)) projectConfigConstraintSource :: ConstraintSource projectConfigConstraintSource = ConstraintSourceProjectConfig "TODO" instance Arbitrary ProjectConfigProvenance where arbitrary = elements [Implicit, Explicit "cabal.project"] instance Arbitrary PackageConfig where arbitrary = PackageConfig <$> (MapLast . Map.fromList <$> shortListOf 10 ((,) <$> arbitraryProgramName <*> arbitraryShortToken)) <*> (MapMappend . Map.fromList <$> shortListOf 10 ((,) <$> arbitraryProgramName <*> listOf arbitraryShortToken)) <*> (toNubList <$> listOf arbitraryShortToken) <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> shortListOf 5 arbitraryShortToken <*> arbitrary <*> arbitrary <*> arbitrary <*> shortListOf 5 arbitraryShortToken <*> shortListOf 5 arbitraryShortToken <*> shortListOf 5 arbitraryShortToken <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitraryFlag arbitraryShortToken <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitraryFlag arbitraryShortToken <*> arbitrary <*> arbitraryFlag arbitraryShortToken <*> arbitrary <*> arbitrary where arbitraryProgramName :: Gen String arbitraryProgramName = elements [ programName prog | (prog, _) <- knownPrograms (defaultProgramDb) ] shrink PackageConfig { packageConfigProgramPaths = x00 , packageConfigProgramArgs = x01 , packageConfigProgramPathExtra = x02 , packageConfigFlagAssignment = x03 , packageConfigVanillaLib = x04 , packageConfigSharedLib = x05 , packageConfigDynExe = x06 , packageConfigProf = x07 , packageConfigProfLib = x08 , packageConfigProfExe = x09 , packageConfigProfDetail = x10 , packageConfigProfLibDetail = x11 , packageConfigConfigureArgs = x12 , packageConfigOptimization = x13 , packageConfigProgPrefix = x14 , packageConfigProgSuffix = x15 , packageConfigExtraLibDirs = x16 , packageConfigExtraFrameworkDirs = x17 , packageConfigExtraIncludeDirs = x18 , packageConfigGHCiLib = x19 , packageConfigSplitObjs = x20 , packageConfigStripExes = x21 , packageConfigStripLibs = x22 , packageConfigTests = x23 , packageConfigBenchmarks = x24 , packageConfigCoverage = x25 , packageConfigRelocatable = x26 , packageConfigDebugInfo = x27 , packageConfigRunTests = x28 , packageConfigDocumentation = x29 , packageConfigHaddockHoogle = x30 , packageConfigHaddockHtml = x31 , packageConfigHaddockHtmlLocation = x32 , packageConfigHaddockForeignLibs = x33 , packageConfigHaddockExecutables = x33_1 , packageConfigHaddockTestSuites = x34 , packageConfigHaddockBenchmarks = x35 , packageConfigHaddockInternal = x36 , packageConfigHaddockCss = x37 , packageConfigHaddockHscolour = x38 , packageConfigHaddockHscolourCss = x39 , packageConfigHaddockContents = x40 , packageConfigHaddockForHackage = x41 } = [ PackageConfig { packageConfigProgramPaths = postShrink_Paths x00' , packageConfigProgramArgs = postShrink_Args x01' , packageConfigProgramPathExtra = x02' , packageConfigFlagAssignment = x03' , packageConfigVanillaLib = x04' , packageConfigSharedLib = x05' , packageConfigDynExe = x06' , packageConfigProf = x07' , packageConfigProfLib = x08' , packageConfigProfExe = x09' , packageConfigProfDetail = x10' , packageConfigProfLibDetail = x11' , packageConfigConfigureArgs = map getNonEmpty x12' , packageConfigOptimization = x13' , packageConfigProgPrefix = x14' , packageConfigProgSuffix = x15' , packageConfigExtraLibDirs = map getNonEmpty x16' , packageConfigExtraFrameworkDirs = map getNonEmpty x17' , packageConfigExtraIncludeDirs = map getNonEmpty x18' , packageConfigGHCiLib = x19' , packageConfigSplitObjs = x20' , packageConfigStripExes = x21' , packageConfigStripLibs = x22' , packageConfigTests = x23' , packageConfigBenchmarks = x24' , packageConfigCoverage = x25' , packageConfigRelocatable = x26' , packageConfigDebugInfo = x27' , packageConfigRunTests = x28' , packageConfigDocumentation = x29' , packageConfigHaddockHoogle = x30' , packageConfigHaddockHtml = x31' , packageConfigHaddockHtmlLocation = x32' , packageConfigHaddockForeignLibs = x33' , packageConfigHaddockExecutables = x33_1' , packageConfigHaddockTestSuites = x34' , packageConfigHaddockBenchmarks = x35' , packageConfigHaddockInternal = x36' , packageConfigHaddockCss = fmap getNonEmpty x37' , packageConfigHaddockHscolour = x38' , packageConfigHaddockHscolourCss = fmap getNonEmpty x39' , packageConfigHaddockContents = x40' , packageConfigHaddockForHackage = x41' } | (((x00', x01', x02', x03', x04'), (x05', x06', x07', x08', x09'), (x10', x11', x12', x13', x14'), (x15', x16', x17', x18', x19')), ((x20', x21', x22', x23', x24'), (x25', x26', x27', x28', x29'), (x30', x31', x32', (x33', x33_1'), x34'), (x35', x36', x37', x38', x39'), (x40', x41'))) <- shrink (((preShrink_Paths x00, preShrink_Args x01, x02, x03, x04), (x05, x06, x07, x08, x09), (x10, x11, map NonEmpty x12, x13, x14), (x15, map NonEmpty x16, map NonEmpty x17, map NonEmpty x18, x19)), ((x20, x21, x22, x23, x24), (x25, x26, x27, x28, x29), (x30, x31, x32, (x33, x33_1), x34), (x35, x36, fmap NonEmpty x37, x38, fmap NonEmpty x39), (x40, x41))) ] where preShrink_Paths = Map.map NonEmpty . Map.mapKeys NoShrink . getMapLast postShrink_Paths = MapLast . Map.map getNonEmpty . Map.mapKeys getNoShrink preShrink_Args = Map.map (NonEmpty . map NonEmpty) . Map.mapKeys NoShrink . getMapMappend postShrink_Args = MapMappend . Map.map (map getNonEmpty . getNonEmpty) . Map.mapKeys getNoShrink instance Arbitrary HaddockTarget where arbitrary = elements [ForHackage, ForDevelopment] instance Arbitrary SourceRepo where arbitrary = (SourceRepo RepoThis <$> arbitrary <*> (fmap getShortToken <$> arbitrary) <*> (fmap getShortToken <$> arbitrary) <*> (fmap getShortToken <$> arbitrary) <*> (fmap getShortToken <$> arbitrary) <*> (fmap getShortToken <$> arbitrary)) `suchThat` (/= emptySourceRepo RepoThis) shrink (SourceRepo _ x1 x2 x3 x4 x5 x6) = [ repo | ((x1', x2', x3'), (x4', x5', x6')) <- shrink ((x1, fmap ShortToken x2, fmap ShortToken x3), (fmap ShortToken x4, fmap ShortToken x5, fmap ShortToken x6)) , let repo = SourceRepo RepoThis x1' (fmap getShortToken x2') (fmap getShortToken x3') (fmap getShortToken x4') (fmap getShortToken x5') (fmap getShortToken x6') , repo /= emptySourceRepo RepoThis ] instance Arbitrary RepoType where arbitrary = elements knownRepoTypes instance Arbitrary ReportLevel where arbitrary = elements [NoReports .. DetailedReports] instance Arbitrary CompilerFlavor where arbitrary = elements knownCompilerFlavors where --TODO: [code cleanup] export knownCompilerFlavors from D.Compiler -- it's already defined there, just need it exported. knownCompilerFlavors = [GHC, GHCJS, NHC, YHC, Hugs, HBC, Helium, JHC, LHC, UHC] instance Arbitrary a => Arbitrary (InstallDirs a) where arbitrary = InstallDirs <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- 4 <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- 8 <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- 12 <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary -- 16 instance Arbitrary PackageDB where arbitrary = oneof [ pure GlobalPackageDB , pure UserPackageDB , SpecificPackageDB . getShortToken <$> arbitrary ] instance Arbitrary RemoteRepo where arbitrary = RemoteRepo <$> arbitraryShortToken `suchThat` (not . (":" `isPrefixOf`)) <*> arbitrary -- URI <*> arbitrary <*> listOf arbitraryRootKey <*> (fmap getNonNegative arbitrary) <*> pure False where arbitraryRootKey = shortListOf1 5 (oneof [ choose ('0', '9') , choose ('a', 'f') ]) instance Arbitrary UserConstraintScope where arbitrary = oneof [ UserQualified <$> arbitrary <*> arbitrary , UserAnySetupQualifier <$> arbitrary , UserAnyQualifier <$> arbitrary ] instance Arbitrary UserQualifier where arbitrary = oneof [ pure UserQualToplevel , UserQualSetup <$> arbitrary -- -- TODO: Re-enable UserQualExe tests once we decide on a syntax. -- , UserQualExe <$> arbitrary <*> arbitrary ] instance Arbitrary UserConstraint where arbitrary = UserConstraint <$> arbitrary <*> arbitrary instance Arbitrary PackageProperty where arbitrary = oneof [ PackagePropertyVersion <$> arbitrary , pure PackagePropertyInstalled , pure PackagePropertySource , PackagePropertyFlags <$> shortListOf1 3 arbitrary , PackagePropertyStanzas . (\x->[x]) <$> arbitrary ] instance Arbitrary OptionalStanza where arbitrary = elements [minBound..maxBound] instance Arbitrary FlagName where arbitrary = mkFlagName <$> flagident where flagident = lowercase <$> shortListOf1 5 (elements flagChars) `suchThat` (("-" /=) . take 1) flagChars = "-_" ++ ['a'..'z'] instance Arbitrary PreSolver where arbitrary = elements [minBound..maxBound] instance Arbitrary ReorderGoals where arbitrary = ReorderGoals <$> arbitrary instance Arbitrary CountConflicts where arbitrary = CountConflicts <$> arbitrary instance Arbitrary IndependentGoals where arbitrary = IndependentGoals <$> arbitrary instance Arbitrary StrongFlags where arbitrary = StrongFlags <$> arbitrary instance Arbitrary AllowBootLibInstalls where arbitrary = AllowBootLibInstalls <$> arbitrary instance Arbitrary AllowNewer where arbitrary = AllowNewer <$> arbitrary instance Arbitrary AllowOlder where arbitrary = AllowOlder <$> arbitrary instance Arbitrary RelaxDeps where arbitrary = oneof [ pure RelaxDepsNone , RelaxDepsSome <$> shortListOf1 3 arbitrary , pure RelaxDepsAll ] instance Arbitrary RelaxedDep where arbitrary = oneof [ RelaxedDep <$> arbitrary , RelaxedDepScoped <$> arbitrary <*> arbitrary ] instance Arbitrary ProfDetailLevel where arbitrary = elements [ d | (_,_,d) <- knownProfDetailLevels ] instance Arbitrary OptimisationLevel where arbitrary = elements [minBound..maxBound] instance Arbitrary DebugInfoLevel where arbitrary = elements [minBound..maxBound] instance Arbitrary URI where arbitrary = URI <$> elements ["file:", "http:", "https:"] <*> (Just <$> arbitrary) <*> (('/':) <$> arbitraryURIToken) <*> (('?':) <$> arbitraryURIToken) <*> pure "" instance Arbitrary URIAuth where arbitrary = URIAuth <$> pure "" -- no password as this does not roundtrip <*> arbitraryURIToken <*> arbitraryURIPort arbitraryURIToken :: Gen String arbitraryURIToken = shortListOf1 6 (elements (filter isUnreserved ['\0'..'\255'])) arbitraryURIPort :: Gen String arbitraryURIPort = oneof [ pure "", (':':) <$> shortListOf1 4 (choose ('0','9')) ]
mydaum/cabal
cabal-install/tests/UnitTests/Distribution/Client/ProjectConfig.hs
bsd-3-clause
33,236
0
55
11,914
5,896
3,368
2,528
661
2
module Rules.General where import Derivation import Goal import Rules.Utils import Tactic import Term -- H >> C -- H >> t = t in C -- Uses: WITNESS generalWITNESS :: Term -> PrlTactic generalWITNESS w (Goal ctx t) = return $ Result { resultGoals = [ Goal ctx (Eq w w t) ] , resultEvidence = \d -> case d of [d] -> WITNESS w d _ -> error "General.WITNESS: Invalid evidence!" } -- H >> C -- H(i) = C -- Uses: VAR generalHYP :: Target -> PrlTactic generalHYP target (Goal ctx t) = case nth (irrelevant t) target ctx of Just t' | t == t' -> return $ Result { resultGoals = [] , resultEvidence = \d -> case d of [] -> VAR target _ -> error "General.HYP: Invalid evidence!" } _ -> fail "General.HYP does not apply." -- H >> C -- H(i) = C -- Uses: VAR_EQ generalHYPEQ :: PrlTactic generalHYPEQ (Goal ctx t) = case t of Eq (Var i) (Var j) a | i == j && nth (irrelevant t) i ctx == Just a -> return $ Result { resultGoals = [] , resultEvidence = \d -> case d of [] -> VAR_EQ _ -> error "General.HYPEQ: Invalid evidence!" } _ -> fail "General.HYPEQ does not apply." {- -- TODO Customer operators -- H >> C -- opid is a lemma proving L -- H, L >> C -- Uses: CUT generalCUT :: RefinerConfig -> Guid -> PrlTactic -- There isn't a nice rule for this really. This rule -- finds every occurence of the Guid given and expands -- it according to what the refiner config says is its -- extract. generalUNFOLD :: RefinerConfig -> Guid -> PrlTactic -}
thsutton/cha
lib/Rules/General.hs
bsd-3-clause
1,769
0
16
627
388
204
184
34
3
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude, MagicHash, UnboxedTuples #-} ----------------------------------------------------------------------------- -- | -- Module : Data.IORef -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- Mutable references in the IO monad. -- ----------------------------------------------------------------------------- module Data.IORef ( -- * IORefs IORef, -- abstract, instance of: Eq, Typeable newIORef, readIORef, writeIORef, modifyIORef, modifyIORef', atomicModifyIORef, atomicModifyIORef', atomicWriteIORef, #if !defined(__PARALLEL_HASKELL__) mkWeakIORef, #endif -- ** Memory Model -- $memmodel ) where import GHC.Base import GHC.STRef import GHC.IORef hiding (atomicModifyIORef) import qualified GHC.IORef #if !defined(__PARALLEL_HASKELL__) import GHC.Weak #endif #if !defined(__PARALLEL_HASKELL__) -- |Make a 'Weak' pointer to an 'IORef', using the second argument as a finalizer -- to run when 'IORef' is garbage-collected mkWeakIORef :: IORef a -> IO () -> IO (Weak (IORef a)) mkWeakIORef r@(IORef (STRef r#)) f = IO $ \s -> case mkWeak# r# r f s of (# s1, w #) -> (# s1, Weak w #) #endif -- |Mutate the contents of an 'IORef'. -- -- Be warned that 'modifyIORef' does not apply the function strictly. This -- means if the program calls 'modifyIORef' many times, but seldomly uses the -- value, thunks will pile up in memory resulting in a space leak. This is a -- common mistake made when using an IORef as a counter. For example, the -- following will likely produce a stack overflow: -- -- >ref <- newIORef 0 -- >replicateM_ 1000000 $ modifyIORef ref (+1) -- >readIORef ref >>= print -- -- To avoid this problem, use 'modifyIORef'' instead. modifyIORef :: IORef a -> (a -> a) -> IO () modifyIORef ref f = readIORef ref >>= writeIORef ref . f -- |Strict version of 'modifyIORef' -- -- /Since: 4.6.0.0/ modifyIORef' :: IORef a -> (a -> a) -> IO () modifyIORef' ref f = do x <- readIORef ref let x' = f x x' `seq` writeIORef ref x' -- |Atomically modifies the contents of an 'IORef'. -- -- This function is useful for using 'IORef' in a safe way in a multithreaded -- program. If you only have one 'IORef', then using 'atomicModifyIORef' to -- access and modify it will prevent race conditions. -- -- Extending the atomicity to multiple 'IORef's is problematic, so it -- is recommended that if you need to do anything more complicated -- then using 'Control.Concurrent.MVar.MVar' instead is a good idea. -- -- 'atomicModifyIORef' does not apply the function strictly. This is important -- to know even if all you are doing is replacing the value. For example, this -- will leak memory: -- -- >ref <- newIORef '1' -- >forever $ atomicModifyIORef ref (\_ -> ('2', ())) -- -- Use 'atomicModifyIORef'' or 'atomicWriteIORef' to avoid this problem. -- atomicModifyIORef :: IORef a -> (a -> (a,b)) -> IO b atomicModifyIORef = GHC.IORef.atomicModifyIORef -- | Strict version of 'atomicModifyIORef'. This forces both the value stored -- in the 'IORef' as well as the value returned. -- -- /Since: 4.6.0.0/ atomicModifyIORef' :: IORef a -> (a -> (a,b)) -> IO b atomicModifyIORef' ref f = do b <- atomicModifyIORef ref $ \a -> case f a of v@(a',_) -> a' `seq` v b `seq` return b -- | Variant of 'writeIORef' with the \"barrier to reordering\" property that -- 'atomicModifyIORef' has. -- -- /Since: 4.6.0.0/ atomicWriteIORef :: IORef a -> a -> IO () atomicWriteIORef ref a = do x <- atomicModifyIORef ref (\_ -> (a, ())) x `seq` return () {- $memmodel In a concurrent program, 'IORef' operations may appear out-of-order to another thread, depending on the memory model of the underlying processor architecture. For example, on x86, loads can move ahead of stores, so in the following example: > maybePrint :: IORef Bool -> IORef Bool -> IO () > maybePrint myRef yourRef = do > writeIORef myRef True > yourVal <- readIORef yourRef > unless yourVal $ putStrLn "critical section" > > main :: IO () > main = do > r1 <- newIORef False > r2 <- newIORef False > forkIO $ maybePrint r1 r2 > forkIO $ maybePrint r2 r1 > threadDelay 1000000 it is possible that the string @"critical section"@ is printed twice, even though there is no interleaving of the operations of the two threads that allows that outcome. The memory model of x86 allows 'readIORef' to happen before the earlier 'writeIORef'. The implementation is required to ensure that reordering of memory operations cannot cause type-correct code to go wrong. In particular, when inspecting the value read from an 'IORef', the memory writes that created that value must have occurred from the point of view of the current thread. 'atomicModifyIORef' acts as a barrier to reordering. Multiple 'atomicModifyIORef' operations occur in strict program order. An 'atomicModifyIORef' is never observed to take place ahead of any earlier (in program order) 'IORef' operations, or after any later 'IORef' operations. -}
jstolarek/ghc
libraries/base/Data/IORef.hs
bsd-3-clause
5,374
0
14
1,126
584
340
244
41
1
{-# LANGUAGE CPP #-} module Data.STRef.Logic ( STRef , newSTRef , readSTRef , writeSTRef , modifySTRef , modifySTRef' ) where #ifdef MODULE_Control_Monad_ST_Safe import Control.Monad.ST.Safe #else import Control.Monad.ST #endif import Control.Monad.ST.Logic import Control.Monad.ST.Logic.Internal type STRef s = Ref s (ST s) newSTRef :: a -> LogicST s (STRef s a) newSTRef = newRef {-# INLINE newSTRef #-} readSTRef :: STRef s a -> LogicST s a readSTRef = readRef {-# INLINE readSTRef #-} writeSTRef :: STRef s a -> a -> LogicST s () writeSTRef = writeRef {-# INLINE writeSTRef #-} modifySTRef :: STRef s a -> (a -> a) -> LogicST s () modifySTRef = modifyRef {-# INLINE modifySTRef #-} modifySTRef' :: STRef s a -> (a -> a) -> LogicST s () modifySTRef' = modifyRef' {-# INLINE modifySTRef' #-}
sonyandy/logicst
src/Data/STRef/Logic.hs
bsd-3-clause
850
0
8
186
231
132
99
27
1
{-#LANGUAGE DeriveDataTypeable #-} module Distribution.HBrew.Utils ( split , showText, readText , createAndWaitProcess , createDirectoryRecursive , getContentsRecursive , readConfFileIO ) where import Control.Monad import Control.Exception(Exception, throwIO) import System.Directory import System.FilePath import System.Exit(ExitCode(..)) import System.IO(Handle) import System.Process (CreateProcess(..), CmdSpec(..), createProcess, waitForProcess) import Distribution.Text(Text, disp, simpleParse) import Distribution.InstalledPackageInfo import Text.PrettyPrint(render) import Data.Typeable(Typeable) import Data.Word import Data.Maybe split :: (a -> Bool) -> [a] -> [[a]] split p str = case span p str of (a,[]) -> [a] (a, b) -> a : split p (tail b) readText :: Text a => String -> a readText = fromMaybe (error "no parse") . simpleParse showText :: Text a => a -> String showText = render. disp data ExitFailureException = FailureShellCommand String Int | FailureRawCommand String [String] Int deriving (Typeable) instance Show ExitFailureException where show (FailureShellCommand cmd code) = cmd ++ ": ExitFailure " ++ show code show (FailureRawCommand cmd args code) = cmd ++ ' ': foldr (\i b -> i ++ ' ': b) "" args ++ ": ExitFailure " ++ show code instance Exception ExitFailureException type Handles = (Maybe Handle, Maybe Handle, Maybe Handle) createAndWaitProcess :: (Handles -> IO a) -> CreateProcess -> IO a createAndWaitProcess f cp = do (i,o,e,h) <- createProcess cp ret <- f (i,o,e) waitForProcess h >>= \code -> case code of ExitSuccess -> return ret ExitFailure ec -> throwIO $ exception ec where exception = case cmdspec cp of ShellCommand cmd -> FailureShellCommand cmd RawCommand cmd args -> FailureRawCommand cmd args createDirectoryRecursive :: FilePath -> [FilePath] -> IO FilePath createDirectoryRecursive base [] = return base createDirectoryRecursive base (p:ps) = do let d = base </> p e <- doesDirectoryExist d unless e $ createDirectory d createDirectoryRecursive d ps getContentsRecursive :: Word -> FilePath -> IO [FilePath] getContentsRecursive ilim dir = sub ilim "" where sub 0 _ = return [] sub lim rel = do cont <- filter (`notElem` [".", ".."]) `fmap` getDirectoryContents (dir </> rel) files <- filterM (doesFileExist . (dir </>)) $ map (rel </>) cont dirs <- filterM (doesDirectoryExist. (dir </>)) $ map (rel </>) cont subc <- mapM (sub (pred lim)) dirs return $ files ++ concat subc newtype PErrorException = PErrorException PError deriving (Show, Typeable) instance Exception PErrorException readConfFileIO :: FilePath -> IO InstalledPackageInfo readConfFileIO path = parseInstalledPackageInfo `fmap` readFile path >>= \info -> case info of ParseFailed perr -> throwIO $ PErrorException perr ParseOk _ i -> return i
philopon/hbrew
src/Distribution/HBrew/Utils.hs
bsd-3-clause
3,038
0
14
674
1,031
540
491
70
3
module ConfigMapperSpec (spec) where import ConfigMapper import ConfigParser (MachineConfig(..), Rules(..), StartConfig(..)) import Data.Either as Either import Machine import Prelude hiding (Right) import Test.Hspec meta0 = Meta { noActionSymbol = '*', anySymbol = '_', emptySymbol = 'e', emptyTape = "" } configForRules rules = MachineConfig { ConfigParser.meta = meta0 , start = StartConfig { ConfigParser.state = "SomeState0", tape = "ABCD[E]FGH" } , rules = rules } automaton = Automaton { Machine.state = "SomeState0" , tapeBefore = "ABCD" , headSymbol = 'E' , tapeAfter = "FGH" } transitions = [ Transition { accept = ("State0", 'A') , actions = [Write 'X', Move Machine.Right] , nextState = "State1" } , Transition { accept = ("State1", 'B'), actions = [Write 'Y'], nextState = "State2" } , Transition { accept = ("State2", 'C') , actions = [Move Machine.Left] , nextState = "State3" } , Transition { accept = ("State3", 'D'), actions = [], nextState = "State4" } ] spec :: Spec spec = describe "Turing machine" $ context "when supplied with a config" $ do context "with empty rule list" $ it "initializes having no transitions" $ fromConfig (configForRules []) `shouldBe` Either.Right (meta0, automaton, []) it "builds intermediate actions for transitions" $ fromConfig (configForRules [ "State0 A X R State1" , "State1 B Y * State2" , "State2 C * L State3" , "State3 D * * State4" ]) `shouldBe` Either.Right (meta0, automaton, transitions)
prSquirrel/turingmachine
test/ConfigMapperSpec.hs
bsd-3-clause
1,836
0
13
615
448
270
178
42
1
import Distribution.Simple import Distribution.Simple.Compiler hiding (Flag) import Distribution.Simple.UserHooks import Distribution.Package import Distribution.PackageDescription ( PackageDescription(..), GenericPackageDescription , updatePackageDescription, hasLibs , HookedBuildInfo, emptyHookedBuildInfo ) import Distribution.PackageDescription.Parse ( readPackageDescription, readHookedBuildInfo ) import Distribution.PackageDescription.Configuration ( flattenPackageDescription ) import Distribution.Simple.Program ( defaultProgramConfiguration, addKnownPrograms, builtinPrograms , restoreProgramConfiguration, reconfigurePrograms ) import Distribution.Simple.PreProcess (knownSuffixHandlers, PPSuffixHandler) import Distribution.Simple.Setup import Distribution.Simple.Command import Distribution.Simple.Build ( build ) import Distribution.Simple.SrcDist ( sdist ) import Distribution.Simple.Register ( register, unregister ) import Distribution.Simple.Configure ( getPersistBuildConfig, maybeGetPersistBuildConfig , writePersistBuildConfig, checkPersistBuildConfigOutdated , configure, checkForeignDeps ) import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) ) import Distribution.Simple.BuildPaths ( srcPref) import Distribution.Simple.Test (test) import Distribution.Simple.Install (install) import Distribution.Simple.Haddock (haddock, hscolour) import Distribution.Simple.Utils (die, notice, info, warn, setupMessage, chattyTry, defaultPackageDesc, defaultHookedPackageDesc, rawSystemExitWithEnv, cabalVersion, topHandler ) import Distribution.System ( OS(..), buildOS ) import Distribution.Verbosity import Language.Haskell.Extension import Distribution.Version import Distribution.License import Distribution.Text ( display ) import System.Process import System.Directory import System.Exit import Control.Monad (when) import Data.List (intersperse, unionBy) main = defaultMainWithHooks simpleUserHooks { preBuild = preHook , postBuild = postHook } alert msg = do putStrLn "" putStrLn "*************************************************************************************" putStrLn "****" putStrLn $ "**** " ++ msg putStrLn "" preHook _ _ = do exists <- doesFileExist "prelude.obj" if exists then removeFile "prelude.obj" else return () system "touch prelude.obj" alert "Building prelude-less compiler" return emptyHookedBuildInfo postHook _ flags pkg_descr localbuildinfo = do --build pkg_descr localbuildinfo flags (allSuffixHandlers hooks) alert "Building prelude" retCode <- rawSystem "dist/build/Forml/forml" ["-no-test", "-no-prelude", "src/forml/prelude.forml"] case retCode of ExitFailure msg -> do alert "FAILED" putStrLn (show msg) ExitSuccess -> do alert "Building compiler" build pkg_descr localbuildinfo flags allSuffixHandlers allSuffixHandlers :: [PPSuffixHandler] allSuffixHandlers = knownSuffixHandlers where overridesPP :: [PPSuffixHandler] -> [PPSuffixHandler] -> [PPSuffixHandler] overridesPP = unionBy (\x y -> fst x == fst y)
texodus/forml
Setup.hs
bsd-3-clause
3,329
0
14
629
670
380
290
78
2
module Util where import Data.Array.Repa hiding ((++)) import qualified Data.Array.Repa as R import Data.Vector.Unboxed.Base updateAS :: (Source r e, Shape sh, Unbox e) => Array r sh e -> Int -> (e -> e) -> Array U sh e updateAS a i f = modifyAS a i $ f e where s = extent a e = a ! (fromIndex s i) modifyAS :: (Source r e, Shape sh, Unbox e) => Array r sh e -> Int -> e -> Array U sh e modifyAS a i v = computeS $ modifyA a i v modifyA :: (Source r e, Shape sh) => Array r sh e -> Int -> e -> Array D sh e modifyA arr i v = R.traverse arr id f where originalShape = extent arr f g sh | toIndex originalShape sh == i = v | otherwise = g sh updateL :: [a] -> Int -> (a -> a) -> [a] updateL ls i f = modifyL ls i (f (ls !! i)) modifyL :: [a] -> Int -> a -> [a] modifyL ls i e = case splitAt i ls of (l1, (_:l2)) -> l1++(e:l2) (l1, []) -> init l1 ++ [e] pickle :: Show a => a -> FilePath -> IO () pickle a f = writeFile f . show $ a unpickle :: Read a => FilePath -> IO a unpickle = fmap read . readFile (=~) :: (Ord a, Fractional a) => a -> a -> Int -> Bool a =~ b = f where f x = a <= (b + (0.1^(x))) && a >= (b - (0.1^(x)))
ayachigin/DeepLearningFromScratch
src/Util.hs
bsd-3-clause
1,275
0
14
421
677
352
325
33
2
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.TE.Corpus ( corpus ) where import Data.String import Prelude import Duckling.Locale import Duckling.Numeral.Types import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale TE Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (NumeralValue 0) [ "సున్న" ] , examples (NumeralValue 1) [ "ఒకటి" ] , examples (NumeralValue 2) [ "రెండు" ] , examples (NumeralValue 3) [ "మూడు" ] , examples (NumeralValue 4) [ "నాలుగు" ] , examples (NumeralValue 5) [ "ఐదు" ] , examples (NumeralValue 6) [ "ఆరు" ] , examples (NumeralValue 7) [ "ఏడు" ] , examples (NumeralValue 8) [ "ఎనిమిది" ] , examples (NumeralValue 9) [ "తొమ్మిది" ] , examples (NumeralValue 10) [ "పది" ] , examples (NumeralValue 11) [ "పదకొండు" ] , examples (NumeralValue 12) [ "పన్నెండు" ] , examples (NumeralValue 13) [ "పదమూడు" ] , examples (NumeralValue 14) [ "పద్నాల్గు" ] , examples (NumeralValue 15) [ "పదిహేను" ] , examples (NumeralValue 16) [ "పదహారు" ] , examples (NumeralValue 17) [ "పదిహేడు" ] , examples (NumeralValue 18) [ "పద్దెనిమిది" ] , examples (NumeralValue 19) [ "పంతొమ్మిది" ] , examples (NumeralValue 20) [ "ఇరవై" ] , examples (NumeralValue 30) [ "ముప్పై" ] , examples (NumeralValue 40) [ "నలబై" ] , examples (NumeralValue 50) [ "యాబై" ] , examples (NumeralValue 60) [ "అరవై" ] , examples (NumeralValue 70) [ "డెబ్బై" ] , examples (NumeralValue 80) [ "ఎనబై" ] , examples (NumeralValue 90) [ "తొంబై" ] , examples (NumeralValue 100) [ "వంద" ] , examples (NumeralValue 1000) [ "వెయ్యి" ] , examples (NumeralValue 100000) [ "లక్ష" ] , examples (NumeralValue 10000000) [ "కోటి" ] ]
facebookincubator/duckling
Duckling/Numeral/TE/Corpus.hs
bsd-3-clause
3,178
0
9
1,211
641
350
291
77
1
module CommandLine.Arguments (parse) where import Control.Applicative (pure, optional, (<$>), (<*>), (<|>)) import Control.Monad.Error (throwError) import Data.Monoid ((<>), mconcat, mempty) import Data.Version (showVersion) import qualified Options.Applicative as Opt import qualified Text.PrettyPrint.ANSI.Leijen as PP import qualified Bump import qualified Diff import qualified Install import qualified Manager import qualified Publish import qualified Paths_elm_package as This import qualified Elm.Compiler as Compiler import qualified Elm.Package.Name as N import qualified Elm.Package.Paths as Path import qualified Elm.Package.Version as V parse :: IO (Manager.Manager ()) parse = Opt.customExecParser preferences parser preferences :: Opt.ParserPrefs preferences = Opt.prefs (mempty <> Opt.showHelpOnError) parser :: Opt.ParserInfo (Manager.Manager ()) parser = Opt.info (Opt.helper <*> commands) infoModifier -- GENERAL HELP infoModifier :: Opt.InfoMod (Manager.Manager ()) infoModifier = mconcat [ Opt.fullDesc , Opt.header top , Opt.progDesc "install and publish elm libraries" , Opt.footerDoc (Just moreHelp) ] where top = "Elm Package Manager " ++ showVersion This.version ++ " (Elm Platform " ++ Compiler.version ++ ")\n" moreHelp = linesToDoc [ "To learn more about a particular command run:" , " elm-package COMMAND --help" ] linesToDoc :: [String] -> PP.Doc linesToDoc lines = PP.vcat (map PP.text lines) -- COMMANDS commands :: Opt.Parser (Manager.Manager ()) commands = Opt.hsubparser commandOptions where version = Opt.flag' (error "temporarily out of order") (Opt.long "version" <> Opt.short 'v' <> Opt.hidden) commandOptions = mconcat [ Opt.command "install" installInfo , Opt.command "publish" publishInfo , Opt.command "bump" bumpInfo , Opt.command "diff" diffInfo ] -- BUMP bumpInfo :: Opt.ParserInfo (Manager.Manager ()) bumpInfo = Opt.info (pure Bump.bump) $ mconcat [ Opt.fullDesc , Opt.progDesc "Bump version numbers based on API changes" ] -- DIFF diffInfo :: Opt.ParserInfo (Manager.Manager ()) diffInfo = Opt.info (Diff.diff <$> range) $ mconcat [ Opt.fullDesc , Opt.progDesc "Get differences between two APIs" ] where range = (Diff.Between <$> package <*> version <*> version) <|> (Diff.Since <$> version) <|> (pure Diff.LatestVsActual) -- PUBLISH publishInfo :: Opt.ParserInfo (Manager.Manager ()) publishInfo = Opt.info (pure Publish.publish) $ mconcat [ Opt.fullDesc , Opt.progDesc "Publish your package to the central catalog" ] -- INSTALL installInfo :: Opt.ParserInfo (Manager.Manager ()) installInfo = Opt.info args infoModifier where args = installWith <$> optional package <*> optional version <*> yes installWith maybeName maybeVersion autoYes = case (maybeName, maybeVersion) of (Nothing, Nothing) -> Install.install autoYes Install.Everything (Just name, Nothing) -> Install.install autoYes (Install.Latest name) (Just name, Just version) -> Install.install autoYes (Install.Exactly name version) (Nothing, Just version) -> throwError $ "You specified a version number, but not a package!\nVersion " ++ V.toString version ++ " of what?" infoModifier = mconcat [ Opt.fullDesc , Opt.progDesc "Install packages to use locally" , Opt.footerDoc (Just examples) ] examples = linesToDoc [ "Examples:" , " elm-package install # everything needed by " ++ Path.description , " elm-package install evancz/elm-html # any version" , " elm-package install evancz/elm-html 1.2.0 # specific version" ] -- ARGUMENT PARSERS package :: Opt.Parser N.Name package = Opt.argument N.fromString $ mconcat [ Opt.metavar "PACKAGE" , Opt.help "A specific package name (e.g. evancz/automaton)" ] version :: Opt.Parser V.Version version = Opt.argument V.fromString $ mconcat [ Opt.metavar "VERSION" , Opt.help "Specific version of a package (e.g. 1.2.0)" ] yes :: Opt.Parser Bool yes = Opt.switch $ mconcat [ Opt.long "yes" , Opt.short 'y' , Opt.help "Reply 'yes' to all automated prompts." ]
rtfeldman/elm-package
src/CommandLine/Arguments.hs
bsd-3-clause
4,697
0
13
1,310
1,150
620
530
124
4
{-# LANGUAGE OverloadedStrings #-} module SlackBot.Parser where import Control.Applicative import qualified Data.Text as T import LambdaHive.Parser.Move import SlackBot.Types import Text.Trifecta import Web.Slack slackBotCommandParser :: Parser SlackBotCommand slackBotCommandParser = userIdParser *> (string ":" <* optional (char ' ') *> choice [try endGameParser, try makeMoveParser, try showGameParser, newGameParser]) where newGameParser = string "start " *> (try aiGameParser <|> humanGameParser) humanGameParser = StartHumanGame <$> playerParser makeMoveParser = MakeMove <$> moveParser aiGameParser = StartAIGame <$> playerParser <*> (char ' ' *> userIdParser) endGameParser = EndGame <$ string "end" showGameParser = ShowGame <$ string "show" userIdParser :: Parser UserId userIdParser = Id . T.pack <$> between (string "<@") (char '>') p where p = head <$> sepBy1 (some alphaNum) (char '|')
z0isch/lambda-hive
src/SlackBot/Parser.hs
bsd-3-clause
1,009
0
11
225
264
140
124
22
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, MagicHash, StandaloneDeriving, BangPatterns #-} {-# LANGUAGE ConstraintKinds, DataKinds, TypeFamilies, UndecidableInstances, MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, PolyKinds, TypeOperators, NoImplicitPrelude, UnliftedFFITypes #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- XXX -fno-warn-unused-imports needed for the GHC.Tuple import below. Sigh. {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Classes -- Copyright : (c) The University of Glasgow, 1992-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- Basic classes. -- ----------------------------------------------------------------------------- module GHC.Classes where -- GHC.Magic is used in some derived instances import GHC.Magic () import GHC.Prim import GHC.Tuple import GHC.Types infix 4 ==, /=, <, <=, >=, > infixr 3 && infixr 2 || default () -- Double isn't available yet -- | The 'Eq' class defines equality ('==') and inequality ('/='). -- All the basic datatypes exported by the "Prelude" are instances of 'Eq', -- and 'Eq' may be derived for any datatype whose constituents are also -- instances of 'Eq'. -- -- Minimal complete definition: either '==' or '/='. -- class Eq a where (==), (/=) :: a -> a -> Bool {-# INLINE (/=) #-} {-# INLINE (==) #-} x /= y = not (x == y) x == y = not (x /= y) {-# MINIMAL (==) | (/=) #-} deriving instance Eq () deriving instance (Eq a, Eq b) => Eq (a, b) deriving instance (Eq a, Eq b, Eq c) => Eq (a, b, c) deriving instance (Eq a, Eq b, Eq c, Eq d) => Eq (a, b, c, d) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e) => Eq (a, b, c, d, e) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => Eq (a, b, c, d, e, f) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g) => Eq (a, b, c, d, e, f, g) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h) => Eq (a, b, c, d, e, f, g, h) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i) => Eq (a, b, c, d, e, f, g, h, i) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j) => Eq (a, b, c, d, e, f, g, h, i, j) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k) => Eq (a, b, c, d, e, f, g, h, i, j, k) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l) => Eq (a, b, c, d, e, f, g, h, i, j, k, l) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n) deriving instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n, Eq o) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) instance (Eq a) => Eq [a] where {-# SPECIALISE instance Eq [[Char]] #-} {-# SPECIALISE instance Eq [Char] #-} {-# SPECIALISE instance Eq [Int] #-} [] == [] = True (x:xs) == (y:ys) = x == y && xs == ys _xs == _ys = False deriving instance Eq Bool deriving instance Eq Ordering deriving instance Eq Word instance Eq Char where (C# c1) == (C# c2) = isTrue# (c1 `eqChar#` c2) (C# c1) /= (C# c2) = isTrue# (c1 `neChar#` c2) instance Eq Float where (F# x) == (F# y) = isTrue# (x `eqFloat#` y) instance Eq Double where (D# x) == (D# y) = isTrue# (x ==## y) instance Eq Int where (==) = eqInt (/=) = neInt {-# INLINE eqInt #-} {-# INLINE neInt #-} eqInt, neInt :: Int -> Int -> Bool (I# x) `eqInt` (I# y) = isTrue# (x ==# y) (I# x) `neInt` (I# y) = isTrue# (x /=# y) -- | The 'Ord' class is used for totally ordered datatypes. -- -- Instances of 'Ord' can be derived for any user-defined -- datatype whose constituent types are in 'Ord'. The declared order -- of the constructors in the data declaration determines the ordering -- in derived 'Ord' instances. The 'Ordering' datatype allows a single -- comparison to determine the precise ordering of two objects. -- -- Minimal complete definition: either 'compare' or '<='. -- Using 'compare' can be more efficient for complex types. -- class (Eq a) => Ord a where compare :: a -> a -> Ordering (<), (<=), (>), (>=) :: a -> a -> Bool max, min :: a -> a -> a compare x y = if x == y then EQ -- NB: must be '<=' not '<' to validate the -- above claim about the minimal things that -- can be defined for an instance of Ord: else if x <= y then LT else GT x < y = case compare x y of { LT -> True; _ -> False } x <= y = case compare x y of { GT -> False; _ -> True } x > y = case compare x y of { GT -> True; _ -> False } x >= y = case compare x y of { LT -> False; _ -> True } -- These two default methods use '<=' rather than 'compare' -- because the latter is often more expensive max x y = if x <= y then y else x min x y = if x <= y then x else y {-# MINIMAL compare | (<=) #-} deriving instance Ord () deriving instance (Ord a, Ord b) => Ord (a, b) deriving instance (Ord a, Ord b, Ord c) => Ord (a, b, c) deriving instance (Ord a, Ord b, Ord c, Ord d) => Ord (a, b, c, d) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e) => Ord (a, b, c, d, e) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f) => Ord (a, b, c, d, e, f) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g) => Ord (a, b, c, d, e, f, g) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h) => Ord (a, b, c, d, e, f, g, h) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i) => Ord (a, b, c, d, e, f, g, h, i) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j) => Ord (a, b, c, d, e, f, g, h, i, j) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k) => Ord (a, b, c, d, e, f, g, h, i, j, k) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l) => Ord (a, b, c, d, e, f, g, h, i, j, k, l) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m, Ord n) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m, n) deriving instance (Ord a, Ord b, Ord c, Ord d, Ord e, Ord f, Ord g, Ord h, Ord i, Ord j, Ord k, Ord l, Ord m, Ord n, Ord o) => Ord (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) instance (Ord a) => Ord [a] where {-# SPECIALISE instance Ord [[Char]] #-} {-# SPECIALISE instance Ord [Char] #-} {-# SPECIALISE instance Ord [Int] #-} compare [] [] = EQ compare [] (_:_) = LT compare (_:_) [] = GT compare (x:xs) (y:ys) = case compare x y of EQ -> compare xs ys other -> other deriving instance Ord Bool deriving instance Ord Ordering deriving instance Ord Word -- We don't use deriving for Ord Char, because for Ord the derived -- instance defines only compare, which takes two primops. Then -- '>' uses compare, and therefore takes two primops instead of one. instance Ord Char where (C# c1) > (C# c2) = isTrue# (c1 `gtChar#` c2) (C# c1) >= (C# c2) = isTrue# (c1 `geChar#` c2) (C# c1) <= (C# c2) = isTrue# (c1 `leChar#` c2) (C# c1) < (C# c2) = isTrue# (c1 `ltChar#` c2) instance Ord Float where (F# x) `compare` (F# y) = if isTrue# (x `ltFloat#` y) then LT else if isTrue# (x `eqFloat#` y) then EQ else GT (F# x) < (F# y) = isTrue# (x `ltFloat#` y) (F# x) <= (F# y) = isTrue# (x `leFloat#` y) (F# x) >= (F# y) = isTrue# (x `geFloat#` y) (F# x) > (F# y) = isTrue# (x `gtFloat#` y) instance Ord Double where (D# x) `compare` (D# y) = if isTrue# (x <## y) then LT else if isTrue# (x ==## y) then EQ else GT (D# x) < (D# y) = isTrue# (x <## y) (D# x) <= (D# y) = isTrue# (x <=## y) (D# x) >= (D# y) = isTrue# (x >=## y) (D# x) > (D# y) = isTrue# (x >## y) instance Ord Int where compare = compareInt (<) = ltInt (<=) = leInt (>=) = geInt (>) = gtInt {-# INLINE gtInt #-} {-# INLINE geInt #-} {-# INLINE ltInt #-} {-# INLINE leInt #-} gtInt, geInt, ltInt, leInt :: Int -> Int -> Bool (I# x) `gtInt` (I# y) = isTrue# (x ># y) (I# x) `geInt` (I# y) = isTrue# (x >=# y) (I# x) `ltInt` (I# y) = isTrue# (x <# y) (I# x) `leInt` (I# y) = isTrue# (x <=# y) compareInt :: Int -> Int -> Ordering (I# x#) `compareInt` (I# y#) = compareInt# x# y# compareInt# :: Int# -> Int# -> Ordering compareInt# x# y# | isTrue# (x# <# y#) = LT | isTrue# (x# ==# y#) = EQ | True = GT -- OK, so they're technically not part of a class...: -- Boolean functions -- | Boolean \"and\" (&&) :: Bool -> Bool -> Bool True && x = x False && _ = False -- | Boolean \"or\" (||) :: Bool -> Bool -> Bool True || _ = True False || x = x -- | Boolean \"not\" not :: Bool -> Bool not True = False not False = True ------------------------------------------------------------------------ -- These don't really belong here, but we don't have a better place to -- put them divInt# :: Int# -> Int# -> Int# x# `divInt#` y# -- Be careful NOT to overflow if we do any additional arithmetic -- on the arguments... the following previous version of this -- code has problems with overflow: -- | (x# ># 0#) && (y# <# 0#) = ((x# -# y#) -# 1#) `quotInt#` y# -- | (x# <# 0#) && (y# ># 0#) = ((x# -# y#) +# 1#) `quotInt#` y# = if isTrue# (x# ># 0#) && isTrue# (y# <# 0#) then ((x# -# 1#) `quotInt#` y#) -# 1# else if isTrue# (x# <# 0#) && isTrue# (y# ># 0#) then ((x# +# 1#) `quotInt#` y#) -# 1# else x# `quotInt#` y# modInt# :: Int# -> Int# -> Int# x# `modInt#` y# = if isTrue# (x# ># 0#) && isTrue# (y# <# 0#) || isTrue# (x# <# 0#) && isTrue# (y# ># 0#) then if isTrue# (r# /=# 0#) then r# +# y# else 0# else r# where !r# = x# `remInt#` y# class Class a where unobj :: a -> Object# a obj :: Object# a -> a instance Class Object where unobj (O# x) = x obj = O# instance Class JString where unobj (JS# x) = x obj = JS# foreign import java unsafe "equals" __equals :: Object# a -> Object# b -> Bool foreign import java unsafe "compareTo" __compareTo :: JString -> JString -> Int instance Eq Object where (==) (O# x) (O# y)= __equals x y instance Eq JString where (==) (JS# x) (JS# y) = __equals x y instance Ord JString where (<=) x y = __compareTo x y <= (I# 0#) -- For embedding Java class hierarchies data Defined = Yes | No type family Inherits (a :: *) :: [*] type family Super (a :: *) :: * where Super a = Head (Inherits a) type family Head (a :: [*]) :: * where Head (a ': b) = a Head '[] = Object type family Implements (a :: *) :: [*] where Implements a = Tail (Inherits a) type family Tail (a :: [*]) :: [*] where Tail (a ': b) = b Tail '[] = '[] type family ExtendsList (a :: [*]) (b :: *) :: Defined where ExtendsList '[] y = No ExtendsList (x ': xs) y = Or (Extends' x y) (ExtendsList xs y) type family Extends' (a :: *) (b :: *) :: Defined where Extends' a a = Yes Extends' a Object = Yes Extends' Object a = No Extends' a b = ExtendsList (Inherits a) b type family Or (a :: Defined) (b :: Defined) :: Defined where Or No No = No Or a b = Yes class (Class a, Class b) => Extends a b where superCast :: a -> b {-# INLINE superCast #-} superCast x = obj (unsafeCoerce# (unobj x)) unsafeCast :: b -> a {-# INLINE unsafeCast #-} unsafeCast x = obj (classCast# (unobj x)) -- TODO: Find out a way to get the same efficiency -- instance Class a => Extends a a where -- {-# INLINE superCast #-} -- superCast x = x -- {-# INLINE unsafeCast #-} -- unsafeCast x = x instance (Class a, Class b, Extends' a b ~ Yes) => Extends a b where type (<:) a b = Extends a b
alexander-at-github/eta
libraries/ghc-prim/GHC/Classes.hs
bsd-3-clause
13,383
7
11
4,256
5,518
3,039
2,479
-1
-1
{-# LANGUAGE MonomorphismRestriction #-} -- | Helpers for defining JSON instances. module Text.JSON.Helpers (readFail,matchConsts,maybeToResult,readJSONEnum,showJSONEnum,constDashed ,maybeValFromObj,unj) where import Control.Applicative (Applicative(..),Alternative(..),(<$>)) import Data.Char import Text.JSON (Result(..),JSValue(..),fromJSString,JSON(..),valFromObj,JSObject) import Text.Regex -- | Make a readJSON error string. readFail :: String -> String -> String readFail n s = n ++ ".readJSON: " ++ s -- | Match constructors against a string. matchConsts :: (String -> String) -> String -> [(String,a)] -> Result a matchConsts n s = maybeToResult (n "enum match fail") . lookup s -- | Convert a Maybe to a parse result. maybeToResult :: String -> Maybe a -> Result a maybeToResult n a = case a of Just v -> return v Nothing -> Error n -- | Read an enum type from JSON. readJSONEnum :: (Show a,Enum a) => String -> JSValue -> Result a readJSONEnum n (JSString s) = matchConsts (readFail n) (fromJSString s) xs where xs = zip (map constDashed ys) ys ys = enumFrom $ toEnum 0 readJSONEnum n _ = Error $ "failed to read enum type: " ++ n -- | Show an enum type. showJSONEnum :: (Enum a,Show a) => a -> JSValue showJSONEnum = showJSON . constDashed -- | Convert a const value e.g. "FooBar" to "foo-bar". constDashed :: (Enum a,Show a) => a -> String constDashed = map toLower . stripDash . upperToDash . show where upperToDash = flip (subRegex (mkRegex "_")) "." . flip (subRegex (mkRegex "([a-zA-Z0-9])([A-Z])")) "\\1-\\2" stripDash = dropWhile (=='-') maybeValFromObj :: (JSON a) => String -> JSObject JSValue -> Result (Maybe a) maybeValFromObj n o = (Just <$> valFromObj n o) <|> pure Nothing unj :: JSON a => String -> JSObject JSValue -> Result a unj name o = do v <- valFromObj name o readJSON v
zhuangzi/genrei
src/Text/JSON/Helpers.hs
bsd-3-clause
1,905
0
12
389
628
335
293
34
2
module Haskeroids.Text ( Text , mkText , setTextCenter ) where import Haskeroids.Geometry import Haskeroids.Geometry.Body import Haskeroids.Geometry.Transform import Haskeroids.Render import Haskeroids.Text.Font import Data.List data Text = Text { textBody :: Body , textWidth :: Float , textHeight :: Float , textLines :: [LineSegment] } instance LineRenderable Text where interpolatedLines f t = map (transform b') $ textLines t where b' = interpolatedBody f $ textBody t mkText :: Font -> FontSize -> String -> Text mkText f sz s = Text { textBody = initBody (0,0) 0 (0,0) 0 , textWidth = sz * len + (sz*0.2) * (len - 1) , textHeight = sz , textLines = lns } where len = fromIntegral $ length s lns = fst . foldl' go ([],0) . map (charLines f sz) $ s go (ls,x) l = (offset x l ++ ls, x + sz * 1.2) offset x ls = map (applyXform $ translatePt (x,0)) ls setTextCenter :: Vec2 -> Text -> Text setTextCenter (cx,cy) (Text b w h ls) = Text b' w h ls where b' = b { bodyPos = pos, prevPos = pos } pos = (cx-w/2,cy-h/2)
shangaslammi/haskeroids-frp
Haskeroids/Text.hs
mit
1,127
0
12
300
462
256
206
32
1
#!/usr/bin/env execthirdlinedocker.sh -- info: use sed -i 's/\r//g' file if report "/usr/bin/env: ‘execthirdlinedocker.sh\r’: No such file or directory" -- runghc -i../transient/src -i../transient-universe/src -i../axiom/src tests/api.hs -p start/localhost/8000 {- execute as ./tests/api.hs -p start/<docker ip>/<port> invoque: curl http://<docker ip>:<port>/api to get some examples -} import Transient.Internals import Transient.Move import Transient.Move.Utils import Transient.Indeterminism import Control.Applicative import Transient.Logged import Control.Concurrent(threadDelay) import Control.Monad.IO.Class import qualified Data.ByteString.Lazy.Char8 as BS import qualified Data.ByteString as BSS import Data.Aeson import System.IO.Unsafe import Data.IORef helpmessage= "Invoke examples:\n\ \ GET: curl http://localhost:8000/api/hello/john\n\ \ curl http://localhost:8000/api/hellos/john\n\ \ POST: curl http://localhost:8000/api/params -d \"name=Hugh&age=30\"\n\ \ curl -H \"Content-Type: application/json\" http://localhost:8000/api/json -d '{\"name\":\"Hugh\",\"age\": 30}'\n" main = keep $ initNode apisample -- onAll $ liftIO $ putStrLn "\n\n" >> putStrLn helpmessage >> putStrLn "\n\n" apisample= (api $ gets <|> posts <|> badRequest) <|> localIO (print "hello") where posts= do received POST postJSON <|> postParams postJSON= do received "json" json <- param liftIO $ print (json :: Value) let msg= "received: " ++ show json ++ "\n" return $ BS.pack $ "HTTP/1.0 200 OK\nContent-Type: text/plain\nContent-Length: "++ show (length msg) ++ "\nConnection: close\n\n" ++ msg postParams= do received "params" postParams <- param liftIO $ print (postParams :: PostParams) let msg= "received\n" return $ BS.pack $ "HTTP/1.0 200 OK\nContent-Type: text/plain\nContent-Length: "++ show (length msg) ++ "\nConnection: close\n\n" ++ msg gets= do received GET hello <|> hellostream hello= do received "hello" name <- param let msg= "hello " ++ name ++ "\n" len= length msg return $ BS.pack $ "HTTP/1.0 200 OK\nContent-Type: text/plain\nContent-Length: "++ show len ++ "\nConnection: close\n\n" ++ msg hellostream = do received "hellos" name <- param header <|> stream name where header=async $ return $ BS.pack $ "HTTP/1.0 200 OK\nContent-Type: text/plain\nConnection: close\n\n"++ "here follows a stream\n" stream name= do i <- threads 0 $ choose [1 ..] liftIO $ threadDelay 100000 return . BS.pack $ " hello " ++ name ++ " "++ show i badRequest = return $ BS.pack $ let resp="Bad Request\n"++ helpmessage in "HTTP/1.0 400 Bad Request\nContent-Length: " ++ show(length resp) ++"\nConnection: close\n\n"++ resp
agocorona/transient-universe
tests/api.hs
mit
3,304
0
16
1,018
583
293
290
58
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} -- -- DeriveAnyClass is not actually used by persistent-template -- But a long standing bug was that if it was enabled, it was used to derive instead of GeneralizedNewtypeDeriving -- This was fixed by using DerivingStrategies to specify newtype deriving should be used. -- This pragma is left here as a "test" that deriving works when DeriveAnyClass is enabled. -- See https://github.com/yesodweb/persistent/issues/578 {-# LANGUAGE DeriveAnyClass #-} module Database.Persist.TH.ForeignRefSpec where import Control.Applicative (Const(..)) import Data.Aeson import Data.ByteString.Lazy.Char8 () import Data.Coerce import Data.Functor.Identity (Identity(..)) import Data.Int import qualified Data.List as List import Data.Proxy import Data.Text (Text, pack) import GHC.Generics (Generic) import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck.Arbitrary import Test.QuickCheck.Gen (Gen) import Database.Persist import Database.Persist.EntityDef.Internal import Database.Persist.Sql import Database.Persist.Sql.Util import Database.Persist.TH import TemplateTestImports mkPersist sqlSettings [persistLowerCase| HasCustomName sql=custom_name name Text ForeignTarget name Text deriving Eq Show ForeignSource name Text foreignTargetId ForeignTargetId Foreign ForeignTarget fk_s_t foreignTargetId ForeignPrimary name Text Primary name deriving Eq Show ForeignPrimarySource name Text Foreign ForeignPrimary fk_name_target name NullableRef name Text Maybe Foreign ForeignPrimary fk_nullable_ref name ParentImplicit name Text ChildImplicit name Text parent ParentImplicitId OnDeleteCascade OnUpdateCascade ParentExplicit name Text Primary name ChildExplicit name Text Foreign ParentExplicit OnDeleteCascade OnUpdateCascade fkparent name |] spec :: Spec spec = describe "ForeignRefSpec" $ do describe "HasCustomName" $ do let edef = entityDef $ Proxy @HasCustomName it "should have a custom db name" $ do entityDB edef `shouldBe` EntityNameDB "custom_name" it "should compile" $ do True `shouldBe` True describe "ForeignPrimarySource" $ do let fpsDef = entityDef $ Proxy @ForeignPrimarySource [foreignDef] = entityForeigns fpsDef it "has the right type" $ do foreignPrimarySourceFk_name_target (ForeignPrimarySource "asdf") `shouldBe` ForeignPrimaryKey "asdf" describe "Cascade" $ do describe "Explicit" $ do let parentDef = entityDef $ Proxy @ParentExplicit childDef = entityDef $ Proxy @ChildExplicit childForeigns = entityForeigns childDef it "should have a single foreign reference defined" $ do case entityForeigns childDef of [a] -> pure () as -> expectationFailure . mconcat $ [ "Expected one foreign reference on childDef, " , "got: " , show as ] let [ForeignDef {..}] = childForeigns describe "ChildExplicit" $ do it "should have the right target table" $ do foreignRefTableHaskell `shouldBe` EntityNameHS "ParentExplicit" foreignRefTableDBName `shouldBe` EntityNameDB "parent_explicit" it "should have the right cascade behavior" $ do foreignFieldCascade `shouldBe` FieldCascade { fcOnUpdate = Just Cascade , fcOnDelete = Just Cascade } it "is not nullable" $ do foreignNullable `shouldBe` False it "is to the Primary key" $ do foreignToPrimary `shouldBe` True describe "Implicit" $ do let parentDef = entityDef $ Proxy @ParentImplicit childDef = entityDef $ Proxy @ChildImplicit childFields = entityFields childDef describe "ChildImplicit" $ do case childFields of [nameField, parentIdField] -> do it "parentId has reference" $ do fieldReference parentIdField `shouldBe` ForeignRef (EntityNameHS "ParentImplicit") as -> error . mconcat $ [ "Expected one foreign reference on childDef, " , "got: " , show as ]
paul-rouse/persistent
persistent/test/Database/Persist/TH/ForeignRefSpec.hs
mit
5,781
0
28
2,153
750
395
355
118
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.RDS.DeleteDBClusterParameterGroup -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a specified DB cluster parameter group. The DB cluster parameter -- group to be deleted cannot be associated with any DB clusters. -- -- For more information on Amazon Aurora, see -- <http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Aurora.html Aurora on Amazon RDS> -- in the /Amazon RDS User Guide./ -- -- /See:/ <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DeleteDBClusterParameterGroup.html AWS API Reference> for DeleteDBClusterParameterGroup. module Network.AWS.RDS.DeleteDBClusterParameterGroup ( -- * Creating a Request deleteDBClusterParameterGroup , DeleteDBClusterParameterGroup -- * Request Lenses , ddbcpgDBClusterParameterGroupName -- * Destructuring the Response , deleteDBClusterParameterGroupResponse , DeleteDBClusterParameterGroupResponse ) where import Network.AWS.Prelude import Network.AWS.RDS.Types import Network.AWS.RDS.Types.Product import Network.AWS.Request import Network.AWS.Response -- | -- -- /See:/ 'deleteDBClusterParameterGroup' smart constructor. newtype DeleteDBClusterParameterGroup = DeleteDBClusterParameterGroup' { _ddbcpgDBClusterParameterGroupName :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteDBClusterParameterGroup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ddbcpgDBClusterParameterGroupName' deleteDBClusterParameterGroup :: Text -- ^ 'ddbcpgDBClusterParameterGroupName' -> DeleteDBClusterParameterGroup deleteDBClusterParameterGroup pDBClusterParameterGroupName_ = DeleteDBClusterParameterGroup' { _ddbcpgDBClusterParameterGroupName = pDBClusterParameterGroupName_ } -- | The name of the DB cluster parameter group. -- -- Constraints: -- -- - Must be the name of an existing DB cluster parameter group. -- - You cannot delete a default DB cluster parameter group. -- - Cannot be associated with any DB clusters. ddbcpgDBClusterParameterGroupName :: Lens' DeleteDBClusterParameterGroup Text ddbcpgDBClusterParameterGroupName = lens _ddbcpgDBClusterParameterGroupName (\ s a -> s{_ddbcpgDBClusterParameterGroupName = a}); instance AWSRequest DeleteDBClusterParameterGroup where type Rs DeleteDBClusterParameterGroup = DeleteDBClusterParameterGroupResponse request = postQuery rDS response = receiveNull DeleteDBClusterParameterGroupResponse' instance ToHeaders DeleteDBClusterParameterGroup where toHeaders = const mempty instance ToPath DeleteDBClusterParameterGroup where toPath = const "/" instance ToQuery DeleteDBClusterParameterGroup where toQuery DeleteDBClusterParameterGroup'{..} = mconcat ["Action" =: ("DeleteDBClusterParameterGroup" :: ByteString), "Version" =: ("2014-10-31" :: ByteString), "DBClusterParameterGroupName" =: _ddbcpgDBClusterParameterGroupName] -- | /See:/ 'deleteDBClusterParameterGroupResponse' smart constructor. data DeleteDBClusterParameterGroupResponse = DeleteDBClusterParameterGroupResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteDBClusterParameterGroupResponse' with the minimum fields required to make a request. -- deleteDBClusterParameterGroupResponse :: DeleteDBClusterParameterGroupResponse deleteDBClusterParameterGroupResponse = DeleteDBClusterParameterGroupResponse'
fmapfmapfmap/amazonka
amazonka-rds/gen/Network/AWS/RDS/DeleteDBClusterParameterGroup.hs
mpl-2.0
4,278
0
9
755
376
235
141
55
1
{- Copyright 2019 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {- | This module encapsulates the logics behind the prediction code in the multi-player setup. It is the “trivially correct” version. -} {-# LANGUAGE RecordWildCards, ViewPatterns #-} module CodeWorld.Prediction.Trivial ( Timestamp , AnimationRate , StepFun , Future , initFuture , currentTimePasses , currentState , addEvent , eqFuture , printInternalState ) where import Data.Bifunctor (second) import qualified Data.IntMap as IM import Data.List (foldl', intercalate) import qualified Data.MultiMap as M import Text.Printf type PlayerId = Int type Timestamp = Double -- in seconds, relative to some arbitrary starting point type AnimationRate = Double -- in seconds, e.g. 0.1 -- All we do with events is to apply them to the state. So let's just store the -- function that does that. type Event s = s -> s -- A state and an event only make sense together with a time. type TState s = (Timestamp, s) type TEvent s = (Timestamp, Event s) type StepFun s = Double -> s -> s type EventQueue s = M.MultiMap (Timestamp, PlayerId) (Event s) -- | Invariants about the time stamps in this data type: -- * committed <= pending <= current < future -- * The time is advanced with strictly ascending timestamps -- * For each player, events come in with strictly ascending timestamps -- * For each player, all events in pending or future are before the -- corresponding lastEvents entry. data Future s = Future { initial :: s , events :: EventQueue s } initFuture :: s -> Int -> Future s initFuture s _numPlayers = Future {initial = s, events = M.empty} -- Time handling. -- -- Move state forward in fixed animation rate steps, and get -- the timestamp as close to the given target as possible (but possibly stop short) timePassesBigStep :: StepFun s -> AnimationRate -> Timestamp -> TState s -> TState s timePassesBigStep step rate target (now, s) | now + rate <= target = timePassesBigStep step rate target (stepBy step rate (now, s)) | otherwise = (now, s) -- Move state forward in fixed animation rate steps, and get -- the timestamp as close to the given target as possible, and then do a final small step timePasses :: StepFun s -> AnimationRate -> Timestamp -> TState s -> TState s timePasses step rate target = stepTo step target . timePassesBigStep step rate target stepBy :: StepFun s -> Double -> TState s -> TState s stepBy step diff (now, s) = (now + diff, step diff s) stepTo :: StepFun s -> Timestamp -> TState s -> TState s stepTo step target (now, s) = (target, step (target - now) s) handleNextEvent :: StepFun s -> AnimationRate -> TEvent s -> TState s -> TState s handleNextEvent step rate (target, event) = second event . timePasses step rate target handleNextEvents :: StepFun s -> AnimationRate -> EventQueue s -> TState s -> TState s handleNextEvents step rate eq ts = foldl' (flip (handleNextEvent step rate)) ts $ map (\((t, _p), h) -> (t, h)) $ M.toList eq -- | This should be called shortly following 'currentTimePasses' currentState :: StepFun s -> AnimationRate -> Timestamp -> Future s -> s currentState step rate target f = snd $ timePasses step rate target $ handleNextEvents step rate to_apply (0, initial f) where (to_apply, _) = M.spanAntitone (\(t, p) -> t <= target) (events f) -- | This should be called regularly, to keep the current state up to date, -- and to incorporate future events in it. currentTimePasses :: StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s currentTimePasses step rate target = id -- | Take a new event into account, local or remote. -- Invariant: -- * The timestamp of the event is larger than the timestamp -- of any event added for this player (which is the timestamp for the player -- in `lastEvents`) addEvent :: StepFun s -> AnimationRate -> PlayerId -> Timestamp -> Maybe (Event s) -> Future s -> Future s-- A future event. addEvent step rate player now mbEvent f = f {events = maybe id (M.insertR (now, player)) mbEvent $ events f} -- | Advances the current time (by big steps) advanceCurrentTime :: StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s advanceCurrentTime step rate target = id eqFuture :: Eq s => Future s -> Future s -> Bool eqFuture f1 f2 = M.keys (events f1) == M.keys (events f2) printInternalState :: (s -> String) -> Future s -> IO () printInternalState showState f = do printf " Event keys: %s\n" (show (M.keys (events f)))
alphalambda/codeworld
codeworld-prediction/src/CodeWorld/Prediction/Trivial.hs
apache-2.0
5,164
0
13
1,097
1,167
624
543
79
1
{-# LANGUAGE DataKinds , TypeOperators , NoImplicitPrelude , FlexibleContexts #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} ---------------------------------------------------------------- -- 2016.04.21 -- | -- Module : Language.Hakaru.Inference -- Copyright : Copyright (c) 2016 the Hakaru team -- License : BSD3 -- Maintainer : wren@community.haskell.org -- Stability : experimental -- Portability : GHC-only -- -- TODO: we may want to give these longer\/more-explicit names so -- as to be a bit less ambiguous in the larger Haskell ecosystem. ---------------------------------------------------------------- module Language.Hakaru.Inference ( priorAsProposal , mh , mcmc , gibbsProposal , slice , sliceX , incompleteBeta , regBeta , tCDF , approxMh , kl ) where import Prelude (($), (.), error, Maybe(..), return) import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing import Language.Hakaru.Syntax.AST (Term) import Language.Hakaru.Syntax.ABT (ABT, binder) import Language.Hakaru.Syntax.Prelude import Language.Hakaru.Syntax.TypeOf import Language.Hakaru.Expect (expect, normalize) import Language.Hakaru.Disintegrate (determine, density, disintegrate) import qualified Data.Text as Text ---------------------------------------------------------------- ---------------------------------------------------------------- priorAsProposal :: (ABT Term abt, SingI a, SingI b) => abt '[] ('HMeasure (HPair a b)) -> abt '[] (HPair a b) -> abt '[] ('HMeasure (HPair a b)) priorAsProposal p x = bern (prob_ 0.5) >>= \c -> p >>= \x' -> dirac $ if_ c (pair (fst x ) (snd x')) (pair (fst x') (snd x )) -- We don't do the accept\/reject part of MCMC here, because @min@ -- and @bern@ don't do well in @simplify@! So we'll be passing the -- resulting AST of 'mh' to 'simplify' before plugging that into -- @mcmc@; that's why 'easierRoadmapProg4' and 'easierRoadmapProg4'' -- have different types. -- -- TODO: the @a@ type should be pure (aka @a ~ Expect' a@ in the old parlance). -- BUG: get rid of the SingI requirements due to using 'lam' mh :: (ABT Term abt) => abt '[] (a ':-> 'HMeasure a) -> abt '[] ('HMeasure a) -> abt '[] (a ':-> 'HMeasure (HPair a 'HProb)) mh proposal target = case determine $ density target of Nothing -> error "mh: couldn't get density" Just theDensity -> let_ theDensity $ \mu -> lam' $ \old -> app proposal old >>= \new -> dirac $ pair' new (mu `app` {-pair-} new {-old-} / mu `app` {-pair-} old {-new-}) where lam' f = lamWithVar Text.empty (sUnMeasure $ typeOf target) f pair' = pair_ (sUnMeasure $ typeOf target) SProb -- BUG: get rid of the SingI requirements due to using 'lam' in 'mh' mcmc :: (ABT Term abt) => abt '[] (a ':-> 'HMeasure a) -> abt '[] ('HMeasure a) -> abt '[] (a ':-> 'HMeasure a) mcmc proposal target = let_ (mh proposal target) $ \f -> lamWithVar Text.empty (sUnMeasure $ typeOf target) $ \old -> app f old >>= \new_ratio -> new_ratio `unpair` \new ratio -> bern (min (prob_ 1) ratio) >>= \accept -> dirac (if_ accept new old) gibbsProposal :: (ABT Term abt, SingI a, SingI b) => abt '[] ('HMeasure (HPair a b)) -> abt '[] (HPair a b) -> abt '[] ('HMeasure (HPair a b)) gibbsProposal p xy = case determine $ disintegrate p of Nothing -> error "gibbsProposal: couldn't disintegrate" Just q -> xy `unpair` \x _y -> pair x <$> normalize (q `app` x) -- Slice sampling can be thought of: -- -- slice target x = do -- u <- uniform(0, density(target, x)) -- x' <- lebesgue -- condition (density(target, x') >= u) true -- return x' slice :: (ABT Term abt) => abt '[] ('HMeasure 'HReal) -> abt '[] ('HReal ':-> 'HMeasure 'HReal) slice target = case determine $ density target of Nothing -> error "slice: couldn't get density" Just densAt -> lam $ \x -> uniform (real_ 0) (fromProb $ app densAt x) >>= \u -> normalize $ lebesgue >>= \x' -> withGuard (u < (fromProb $ app densAt x')) $ dirac x' sliceX :: (ABT Term abt, SingI a) => abt '[] ('HMeasure a) -> abt '[] ('HMeasure (HPair a 'HReal)) sliceX target = case determine $ density target of Nothing -> error "sliceX: couldn't get density" Just densAt -> target `bindx` \x -> uniform (real_ 0) (fromProb $ app densAt x) incompleteBeta :: (ABT Term abt) => abt '[] 'HProb -> abt '[] 'HProb -> abt '[] 'HProb -> abt '[] 'HProb incompleteBeta x a b = let one' = real_ 1 in integrate (real_ 0) (fromProb x) $ \t -> unsafeProb t ** (fromProb a - one') * unsafeProb (one' - t) ** (fromProb b - one') regBeta -- TODO: rename 'regularBeta' :: (ABT Term abt) => abt '[] 'HProb -> abt '[] 'HProb -> abt '[] 'HProb -> abt '[] 'HProb regBeta x a b = incompleteBeta x a b / betaFunc a b tCDF :: (ABT Term abt) => abt '[] 'HReal -> abt '[] 'HProb -> abt '[] 'HProb tCDF x v = let b = regBeta (v / (unsafeProb (x*x) + v)) (v / prob_ 2) (prob_ 0.5) in unsafeProb $ real_ 1 - real_ 0.5 * fromProb b -- BUG: get rid of the SingI requirements due to using 'lam' approxMh :: (ABT Term abt, SingI a) => (abt '[] a -> abt '[] ('HMeasure a)) -> abt '[] ('HMeasure a) -> [abt '[] a -> abt '[] ('HMeasure a)] -> abt '[] (a ':-> 'HMeasure a) approxMh _ _ [] = error "TODO: approxMh for empty list" approxMh proposal prior (_:xs) = case determine . density $ bindx prior proposal of Nothing -> error "approxMh: couldn't get density" Just theDensity -> lam $ \old -> let_ theDensity $ \mu -> unsafeProb <$> uniform (real_ 0) (real_ 1) >>= \u -> proposal old >>= \new -> let_ (u * mu `app` pair new old / mu `app` pair old new) $ \u0 -> let_ (l new new / l old old) $ \l0 -> let_ (tCDF (n - real_ 1) (udif l0 u0)) $ \delta -> if_ (delta < eps) (if_ (u0 < l0) (dirac new) (dirac old)) (approxMh proposal prior xs `app` old) where n = real_ 2000 eps = prob_ 0.05 udif lo hi = unsafeProb $ fromProb lo - fromProb hi l = \_d1 _d2 -> prob_ 2 -- determine (density (\theta -> x theta)) kl :: (ABT Term abt) => abt '[] ('HMeasure a) -> abt '[] ('HMeasure a) -> Maybe (abt '[] 'HProb) kl p q = do dp <- determine $ density p dq <- determine $ density q return . expect p . binder Text.empty (sUnMeasure $ typeOf p) $ \i -> unsafeProb $ log (app dp i / app dq i)
zaxtax/hakaru
haskell/Language/Hakaru/Inference.hs
bsd-3-clause
6,849
0
26
1,893
2,447
1,261
1,186
159
2
{-# LANGUAGE MultiParamTypeClasses , GADTs , DataKinds , RankNTypes , TypeFamilies , TypeOperators , FlexibleContexts , FlexibleInstances , ScopedTypeVariables , UndecidableInstances , ConstraintKinds , PolyKinds , FunctionalDependencies , NoMonoLocalBinds , InstanceSigs , BangPatterns , ViewPatterns , PatternSynonyms , DeriveFunctor , DeriveDataTypeable , StandaloneDeriving , CPP #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} module Ef (module Ef, module Export) where import Control.Applicative as Export import Control.Monad as Export import Control.Monad.Codensity as Export import Control.Monad.Fail import Control.Monad.Fix as Export import Control.Monad.Free as Export hiding (unfold,cutoff) import Control.Monad.IO.Class as Export import Control.Monad.Trans.Class as Export import Control.Monad.Reader.Class import Control.Monad.Writer.Class import Control.Monad.State.Class import Control.Monad.Error.Class import Control.Monad.Morph as Export import Control.Monad.Base as Export import Control.Monad.Trans.Resource import Control.Monad.Catch import Control.Comonad import Control.Comonad.Cofree import Data.Data import Data.Functor.Compose import Data.Functor.Sum import Data.IORef import Data.Proxy as Export import Ef.Type.Bool as Export import Ef.Type.Nat as Export import Ef.Type.List as Export import Ef.Type.Set as Export import GHC.Exts data Modules (ts :: [* -> *]) (x :: *) where Empty :: Modules '[] x Mod :: t x -> Modules ts x -> Modules (t ': ts) x data Messages ms a where Other :: Messages ms' a -> Messages (m ': ms') a Msg :: m a -> Messages (m ': ms') a newtype Object ts c = Object { deconstruct :: Modules ts (Action ts c) } data Narrative (f :: * -> *) c a = Do (f (Narrative f c a)) | Lift (c (Narrative f c a)) | Return a type Ef (ms :: [* -> *]) (c :: * -> *) = Narrative (Messages ms) c {-# INLINE viewMsg #-} viewMsg :: (Can' ms m (Offset ms m)) => Ef ms c a -> Maybe (m (Ef ms c a)) viewMsg (Do m) = prj m viewMsg _ = Nothing pattern Module :: Has' ts t (Offset ts t) => t (Action ts c) -> Object ts c -> Object ts c pattern Module x o <- (\o -> let x = pull (deconstruct o) in (x,o) -> (x,o)) where Module x o = Object $ push x $ deconstruct o pattern Send :: Can' ms m (Offset ms m) => m (Ef ms c a) -> Ef ms c a pattern Send x <- (viewMsg -> Just x) where Send x = Do (inj x) {-# INLINE send #-} send :: Functor f => f a -> Narrative f c a send f = buildn $ \r _ d -> d (fmap r f) {-# INLINE yields #-} yields :: Functor f => f r -> Narrative f c r yields fr = buildn $ \r l d -> d (fmap r fr) {-# INLINE sends #-} sends :: (ms <: '[f]) => f r -> Ef ms c r sends = yields . inj {-# INLINE super #-} super :: Functor c => c a -> Narrative f c a super s = buildn (\r l _ -> l (fmap r s)) deriving instance (Show a, Show (c (Narrative f c a)), Show (f (Narrative f c a))) => Show (Narrative f c a) deriving instance (Eq a, Eq (c (Narrative f c a)), Eq (f (Narrative f c a))) => Eq (Narrative f c a) deriving instance (Typeable f, Typeable c, Data a, Data (c (Narrative f c a)), Data (f (Narrative f c a))) => Data (Narrative f c a) instance (MonadIO c, Functor f) => MonadIO (Narrative f c) where {-# INLINE liftIO #-} liftIO ioa = buildn $ \r l _ -> l (fmap r (liftIO ioa)) instance MonadTrans (Narrative f) where {-# INLINE lift #-} lift ca = buildn $ \r l _ -> l (fmap r ca) instance Functor (Modules '[]) where {-# INLINE fmap #-} fmap _ _ = Empty instance (Functor t, Functor (Modules ts)) => Functor (Modules (t ': ts)) where {-# INLINE fmap #-} fmap f (Mod t ts) = Mod (fmap f t) (fmap f ts) instance Functor (Messages '[]) instance (Functor (Messages ms), Functor m) => Functor (Messages (m ': ms)) where {-# INLINE fmap #-} fmap = _fmapMsg {-# INLINE [1] _fmapMsg #-} _fmapMsg :: forall a b m ms. (Functor m, Functor (Messages ms)) => (a -> b) -> Messages (m ': ms) a -> Messages (m ': ms) b _fmapMsg f = go where go :: Messages (m ': ms) a -> Messages (m ': ms) b go (Other ms) = Other (fmap f ms) go (Msg m) = Msg (fmap f m) instance (Functor f, Functor c) => MonadFree f (Narrative f c) where {-# INLINE wrap #-} wrap = Do instance (Functor f, Functor c) => Functor (Narrative f c) where {-# INLINE fmap #-} fmap = _fmap instance (Functor f, Functor c) => Applicative (Narrative f c) where {-# INLINE pure #-} pure a = Return a {-# INLINE (<*>) #-} (<*>) = ap instance (Functor f, Functor c) => Monad (Narrative f c) where {-# INLINE return #-} return a = Return a {-# INLINE (>>=) #-} (>>=) = _bind {-# INLINE (>>) #-} (>>) ma mb = _bind ma (const mb) instance (Applicative f, Monad c) => MonadPlus (Narrative f c) where {-# INLINE mzero #-} mzero = empty {-# INLINE mplus #-} mplus = (<|>) instance (Applicative f, Monad c) => Alternative (Narrative f c) where {-# INLINE empty #-} empty = never {-# INLINE (<|>) #-} (<|>) = zipsWith (liftA2 (,)) instance (Monad c, Monoid r, Functor f) => Monoid (Narrative f c r) where {-# INLINE mempty #-} mempty = return mempty #if !MIN_VERSION_base(4,11,0) {-# INLINE mappend #-} mappend a b = a >>= \w -> fmap (mappend w) b #else instance (Monad c, Semigroup r, Functor f) => Semigroup (Narrative f c r) where (<>) a b = a >>= \w -> fmap (w <>) b #endif instance Functor f => MFunctor (Narrative f) where {-# INLINE hoist #-} hoist = _hoist instance Functor f => MMonad (Narrative f) where {-# INLINE embed #-} embed = _embed instance (MonadBase b c, Functor f) => MonadBase b (Narrative f c) where {-# INLINE liftBase #-} liftBase b = Lift (fmap Return (liftBase b)) instance (MonadThrow c, Functor f) => MonadThrow (Narrative f c) where {-# INLINE throwM #-} throwM = lift . throwM instance (MonadCatch c, Functor f) => MonadCatch (Narrative f c) where {-# INLINE catch #-} catch = _catch instance (MonadResource c, Functor f) => MonadResource (Narrative f c) where {-# INLINE liftResourceT #-} liftResourceT = lift . liftResourceT instance (MonadWriter w c, Functor f) => MonadWriter w (Narrative f c) where {-# INLINE writer #-} writer = lift . writer {-# INLINE tell #-} tell = lift . tell {-# INLINE listen #-} listen n = buildn go where go r l d = foldn (\a w -> r (a,w)) (\c w -> l (fmap ($ w) c)) (\f w -> d (fmap ($ w) f)) n mempty {-# INLINE pass #-} pass n = buildn go where go r l d = foldn (\(a,f) w -> l $ pass $ return (r a,\_ -> f w)) (\c w -> l (fmap ($ w) c)) (\f w -> d (fmap ($ w) f)) n mempty instance (MonadReader r c, Functor f) => MonadReader r (Narrative f c) where {-# INLINE ask #-} ask = lift ask {-# INLINE local #-} local f n = buildn go where go r l d = foldn r (l . local f) d n {-# INLINE reader #-} reader = lift . reader instance (MonadState s c, Functor f) => MonadState s (Narrative f c) where {-# INLINE get #-} get = lift get {-# INLINE put #-} put = lift . put {-# INLINE state #-} state = lift . state instance (MonadError e c, Functor f) => MonadError e (Narrative f c) where {-# INLINE throwError #-} throwError = lift . throwError {-# INLINE catchError #-} catchError = _catchError data Restore m = Unmasked | Masked (forall x . m x -> m x) {-# INLINE liftMask #-} liftMask :: forall f c x. (Functor f, MonadIO c, MonadCatch c, MonadFail c) => (forall s . ((forall x . c x -> c x) -> c s) -> c s) -> ((forall x . Narrative f c x -> Narrative f c x) -> Narrative f c x) -> Narrative f c x liftMask maskVariant k = do ioref <- liftIO $ newIORef Unmasked let -- mask adjacent actions in base monad loop :: Narrative f c r -> Narrative f c r loop (Do m) = Do (fmap loop m) loop (Lift m) = Lift $ maskVariant $ \unmaskVariant -> do -- stash base's unmask and merge action liftIO $ writeIORef ioref $ Masked unmaskVariant m >>= chunk >>= return . loop loop (Return r) = Return r -- unmask adjacent actions in base monad unmask :: forall q. Narrative f c q -> Narrative f c q unmask (Do m) = Do (fmap unmask m) unmask (Lift m) = Lift $ do -- retrieve base's unmask and apply to merged action Masked unmaskVariant <- liftIO $ readIORef ioref unmaskVariant (m >>= chunk >>= return . unmask) unmask (Return q) = Return q -- merge adjacent actions in base monad chunk :: forall s. Narrative f c s -> c (Narrative f c s) chunk (Lift m) = m >>= chunk chunk s = return s loop $ k unmask instance (MonadMask c, MonadFail c, MonadIO c, Functor f) => MonadMask (Narrative f c) where mask = liftMask mask uninterruptibleMask = liftMask uninterruptibleMask {-# INLINE _hoist #-} _hoist :: (Functor f, Functor c') => (c' (Narrative f c a) -> c (Narrative f c a)) -> Narrative f c' a -> Narrative f c a _hoist f n = foldn Return (Lift . f) Do n {-# INLINE _embed #-} _embed :: (Monad c, Functor f) => (t (Narrative f t a) -> Narrative f c (Narrative f t a)) -> Narrative f t a -> Narrative f c a _embed f = go where go (Return r) = Return r go (Lift c) = f c >>= go go (Do m) = Do (fmap go m) {-# INLINE _catch #-} _catch :: (Exception e, Functor f, MonadCatch c) => Narrative f c a -> (e -> Narrative f c a) -> Narrative f c a _catch n f = foldn Return (\c -> Lift (catch c (pure . f))) Do n {-# INLINE _catchError #-} _catchError :: (Functor f, MonadError e c) => Narrative f c a -> (e -> Narrative f c a) -> Narrative f c a _catchError n f = foldn Return (\c -> Lift (catchError c (pure . f))) Do n class Delta f g | f -> g where delta :: (a -> b -> r) -> f a -> g b -> r type (<=>) ts ms = Delta (Modules ts) (Messages ms) instance Delta ((->) a) ((,) a) where {-# INLINE delta #-} delta u f (l,r) = u (f l) r instance Delta ((,) a) ((->) a) where {-# INLINE delta #-} delta u (l,r) g = u r (g l) instance Delta (Modules '[]) (Messages '[]) where {-# INLINE delta #-} delta u _ _ = u undefined undefined instance (t `Delta` m, Modules ts `Delta` Messages ms) => Delta (Modules (t ': ts)) (Messages (m ': ms)) where {-# INLINE delta #-} delta u (Mod t _) (Msg m) = delta u t m delta u (Mod _ ts) (Other ms) = delta u ts ms type Mod t ts c = t (Action ts c) type Action ts c = Object ts c -> c (Object ts c) class Has (ts :: [* -> *]) (t :: * -> *) where push :: t a -> Modules ts a -> Modules ts a pull :: Modules ts a -> t a instance (i ~ Offset ts t, Has' ts t i) => Has ts t where {-# INLINE push #-} push = let i = Index :: Index i in push' i {-# INLINE pull #-} pull = let i = Index :: Index i in pull' i class Has' (ts :: [* -> *]) (t :: * -> *) (n :: Nat) where push' :: Index n -> t a -> Modules ts a -> Modules ts a pull' :: Index n -> Modules ts a -> t a instance ts ~ (t ': xs) => Has' ts t 'Z where {-# INLINE push' #-} push' _ t (Mod _ ts) = Mod t ts {-# INLINE pull' #-} pull' _ (Mod t _) = t instance (i ~ Offset ts t, Has' ts t i) => Has' (t' ': ts) t ('S n) where {-# INLINE push' #-} push' _ t (Mod t' ts) = let i = Index :: Index i in Mod t' (push' i t ts) {-# INLINE pull' #-} pull' _ (Mod _ ts) = let i = Index :: Index i in pull' i ts type family (<.) (ts :: [* -> *]) (ts' :: [* -> *]) :: Constraint where (<.) ts' '[] = () (<.) ts' (t ': ts) = (Has' ts' t (Offset ts' t), ts' <. ts) type ts .> ts' = ts' <. ts class Can ms m where inj :: m a -> Messages ms a prj :: Messages ms a -> Maybe (m a) instance (i ~ Offset ms m, Can' ms m i) => Can ms m where {-# INLINE inj #-} inj = let i = Index :: Index i in inj' i {-# INLINE prj #-} prj = let i = Index :: Index i in prj' i class Can' ms m (n :: Nat) where inj' :: Index n -> m a -> Messages ms a prj' :: Index n -> Messages ms a -> Maybe (m a) instance (i ~ Offset ms' m, Can' ms' m i) => Can' (m' ': ms') m ('S n) where {-# INLINE inj' #-} inj' _ = let i = Index :: Index i in Other . inj' i {-# INLINE prj' #-} prj' _ (Other ms) = let i = Index :: Index i in prj' i ms prj' _ _ = Nothing instance (ms ~ (m ': ms')) => Can' ms m 'Z where {-# INLINE inj' #-} inj' _ = Msg {-# INLINE prj' #-} prj' _ (Msg message) = Just message prj' _ (Other _) = Nothing type family (<:) ms ms' where ms <: '[] = (Functor (Messages ms)) ms <: (m ': ms') = (Can' ms m (Offset ms m), ms <: ms') type ms :> ms' = ms' <: ms infixr 6 *:* {-# INLINE (*:*) #-} (*:*) :: t a -> Modules ts a -> Modules (t ': ts) a (*:*) = Mod class Append ts ts' ts'' where (*++*) :: (Appended ts ts' ~ ts'') => Modules ts a -> Modules ts' a -> Modules ts'' a instance (Appended ts ts' ~ ts'', Append ts ts' ts'') => Append (t ': ts) ts' (t ': ts'') where {-# INLINE (*++*) #-} (*++*) (Mod m ms) ys = m *:* (ms *++* ys) instance Append '[] ts ts where {-# INLINE (*++*) #-} (*++*) Empty ys = ys instance Append ts '[] ts where {-# INLINE (*++*) #-} (*++*) xs Empty = xs {-# INLINE unit #-} unit :: Proxy () unit = Proxy {-# INLINE transform #-} transform :: Monad c => (r -> a) -> (f (Narrative f c r) -> Narrative f' c a) -> Narrative f c r -> Narrative f' c a transform f t = go where go (Do m) = t m go (Lift sup) = Lift (fmap go sup) go (Return r) = Return (f r) {-# INLINE runWith #-} runWith :: forall ts ms c a. ((Modules ts) `Delta` (Messages ms), Functor (Messages ms), Monad c) => Object ts c -> Ef ms c a -> c (Object ts c,a) runWith o c = foldn runReturn runLift runDo c o where runReturn a o' = return (o',a) runLift c o = c >>= \f -> f o runDo :: Messages ms (Object ts c -> c (Object ts c,a)) -> Object ts c -> c (Object ts c,a) runDo ms o' = let ~(f,cont) = delta (,) (deconstruct o' :: Modules ts (Action ts c)) ms in f o' >>= cont infixr 5 ! {-# INLINE (!) #-} (!) :: ((Modules ts) `Delta` (Messages ms), Functor (Messages ms), Monad c) => Object ts c -> Ef ms c a -> c (Object ts c,a) (!) = runWith {-# INLINE [0] foldn #-} foldn :: (Functor c, Functor f) => (a -> b) -> (c b -> b) -> (f b -> b) -> Narrative f c a -> b foldn r l d = go where go (Return a) = r a go (Lift c) = l (fmap go c) go (Do m) = d (fmap go m) {-# INLINE [1] buildn #-} buildn :: (forall b. (a -> b) -> (c b -> b) -> (f b -> b) -> b) -> Narrative f c a buildn f = f Return Lift Do {-# INLINE run #-} run :: (Functor f, Monad m) => (f (m a) -> m a) -> Narrative f m a -> m a run = foldn return join {-# INLINE thread #-} thread :: (Functor f, Monad m) => (f (r -> m (r,a)) -> r -> m (r, a)) -> Narrative f m a -> r -> m (r,a) thread = foldn (\a r -> return (r,a)) (\cf a -> cf >>= ($ a)) {-# INLINE [0] foldn' #-} foldn' :: (Functor c, Functor f) => (a -> Narrative f c a) -> (c (Narrative f c a) -> Narrative f c a) -> (f (Narrative f c a) -> Narrative f c a) -> Narrative f c a -> Narrative f c a foldn' r l d = go where go (Return a) = r a go (Lift c) = l (fmap go c) go (Do m) = d (fmap go m) {-# INLINE [1] buildn' #-} buildn' :: forall f c a. ((a -> Narrative f c a) -> (c (Narrative f c a) -> Narrative f c a) -> (f (Narrative f c a) -> Narrative f c a) -> Narrative f c a) -> Narrative f c a buildn' f = f Return Lift Do {-# INLINE [1] fmapn #-} fmapn :: (Functor f, Functor c) => (a -> b) -> Narrative f c a -> Narrative f c b fmapn f (Return r) = Return (f r) fmapn f (Lift l) = Lift (fmap (fmapn f) l) fmapn f (Do d) = Do (fmap (fmapn f) d) {-# INLINE [0] fmapnR #-} fmapnR :: (a -> r) -> (x -> a) -> x -> r fmapnR r f = \c -> r (f c) {-# INLINE [0] fmapnFB #-} fmapnFB :: (a -> r) -> a -> r fmapnFB l = \a -> l a {-# INLINE [1] augmentn #-} augmentn :: forall f c a. (forall b. (a -> b) -> (c b -> b) -> (f b -> b) -> b -> b) -> Narrative f c a -> Narrative f c a augmentn f n = f Return Lift Do n {-# INLINE [2] _bind #-} _bind :: (Functor f, Functor c) => Narrative f c a -> (a -> Narrative f c b) -> Narrative f c b _bind m k = foldn k Lift Do m {-# INLINE [2] _fmap #-} _fmap :: (Functor f, Functor c) => (a -> b) -> Narrative f c a -> Narrative f c b _fmap f n = foldn (Return . f) Lift Do n {-# RULES "foldn/buildn" forall r l d (g :: forall b. (a -> b) -> (c b -> b) -> (f b -> b) -> b). foldn r l d (buildn g) = g r l d "foldn'/buildn'" forall r l d g. foldn' r l d (buildn' g) = g r l d "foldn/buildn'" forall r l d (g :: forall b. (a -> b) -> (c b -> b) -> (f b -> b) -> b). foldn r l d (buildn' g) = g r l d "foldn/augmentn" forall r l d (g :: forall b. (a -> b) -> (c b -> b) -> (f b -> b) -> b -> b) n. foldn r l d (augmentn g n) = g r l d (foldn r l d n) "_fmap/fmapn" forall f n. _fmap f n = fmapn f n "fmapn" [~1] forall f n. fmapn f n = buildn (\r l d -> foldn (fmapnR r f) (fmapnFB l) (fmapnFB d) n) "fmapnRFB" [1] forall f. foldn (fmapnR Return f) (fmapnFB Lift) (fmapnFB Do) = fmapn f "fmapnR" forall r f g. fmapnR (fmapnR r f) g = fmapnR r (f . g) "foldn (Return r)" forall r l d a. foldn r l d (Return a) = r a "foldn (Lift c)" forall r l d c. foldn r l d (Lift c) = l (fmap (foldn r l d) c) "foldn (Do m)" forall r l d m. foldn r l d (Do m) = d (fmap (foldn r l d) m) "foldn' (Return r)" forall r l d a. foldn' r l d (Return a) = r a "foldn' (Lift c)" forall r l d c. foldn' r l d (Lift c) = l (fmap (foldn' r l d) c) "foldn' (Do m)" forall r l d m. foldn' r l d (Do m) = d (fmap (foldn' r l d) m) "_bind (Return r)" forall r f. _bind (Return r) f = f r "_bind (Lift c)" forall c f. _bind (Lift c) f = Lift (fmap (\a -> _bind a f) c) "_bind (Do m)" forall m f. _bind (Do m) f = Do (fmap (\a -> _bind a f) m) "_fmap (Return r)" forall r f. _fmap f (Return r) = Return (f r) "_fmap (Lift c)" forall c f. _fmap f (Lift c) = Lift (fmap (_fmap f) c) "_fmap (Do m)" forall m f. _fmap f (Do m) = Do (fmap (_fmap f) m) #-} {- for reference _unfold mk n = Lift $ mk n >>= return . either Return (Do . fmap go) swapObj :: (Monad c, Delta (Modules ts) (Messages ms)) => Object ts c -> Cofree c (Object ts c, Ef ms c a) -> Cofree c (Object ts c, Ef ms c a) swapObj obj = path obj . snd . extract swapEf :: (Monad c, Delta (Modules ts) (Messages ms)) => Ef ms c a -> Cofree c (Object ts c, Ef ms c a) -> Cofree c (Object ts c, Ef ms c a) swapEf code = flip path code . fst . extract branch :: (Monad c, Delta (Modules ts) (Messages ms)) => Cofree c (Object ts c, Ef ms c a) -> Cofree c (Cofree c (Object ts c, Ef ms c a)) branch = duplicate reseedObj :: (Monad c, Delta (Modules ts) (Messages ms)) => Object ts c -> Cofree c (Cofree c (Object ts c, Ef ms c a)) -> Cofree c (Cofree c (Object ts c, Ef ms c a)) reseedObj obj = fmap (swapObj obj) reseedEf :: (Monad c, Delta (Modules ts) (Messages ms)) => Ef ms c a -> Cofree c (Cofree c (Object ts c, Ef ms c a)) -> Cofree c (Cofree c (Object ts c, Ef ms c a)) reseedEf code = fmap (swapEf code) -} {-# INLINE [2] reduce #-} reduce :: (Functor f, Functor c) => Narrative f c a -> (f b -> b) -> (c b -> b) -> (a -> b) -> b reduce n d l r = foldn r l d n {-# INLINE observe #-} observe :: (Functor f, Monad c) => Narrative f c r -> Narrative f c r observe n = Lift $ foldn (return . Return) join (return . Do . fmap Lift) n {-# INLINE never #-} never :: (Applicative f, Applicative c) => Narrative f c r never = loop where loop = Lift $ pure $ Do $ pure loop {-# INLINE uncons #-} uncons :: (Functor f, Monad c) => Narrative f c r -> c (Either r (f (Narrative f c r))) uncons = go where go (Return r) = return (Left r) go (Lift m) = m >>= go go (Do fs) = return (Right fs) zipsWith :: (Monad c, Functor f, Functor g, Functor h) => (forall x y . f x -> g y -> h (x,y)) -> Narrative f c a -> Narrative g c a -> Narrative h c a zipsWith = _zipsWith {-# INLINE _zipsWith #-} _zipsWith :: (Monad c, Functor f, Functor l, Functor r) => (l (Narrative l c a) -> r (Narrative r c a) -> f (Narrative l c a, Narrative r c a)) -> Narrative l c a -> Narrative r c a -> Narrative f c a _zipsWith f x y = Lift $ liftA2 (_zipsWithInternal f) (uncons x) (uncons y) {-# INLINE _zipsWithInternal #-} _zipsWithInternal :: (Monad c, Functor f, Functor l, Functor r) => (l (Narrative l c a) -> r (Narrative r c a) -> f (Narrative l c a, Narrative r c a)) -> Either a (l (Narrative l c a)) -> Either a (r (Narrative r c a)) -> Narrative f c a _zipsWithInternal f = go where go (Left x) _ = Return x go _ (Left y) = Return y go (Right x) (Right y) = Do (fmap (uncurry (_zipsWith f)) (f x y)) {-# INLINE zips #-} zips :: (Monad c, Functor f, Functor g) => Narrative f c a -> Narrative g c a -> Narrative (Compose f g) c a zips = zipsWith (\f g -> Compose (fmap (\x -> fmap (\y -> (x,y)) g) f)) {-# INLINE [2] unzips #-} unzips :: (Functor f, Functor g, Monad c) => Narrative (Compose f g) c r -> Narrative f (Narrative g c) r unzips n = foldn Return (Lift . lift) (\(Compose fgn) -> Do (fmap (Lift . Do . fmap Return) fgn)) n {-# INLINE interleaves #-} interleaves :: (Monad c, Applicative f) => Narrative f c a -> Narrative f c a -> Narrative f c a interleaves = zipsWith (liftA2 (,)) {-# INLINE decompose #-} decompose :: (Functor f, Monad c) => Narrative (Compose c f) c r -> Narrative f c r decompose n = buildn go where go r l d = foldn r l (\(Compose c) -> l $ c >>= return . d) n {-# INLINE [2] implode #-} implode :: (Monad c) => Narrative c c r -> c r implode = foldn return join join {-# INLINE brackets #-} brackets :: (Functor f, MonadResource c) => IO a -> (a -> IO ()) -> (a -> Narrative f c b) -> Narrative f c b brackets alloc free inside = do (key, seed) <- lift (allocate alloc free) buildn $ \r l d -> foldn (\a -> l (release key >> return (r a))) l d (inside seed) {-# INLINE cutoff #-} cutoff :: (Functor f, Monad c) => Int -> Narrative f c r -> Narrative f c (Maybe r) cutoff = go where go 0 _ = return Nothing go i n = do e <- lift $ uncons n case e of Left r -> return (Just r) Right n' -> Do $ fmap (go (i-1)) n' {-# INLINE unfold #-} unfold :: (Functor f, Monad c) => (s -> c (Either r (f s))) -> s -> Narrative f c r unfold mk = go where go n = Lift $ mk n >>= return . either Return (Do . fmap go) {-# INLINE iterTM #-} iterTM :: (Functor f, Monad c, MonadTrans t, Monad (t c)) => (f (t c a) -> t c a) -> Narrative f c a -> t c a iterTM f n = reduce n f (join . lift) return {-# INLINE iterT #-} iterT :: (Functor f, Monad c) => (f (c a) -> c a) -> Narrative f c a -> c a iterT f n = reduce n f join return {-# INLINE [2] distribute #-} distribute :: (Functor f, Monad c, Functor (t c), MonadTrans t, MFunctor t, Monad (t (Narrative f c))) => Narrative f (t c) r -> t (Narrative f c) r distribute n = foldn (lift . return) (join . hoist lift) (join . lift . wrap . fmap return) n {-# INLINE separate #-} separate :: (Monad c, Functor f, Functor g) => Narrative (Sum f g) c r -> Narrative f (Narrative g c) r separate n = buildn go where go r l d = foldn r (l . lift) (\x -> case x of InL fn -> d fn; InR gn -> l (yields gn)) n {-# INLINE unseparate #-} unseparate :: (Monad c, Functor f, Functor g) => Narrative f (Narrative g c) r -> Narrative (Sum f g) c r unseparate n = buildn' go where go r _ d = foldn r (join . maps InR) (d . InL) n -- Walk a narrative n functor steps and then repackage the rest of the narrative as a return value. -- If a return constructor is seen, it is repackaged as a return value. Context steps are not counted. {-# INLINE splitsAt #-} splitsAt :: (Functor f, Monad c) => Int -> Narrative f c r -> Narrative f c (Narrative f c r) splitsAt = go where go i n | i <= 0 = return n go i n = case n of Return _ -> Return n Lift c -> Lift (fmap (go i) c) Do m -> Do (fmap (go (i - 1)) m) -- drops functor layers where the functor is comonadic (to guarantee extractability); -- keeps effect layers. Note that Ef is non-droppable. {-# INLINE drops #-} drops :: (Comonad f, Monad c) => Int -> Narrative f c r -> Narrative f c r drops = go where go i n | i <= 0 = n go i n = case n of Return a -> Return a Lift c -> Lift (fmap (go i) c) Do m -> go (i - 1) (extract m) -- takes n functor layers; keeps effect layers. -- Equivalent to `void . splitsAt n` {-# INLINE takes #-} takes :: (Functor f, Monad c) => Int -> Narrative f c r -> Narrative f c () takes = go where go i _ | i <= 0 = return () go i n = case n of Return _ -> Return () Lift c -> Lift (fmap (go i) c) Do m -> Do (fmap (go (i - 1)) m) -- map a value-preserving transformation over functor layers in a Narrative. {-# INLINE maps #-} maps :: (Functor f, Functor g, Monad c) => (forall x. f x -> g x) -> Narrative f c r -> Narrative g c r maps f n = buildn go where go r l d = foldn r l (d . f) n -- map a value-preserving contextualized transformation over functor layers in a Narrative. {-# INLINE mapsM #-} mapsM :: (Functor f, Functor g, Monad c) => (forall x. f x -> c (g x)) -> Narrative f c r -> Narrative g c r mapsM f n = buildn go where go r l d = foldn r l (l . fmap d . f) n -- Convert functor layers to context layers; map a value-preserving contextualized -- transformation converting from the base Narrative functor to the Narrative's context -- and then implode the result to be rid of the Narrative. {-# INLINE mapsM_ #-} mapsM_ :: (Functor f, Monad c) => (forall x. f x -> c x) -> Narrative f c r -> c r mapsM_ f = implode . maps f {-# INLINE intersperses #-} intersperses :: (Monad c, Monad (t c), MonadTrans t) => t c x -> Narrative (t c) c r -> Narrative (t c) c r intersperses sep n = buildn $ \r l d -> foldn r l (\m -> d (m >>= \a -> sep >> return a)) n -- Embed monadic transformer layers between functor layers where the functor layer is the monadic -- transformer and collapse the resulting Narrative into the functor/transformer. Equivalent to -- `concats . intersperses x` when the type specializes to that expected by concats. {-# INLINE intercalates #-} intercalates :: (Monad c, Monad (t c), MonadTrans t) => t c x -> Narrative (t c) c r -> t c r intercalates sep = go0 where go0 (Return a) = return a go0 (Lift c) = lift c >>= go0 go0 (Do m) = m >>= go1 go1 = foldn return (join . lift) (\m -> join (sep >> m)) -- Collapse functor layers into the embedding context when parent contexts match. {-# INLINE concats #-} concats :: (Functor f, Monad c) => Narrative (Narrative f c) c r -> Narrative f c r concats n = buildn' go where go r l _ = foldn r l join n -- Split functor layers based on a maximum size; produces a Narrative where the functor layers -- are of the same type as the original Narrative. `concats . chunksOf n` == `id` {-# INLINE chunksOf #-} chunksOf :: (Functor f, Monad c) => Int -> Narrative f c r -> Narrative (Narrative f c) c r chunksOf i n = buildn go where go r l d = go' n where go' (Return a) = r a go' (Lift c) = l (fmap go' c) go' (Do fs) = d (Do (fmap (fmap go' . splitsAt (i - 1)) fs)) -- repeat a functor layer ad infinitum {-# INLINE repeats #-} repeats :: (Functor f, Monad c) => f () -> Narrative f c r repeats f = buildn go where go _ l d = go' where go' = l (return (d (fmap (\_ -> go') f))) -- repeat a contextualized layer whose result is a functor layer {-# INLINE repeatsM #-} repeatsM :: (Functor f, Monad c) => c (f ()) -> Narrative f c r repeatsM cf = buildn go where go _ l d = go' where go' = l $ cf >>= return . d . fmap (\_ -> go') -- repeat a functor layer n times {-# INLINE replicates #-} replicates :: (Functor f, Monad c) => Int -> f () -> Narrative f c () replicates n f = fmap (const ()) (splitsAt n (repeats f)) -- repeat a contextualized layer whose result is a functor layer n times {-# INLINE replicatesM #-} replicatesM :: (Functor f, Monad c) => Int -> c (f ()) -> Narrative f c () replicatesM n f = fmap (const ()) (splitsAt n (repeatsM f)) -- repeat a Narrative ad infinitum; equivalent to `forever` {-# INLINE cycles #-} cycles :: (Monad m, Functor f) => Narrative f m r -> Narrative f m s cycles str = loop where loop = str >> loop {-# INLINE runs #-} -- groups in streaming runs :: forall f g c r. (Functor f, Functor g, Monad c) => Narrative (Sum f g) c r -> Narrative (Sum (Narrative f c) (Narrative g c)) c r runs n = buildn' start where {-# INLINE start #-} start r l d = foldn r l (d . msg) n where msg (InL fn) = InL $ goL fn msg (InR gn) = InR $ goR gn goL n = buildn' $ \r' l' d' -> d' $ fmap (foldn (r' . r) l' (\x -> case x of InL fn -> join fn InR gn -> r' (d (fmap (d . InL) (InR gn))) )) n goR n = buildn' $ \r' l' d' -> d' $ fmap (foldn (r' . r) l' (\x -> case x of InL fn -> r' (d (fmap (d . InR) (InL fn))) InR gn -> join gn )) n
grumply/mop
src/Ef.hs
bsd-3-clause
29,585
1
26
8,115
12,058
6,202
5,856
625
6
{-# LANGUAGE TemplateHaskell #-} module Snap.Snaplet.Heist.Internal where import Prelude import Control.Lens import Control.Monad.State import qualified Data.HashMap.Strict as Map import Data.IORef import Data.List import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Heist import Heist.Splices.Cache import System.FilePath.Posix import Snap.Core import Snap.Snaplet data DefaultMode = Compiled | Interpreted ------------------------------------------------------------------------------ -- | The state for the Heist snaplet. To use the Heist snaplet in your app -- include this in your application state and use 'heistInit' to initialize -- it. The type parameter b will typically be the base state type for your -- application. data Heist b = Configuring { _heistConfig :: IORef (HeistConfig (Handler b b), DefaultMode) } | Running { _masterConfig :: HeistConfig (Handler b b) , _heistState :: HeistState (Handler b b) , _heistCTS :: CacheTagState , _defMode :: DefaultMode } makeLenses ''Heist ------------------------------------------------------------------------------ -- | Generic initializer function that allows compiled/interpreted template -- serving to be specified by the caller. gHeistInit :: Handler b (Heist b) () -> FilePath -> SnapletInit b (Heist b) gHeistInit serve templateDir = do makeSnaplet "heist" "" Nothing $ do hs <- heistInitWorker templateDir defaultConfig addRoutes [ ("", serve) , ("heistReload", failIfNotLocal heistReloader) ] return hs where sc = set scLoadTimeSplices defaultLoadTimeSplices mempty defaultConfig = emptyHeistConfig & hcSpliceConfig .~ sc & hcNamespace .~ "" & hcErrorNotBound .~ True ------------------------------------------------------------------------------ -- | Internal worker function used by variants of heistInit. This is -- necessary because of the divide between SnapletInit and Initializer. heistInitWorker :: FilePath -> HeistConfig (Handler b b) -> Initializer b (Heist b) (Heist b) heistInitWorker templateDir initialConfig = do snapletPath <- getSnapletFilePath let tDir = snapletPath </> templateDir templates <- liftIO $ (loadTemplates tDir) >>= either (error . concat) return printInfo $ T.pack $ unwords [ "...loaded" , (show $ Map.size templates) , "templates from" , tDir ] let config = over hcTemplateLocations (<> [loadTemplates tDir]) initialConfig ref <- liftIO $ newIORef (config, Compiled) -- FIXME This runs after all the initializers, but before post init -- hooks registered by other snaplets. addPostInitHook finalLoadHook return $ Configuring ref ------------------------------------------------------------------------------ -- | Hook that converts the Heist type from Configuring to Running at the end -- of initialization. finalLoadHook :: Heist b -> IO (Either Text (Heist b)) finalLoadHook (Configuring ref) = do (hc,dm) <- readIORef ref res <- liftM toTextErrors $ initHeistWithCacheTag hc return $ case res of Left e -> Left e Right (hs,cts) -> Right $ Running hc hs cts dm where toTextErrors = mapBoth (T.pack . intercalate "\n") id finalLoadHook (Running _ _ _ _) = return $ Left "finalLoadHook called while running" mapBoth :: (a -> c) -> (b -> d) -> Either a b -> Either c d mapBoth f _ (Left x) = Left (f x) mapBoth _ f (Right x) = Right (f x) ------------------------------------------------------------------------------ -- | Handler that triggers a template reload. For large sites, this can be -- desireable because it may be much quicker than the full site reload -- provided at the /admin/reload route. This allows you to reload only the -- heist templates This handler is automatically set up by heistInit, but if -- you use heistInit', then you can create your own route with it. heistReloader :: Handler b (Heist b) () heistReloader = do h <- get ehs <- liftIO $ initHeist $ _masterConfig h either (writeText . T.pack . unlines) (\hs -> do writeText "Heist reloaded." modifyMaster $ set heistState hs h) ehs
sopvop/snap
src/Snap/Snaplet/Heist/Internal.hs
bsd-3-clause
4,653
0
13
1,277
950
495
455
77
2
----------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.FramebufferObjects.Queries -- Copyright : (c) Sven Panne, Lars Corbijn 2011-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- ----------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.FramebufferObjects.Queries ( AttachmentObjectType(..), attachmentObjectType, attachmentObject, attachmentTextureLayer, attachmentTextureLevel, attachmentTextureTextureTargetCubeMapFace, attachmentRedSize, attachmentBlueSize, attachmentGreenSize, attachmentAlphaSize, attachmentDepthSize, attachmentStencilSize, renderbufferWidth, renderbufferHeight, renderbufferInternalFormat, renderbufferSamples, renderbufferRedSize, renderbufferBlueSize, renderbufferGreenSize, renderbufferAlphaSize, renderbufferDepthSize, renderbufferStencilSize, ) where import Graphics.Rendering.OpenGL.GL.FramebufferObjects.FramebufferObjectAttachment import Graphics.Rendering.OpenGL.GL.FramebufferObjects.FramebufferTarget import Graphics.Rendering.OpenGL.GL.FramebufferObjects.RenderbufferObject import Graphics.Rendering.OpenGL.GL.FramebufferObjects.RenderbufferTarget import Graphics.Rendering.OpenGL.GL.StateVar import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat import Graphics.Rendering.OpenGL.GL.Texturing.Specification(Level) import Graphics.Rendering.OpenGL.GL.Texturing.TextureObject import Graphics.Rendering.OpenGL.GL.Texturing.TextureTarget import Graphics.Rendering.OpenGL.Raw ----------------------------------------------------------------------------- data GetFramebufferAttachmentPName = AttachmentObjectType | AttachmentObjectName | AttachmentTextureLevel | AttachmentTextureCubeMapFace | AttachmentTextureLayer | AttachmentComponentType | AttachmentColorEncoding | AttachmentRedSize | AttachmentBlueSize | AttachmentGreenSize | AttachmentAlphaSize | AttachmentDepthSize | AttachmentStencilSize marshalGetFBAPName :: GetFramebufferAttachmentPName -> GLenum marshalGetFBAPName x = case x of AttachmentObjectType -> gl_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE AttachmentObjectName -> gl_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME AttachmentTextureLevel -> gl_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL AttachmentTextureCubeMapFace -> gl_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE AttachmentTextureLayer -> gl_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER AttachmentComponentType -> gl_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE -- TODO impement usefull function AttachmentColorEncoding -> gl_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING -- TODO impement usefull function AttachmentRedSize -> gl_FRAMEBUFFER_ATTACHMENT_RED_SIZE AttachmentBlueSize -> gl_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE AttachmentGreenSize -> gl_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE AttachmentAlphaSize -> gl_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE AttachmentDepthSize -> gl_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE AttachmentStencilSize -> gl_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE getFBAPName :: FramebufferAttachment fba => FramebufferTarget -> fba -> (GLint -> a) -> GetFramebufferAttachmentPName -> IO a getFBAPName fbt fba f p = getFBAParameteriv fbt fba f (marshalGetFBAPName p) ----------------------------------------------------------------------------- data AttachmentObjectType = DefaultFramebufferAttachment | TextureAttachment | RenderbufferAttachment deriving ( Eq, Ord, Show ) unmarshalAttachmentObjectType :: GLenum -> Maybe AttachmentObjectType unmarshalAttachmentObjectType x | x == gl_FRAMEBUFFER_DEFAULT = Just DefaultFramebufferAttachment | x == gl_TEXTURE = Just TextureAttachment | x == gl_RENDERBUFFER = Just RenderbufferAttachment | x == gl_NONE = Nothing | otherwise = error $ "unmarshalAttachmentObject: unknown value " ++ show x attachmentObjectType :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar (Maybe AttachmentObjectType) attachmentObjectType fbt fba = makeGettableStateVar $ getFBAPName fbt fba (unmarshalAttachmentObjectType . fromIntegral) AttachmentObjectType -- | tries to retrieve the object that is bound to the attachment point of the -- given framebuffertarget. If the object type of it is None or the default, then -- `Nothing` is returned, otherwise the bound `RenderbufferObject` or `TextureObject` attachmentObject :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar (Maybe (Either RenderbufferObject TextureObject)) attachmentObject fbt fba = makeGettableStateVar getter where getter = do objT <- get $ attachmentObjectType fbt fba case objT of Nothing -> return $ Nothing (Just DefaultFramebufferAttachment) -> return $ Nothing (Just TextureAttachment) -> getObjectName (Right . TextureObject) (Just RenderbufferAttachment) -> getObjectName (Left . RenderbufferObject) getObjectName :: Num n => (n -> Either RenderbufferObject TextureObject) -> IO (Maybe (Either RenderbufferObject TextureObject)) getObjectName con = getFBAPName fbt fba (Just . con . fromIntegral) AttachmentObjectName attachmentTextureLayer :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar GLint attachmentTextureLayer fbt fba = makeGettableStateVar $ getFBAPName fbt fba id AttachmentTextureLayer attachmentTextureLevel :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar Level attachmentTextureLevel fbt fba = makeGettableStateVar $ getFBAPName fbt fba id AttachmentTextureLevel attachmentTextureTextureTargetCubeMapFace :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar TextureTargetCubeMapFace attachmentTextureTextureTargetCubeMapFace fbt fba = makeGettableStateVar $ getFBAPName fbt fba (unmarshalTextureTargetCubeMapFace . fromIntegral) AttachmentTextureLevel ----------------------------------------------------------------------------- attachmentRedSize :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar GLint attachmentRedSize fbt fba = makeGettableStateVar $ getFBAPName fbt fba id AttachmentRedSize attachmentGreenSize :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar GLint attachmentGreenSize fbt fba = makeGettableStateVar $ getFBAPName fbt fba id AttachmentGreenSize attachmentBlueSize :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar GLint attachmentBlueSize fbt fba = makeGettableStateVar $ getFBAPName fbt fba id AttachmentBlueSize attachmentAlphaSize :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar GLint attachmentAlphaSize fbt fba = makeGettableStateVar $ getFBAPName fbt fba id AttachmentAlphaSize attachmentDepthSize :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar GLint attachmentDepthSize fbt fba = makeGettableStateVar $ getFBAPName fbt fba id AttachmentDepthSize attachmentStencilSize :: FramebufferAttachment fba => FramebufferTarget -> fba -> GettableStateVar GLint attachmentStencilSize fbt fba = makeGettableStateVar $ getFBAPName fbt fba id AttachmentStencilSize ----------------------------------------------------------------------------- data GetRenderbufferPName = RenderbufferWidth | RenderbufferHeight | RenderbufferInternalFormat | RenderbufferSamples | RenderbufferRedSize | RenderbufferBlueSize | RenderbufferGreenSize | RenderbufferAlphaSize | RenderbufferDepthSize | RenderbufferStencilSize marshalGetRBPname :: GetRenderbufferPName -> GLenum marshalGetRBPname x = case x of RenderbufferWidth -> gl_RENDERBUFFER_WIDTH RenderbufferHeight -> gl_RENDERBUFFER_HEIGHT RenderbufferInternalFormat -> gl_RENDERBUFFER_INTERNAL_FORMAT RenderbufferSamples -> gl_RENDERBUFFER_SAMPLES RenderbufferRedSize -> gl_RENDERBUFFER_RED_SIZE RenderbufferBlueSize -> gl_RENDERBUFFER_BLUE_SIZE RenderbufferGreenSize -> gl_RENDERBUFFER_GREEN_SIZE RenderbufferAlphaSize -> gl_RENDERBUFFER_ALPHA_SIZE RenderbufferDepthSize -> gl_RENDERBUFFER_DEPTH_SIZE RenderbufferStencilSize -> gl_RENDERBUFFER_STENCIL_SIZE getRBPName :: RenderbufferTarget -> (GLint -> a) -> GetRenderbufferPName -> IO a getRBPName rbt f = getRBParameteriv rbt f . marshalGetRBPname ----------------------------------------------------------------------------- renderbufferWidth :: RenderbufferTarget -> GettableStateVar GLsizei renderbufferWidth rbt = makeGettableStateVar $ getRBPName rbt fromIntegral RenderbufferWidth renderbufferHeight :: RenderbufferTarget -> GettableStateVar GLsizei renderbufferHeight rbt = makeGettableStateVar $ getRBPName rbt fromIntegral RenderbufferHeight renderbufferInternalFormat :: RenderbufferTarget -> GettableStateVar PixelInternalFormat renderbufferInternalFormat rbt = makeGettableStateVar $ getRBPName rbt unmarshalPixelInternalFormat RenderbufferInternalFormat renderbufferSamples :: RenderbufferTarget -> GettableStateVar Samples renderbufferSamples rbt = makeGettableStateVar $ getRBPName rbt (Samples . fromIntegral) RenderbufferSamples renderbufferRedSize :: RenderbufferTarget -> GettableStateVar GLint renderbufferRedSize rbt = makeGettableStateVar $ getRBPName rbt id RenderbufferRedSize renderbufferGreenSize :: RenderbufferTarget -> GettableStateVar GLint renderbufferGreenSize rbt = makeGettableStateVar $ getRBPName rbt id RenderbufferGreenSize renderbufferBlueSize :: RenderbufferTarget -> GettableStateVar GLint renderbufferBlueSize rbt = makeGettableStateVar $ getRBPName rbt id RenderbufferBlueSize renderbufferAlphaSize :: RenderbufferTarget -> GettableStateVar GLint renderbufferAlphaSize rbt = makeGettableStateVar $ getRBPName rbt id RenderbufferAlphaSize renderbufferDepthSize :: RenderbufferTarget -> GettableStateVar GLint renderbufferDepthSize rbt = makeGettableStateVar $ getRBPName rbt id RenderbufferDepthSize renderbufferStencilSize :: RenderbufferTarget -> GettableStateVar GLint renderbufferStencilSize rbt = makeGettableStateVar $ getRBPName rbt id RenderbufferStencilSize
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/FramebufferObjects/Queries.hs
bsd-3-clause
10,404
0
14
1,382
1,712
899
813
173
13
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ViewPatterns #-} module Servant.Common.BaseUrl ( -- * types BaseUrl (..) , InvalidBaseUrlException , Scheme (..) -- * functions , parseBaseUrl , showBaseUrl ) where import Control.Monad.Catch (MonadThrow, throwM, Exception) import Data.List import Data.Typeable import GHC.Generics import Network.URI import Safe import Text.Read -- | URI scheme to use data Scheme = Http -- ^ http:// | Https -- ^ https:// deriving (Show, Eq, Ord, Generic) -- | Simple data type to represent the target of HTTP requests -- for servant's automatically-generated clients. data BaseUrl = BaseUrl { baseUrlScheme :: Scheme -- ^ URI scheme to use , baseUrlHost :: String -- ^ host (eg "haskell.org") , baseUrlPort :: Int -- ^ port (eg 80) } deriving (Show, Eq, Ord, Generic) showBaseUrl :: BaseUrl -> String showBaseUrl (BaseUrl urlscheme host port) = schemeString ++ "//" ++ host ++ portString where schemeString = case urlscheme of Http -> "http:" Https -> "https:" portString = case (urlscheme, port) of (Http, 80) -> "" (Https, 443) -> "" _ -> ":" ++ show port data InvalidBaseUrlException = InvalidBaseUrlException String deriving (Show, Typeable) instance Exception InvalidBaseUrlException parseBaseUrl :: MonadThrow m => String -> m BaseUrl parseBaseUrl s = case parseURI (removeTrailingSlash s) of -- This is a rather hacky implementation and should be replaced with something -- implemented in attoparsec (which is already a dependency anyhow (via aeson)). Just (URI "http:" (Just (URIAuth "" host (':' : (readMaybe -> Just port)))) "" "" "") -> return (BaseUrl Http host port) Just (URI "http:" (Just (URIAuth "" host "")) "" "" "") -> return (BaseUrl Http host 80) Just (URI "https:" (Just (URIAuth "" host (':' : (readMaybe -> Just port)))) "" "" "") -> return (BaseUrl Https host port) Just (URI "https:" (Just (URIAuth "" host "")) "" "" "") -> return (BaseUrl Https host 443) _ -> if "://" `isInfixOf` s then throwM (InvalidBaseUrlException $ "Invalid base URL: " ++ s) else parseBaseUrl ("http://" ++ s) where removeTrailingSlash str = case lastMay str of Just '/' -> init str _ -> str
meiersi/ghcjs-servant-client
src/Servant/Common/BaseUrl.hs
bsd-3-clause
2,328
0
19
514
669
360
309
53
7
module Inter.Bank where -- -- $Id$ import Control.Punkt import Control.Types import qualified System.Posix import System.Time import qualified Inter.Param as P import qualified Inter.Store import Util.Datei bank :: P.Type -> IO String bank p = do ( pid , minfile ) <- Inter.Store.store Inter.Store.Input p ( _ , minstfile ) <- Inter.Store.store Inter.Store.Instant p mrepfile <- case P.mresult p of Just x | x /= Pending -> do ( pid , mrepfile ) <- Inter.Store.store Inter.Store.Report p return $ mrepfile _ -> return Nothing bepunkteStudentDB (P.ident p) (P.anr p) ( minstfile ) (P.mresult p) (P.highscore p) ( minfile ) ( mrepfile ) case P.mresult p of Nothing -> do return "(kein Resultat => kein Eintrag)" Just res -> do time <- zeit let msg = logline time pid p res d <- datum let logcgi = Datei { pfad = [ "autotool", "log" ] ++ d , name = "CGI" , extension = "" } anhaengen logcgi msg return msg logline time pid p res = unwords [ time , "(", pid, ")" , "cgi-" ++ P.smatrikel p , "(", P.smatrikel p, ")" , P.subject p , ":" , result_string res , "\n" ] result_string :: Wert -> String result_string mres = case mres of Pending -> "Pending" No -> "NO" Okay {} -> "OK # Size: " ++ show (size mres) ++ " Punkte: " ++ show (punkte mres) datum :: IO [ String ] datum = do clock <- getClockTime cal <- toCalendarTime clock return [ show $ ctYear cal , show $ ctMonth cal , show $ ctDay cal ] zeit :: IO String zeit = do clock <- getClockTime cal <- toCalendarTime clock return $ calendarTimeToString cal
Erdwolf/autotool-bonn
trial/src/Inter/Bank.hs
gpl-2.0
1,800
11
20
575
635
322
313
58
3
module Distribution.Server.Framework.ServerEnv where import Distribution.Server.Framework.BlobStorage (BlobStorage) import Distribution.Server.Framework.Logging (Verbosity) import Distribution.Server.Framework.Cron (Cron) import Distribution.Server.Framework.Templating (TemplatesMode) import qualified Network.URI as URI import qualified Hackage.Security.Util.Path as Sec -- | The internal server environment as used by 'HackageFeature's. -- -- It contains various bits of static information (and handles of -- server-global objects) that are needed by the implementations of -- some 'HackageFeature's. -- data ServerEnv = ServerEnv { -- | The location of the server's static files serverStaticDir :: FilePath, -- | The location of the server's template files serverTemplatesDir :: FilePath, -- | The location of TUF data (signed root info, private keys) serverTUFDir :: Sec.AbsolutePath, -- | Default templates mode serverTemplatesMode :: TemplatesMode, -- | The location of the server's state directory. This is where the -- server's persistent state is kept, e.g. using ACID state. serverStateDir :: FilePath, -- | The blob store is a specialised provider of persistent state for -- larger relatively-static blobs of data (e.g. uploaded tarballs). serverBlobStore :: BlobStorage, -- | A cron job service serverCron :: Cron, -- | The temporary directory the server has been configured to use. -- Use it for temp files such as when validating uploads. serverTmpDir :: FilePath, -- | The base URI of the server, just the hostname (and perhaps port). -- Use this if you need to construct absolute URIs pointing to the -- current server (e.g. as required in RSS feeds). serverBaseURI :: URI.URI, -- | A tunable parameter for cache policy. Setting this parameter high -- during bulk imports can very significantly improve performance. During -- normal operation it probably doesn't help much. -- By delaying cache updates we can sometimes save some effort: caches are -- based on a bit of changing state and if that state is updated more -- frequently than the time taken to update the cache, then we don't have -- to do as many cache updates as we do state updates. By artificially -- increasing the time taken to update the cache we can push this further. serverCacheDelay :: Int, serverVerbosity :: Verbosity }
ocharles/hackage-server
Distribution/Server/Framework/ServerEnv.hs
bsd-3-clause
2,467
0
9
500
181
131
50
19
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="hi-IN"> <title>All In One Notes Add-On</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/allinonenotes/src/main/javahelp/org/zaproxy/zap/extension/allinonenotes/resources/help_hi_IN/helpset_hi_IN.hs
apache-2.0
968
77
67
159
417
211
206
-1
-1
module SDL.Raw.Video ( -- * Display and Window Management createWindow, createWindowAndRenderer, createWindowFrom, destroyWindow, disableScreenSaver, enableScreenSaver, glBindTexture, glCreateContext, glDeleteContext, glExtensionSupported, glGetAttribute, glGetCurrentContext, glGetCurrentWindow, glGetDrawableSize, glGetProcAddress, glGetSwapInterval, glLoadLibrary, glMakeCurrent, glResetAttributes, glSetAttribute, glSetSwapInterval, glSwapWindow, glUnbindTexture, glUnloadLibrary, getClosestDisplayMode, getCurrentDisplayMode, getCurrentVideoDriver, getDesktopDisplayMode, getDisplayBounds, getDisplayMode, getDisplayName, getNumDisplayModes, getNumVideoDisplays, getNumVideoDrivers, getVideoDriver, getWindowBrightness, getWindowData, getWindowDisplayIndex, getWindowDisplayMode, getWindowFlags, getWindowFromID, getWindowGammaRamp, getWindowGrab, getWindowID, getWindowMaximumSize, getWindowMinimumSize, getWindowPixelFormat, getWindowPosition, getWindowSize, getWindowSurface, getWindowTitle, hideWindow, isScreenSaverEnabled, maximizeWindow, minimizeWindow, raiseWindow, restoreWindow, setWindowBordered, setWindowBrightness, setWindowData, setWindowDisplayMode, setWindowFullscreen, setWindowGammaRamp, setWindowGrab, setWindowIcon, setWindowMaximumSize, setWindowMinimumSize, setWindowPosition, setWindowSize, setWindowTitle, showMessageBox, showSimpleMessageBox, showWindow, updateWindowSurface, updateWindowSurfaceRects, videoInit, videoQuit, -- * 2D Accelerated Rendering createRenderer, createSoftwareRenderer, createTexture, createTextureFromSurface, destroyRenderer, destroyTexture, getNumRenderDrivers, getRenderDrawBlendMode, getRenderDrawColor, getRenderDriverInfo, getRenderTarget, getRenderer, getRendererInfo, getRendererOutputSize, getTextureAlphaMod, getTextureBlendMode, getTextureColorMod, lockTexture, queryTexture, renderClear, renderCopy, renderCopyEx, renderDrawLine, renderDrawLines, renderDrawPoint, renderDrawPoints, renderDrawRect, renderDrawRects, renderFillRect, renderFillRects, renderGetClipRect, renderGetLogicalSize, renderGetScale, renderGetViewport, renderPresent, renderReadPixels, renderSetClipRect, renderSetLogicalSize, renderSetScale, renderSetViewport, renderTargetSupported, setRenderDrawBlendMode, setRenderDrawColor, setRenderTarget, setTextureAlphaMod, setTextureBlendMode, setTextureColorMod, unlockTexture, updateTexture, updateYUVTexture, -- * Pixel Formats and Conversion Routines allocFormat, allocPalette, calculateGammaRamp, freeFormat, freePalette, getPixelFormatName, getRGB, getRGBA, mapRGB, mapRGBA, masksToPixelFormatEnum, pixelFormatEnumToMasks, setPaletteColors, setPixelFormatPalette, -- * Rectangle Functions enclosePoints, hasIntersection, intersectRect, intersectRectAndLine, unionRect, -- * Surface Creation and Simple Drawing blitScaled, blitSurface, convertPixels, convertSurface, convertSurfaceFormat, createRGBSurface, createRGBSurfaceFrom, fillRect, fillRects, freeSurface, getClipRect, getColorKey, getSurfaceAlphaMod, getSurfaceBlendMode, getSurfaceColorMod, loadBMP, loadBMP_RW, lockSurface, lowerBlit, lowerBlitScaled, saveBMP, saveBMP_RW, setClipRect, setColorKey, setSurfaceAlphaMod, setSurfaceBlendMode, setSurfaceColorMod, setSurfacePalette, setSurfaceRLE, unlockSurface, -- * Platform-specific Window Management getWindowWMInfo, -- * Clipboard Handling getClipboardText, hasClipboardText, setClipboardText ) where import Control.Monad.IO.Class import Data.Word import Foreign.C.String import Foreign.C.Types import Foreign.Ptr import SDL.Raw.Enum import SDL.Raw.Filesystem import SDL.Raw.Types foreign import ccall "SDL.h SDL_CreateWindow" createWindow' :: CString -> CInt -> CInt -> CInt -> CInt -> Word32 -> IO Window foreign import ccall "SDL.h SDL_CreateWindowAndRenderer" createWindowAndRenderer' :: CInt -> CInt -> Word32 -> Ptr Window -> Ptr Renderer -> IO CInt foreign import ccall "SDL.h SDL_CreateWindowFrom" createWindowFrom' :: Ptr () -> IO Window foreign import ccall "SDL.h SDL_DestroyWindow" destroyWindow' :: Window -> IO () foreign import ccall "SDL.h SDL_DisableScreenSaver" disableScreenSaver' :: IO () foreign import ccall "SDL.h SDL_EnableScreenSaver" enableScreenSaver' :: IO () foreign import ccall "SDL.h SDL_GL_BindTexture" glBindTexture' :: Texture -> Ptr CFloat -> Ptr CFloat -> IO CInt foreign import ccall "SDL.h SDL_GL_CreateContext" glCreateContext' :: Window -> IO GLContext foreign import ccall "SDL.h SDL_GL_DeleteContext" glDeleteContext' :: GLContext -> IO () foreign import ccall "SDL.h SDL_GL_ExtensionSupported" glExtensionSupported' :: CString -> IO Bool foreign import ccall "SDL.h SDL_GL_GetAttribute" glGetAttribute' :: GLattr -> Ptr CInt -> IO CInt foreign import ccall "SDL.h SDL_GL_GetCurrentContext" glGetCurrentContext' :: IO GLContext foreign import ccall "SDL.h SDL_GL_GetCurrentWindow" glGetCurrentWindow' :: IO Window foreign import ccall "SDL.h SDL_GL_GetDrawableSize" glGetDrawableSize' :: Window -> Ptr CInt -> Ptr CInt -> IO () foreign import ccall "SDL.h SDL_GL_GetProcAddress" glGetProcAddress' :: CString -> IO (Ptr ()) foreign import ccall "SDL.h SDL_GL_GetSwapInterval" glGetSwapInterval' :: IO CInt foreign import ccall "SDL.h SDL_GL_LoadLibrary" glLoadLibrary' :: CString -> IO CInt foreign import ccall "SDL.h SDL_GL_MakeCurrent" glMakeCurrent' :: Window -> GLContext -> IO CInt foreign import ccall "SDL.h SDL_GL_ResetAttributes" glResetAttributes' :: IO () foreign import ccall "SDL.h SDL_GL_SetAttribute" glSetAttribute' :: GLattr -> CInt -> IO CInt foreign import ccall "SDL.h SDL_GL_SetSwapInterval" glSetSwapInterval' :: CInt -> IO CInt foreign import ccall "SDL.h SDL_GL_SwapWindow" glSwapWindow' :: Window -> IO () foreign import ccall "SDL.h SDL_GL_UnbindTexture" glUnbindTexture' :: Texture -> IO CInt foreign import ccall "SDL.h SDL_GL_UnloadLibrary" glUnloadLibrary' :: IO () foreign import ccall "SDL.h SDL_GetClosestDisplayMode" getClosestDisplayMode' :: CInt -> Ptr DisplayMode -> Ptr DisplayMode -> IO (Ptr DisplayMode) foreign import ccall "SDL.h SDL_GetCurrentDisplayMode" getCurrentDisplayMode' :: CInt -> Ptr DisplayMode -> IO CInt foreign import ccall "SDL.h SDL_GetCurrentVideoDriver" getCurrentVideoDriver' :: IO CString foreign import ccall "SDL.h SDL_GetDesktopDisplayMode" getDesktopDisplayMode' :: CInt -> Ptr DisplayMode -> IO CInt foreign import ccall "SDL.h SDL_GetDisplayBounds" getDisplayBounds' :: CInt -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_GetDisplayMode" getDisplayMode' :: CInt -> CInt -> Ptr DisplayMode -> IO CInt foreign import ccall "SDL.h SDL_GetDisplayName" getDisplayName' :: CInt -> IO CString foreign import ccall "SDL.h SDL_GetNumDisplayModes" getNumDisplayModes' :: CInt -> IO CInt foreign import ccall "SDL.h SDL_GetNumVideoDisplays" getNumVideoDisplays' :: IO CInt foreign import ccall "SDL.h SDL_GetNumVideoDrivers" getNumVideoDrivers' :: IO CInt foreign import ccall "SDL.h SDL_GetVideoDriver" getVideoDriver' :: CInt -> IO CString foreign import ccall "SDL.h SDL_GetWindowBrightness" getWindowBrightness' :: Window -> IO CFloat foreign import ccall "SDL.h SDL_GetWindowData" getWindowData' :: Window -> CString -> IO (Ptr ()) foreign import ccall "SDL.h SDL_GetWindowDisplayIndex" getWindowDisplayIndex' :: Window -> IO CInt foreign import ccall "SDL.h SDL_GetWindowDisplayMode" getWindowDisplayMode' :: Window -> Ptr DisplayMode -> IO CInt foreign import ccall "SDL.h SDL_GetWindowFlags" getWindowFlags' :: Window -> IO Word32 foreign import ccall "SDL.h SDL_GetWindowFromID" getWindowFromID' :: Word32 -> IO Window foreign import ccall "SDL.h SDL_GetWindowGammaRamp" getWindowGammaRamp' :: Window -> Ptr Word16 -> Ptr Word16 -> Ptr Word16 -> IO CInt foreign import ccall "SDL.h SDL_GetWindowGrab" getWindowGrab' :: Window -> IO Bool foreign import ccall "SDL.h SDL_GetWindowID" getWindowID' :: Window -> IO Word32 foreign import ccall "SDL.h SDL_GetWindowMaximumSize" getWindowMaximumSize' :: Window -> Ptr CInt -> Ptr CInt -> IO () foreign import ccall "SDL.h SDL_GetWindowMinimumSize" getWindowMinimumSize' :: Window -> Ptr CInt -> Ptr CInt -> IO () foreign import ccall "SDL.h SDL_GetWindowPixelFormat" getWindowPixelFormat' :: Window -> IO Word32 foreign import ccall "SDL.h SDL_GetWindowPosition" getWindowPosition' :: Window -> Ptr CInt -> Ptr CInt -> IO () foreign import ccall "SDL.h SDL_GetWindowSize" getWindowSize' :: Window -> Ptr CInt -> Ptr CInt -> IO () foreign import ccall "SDL.h SDL_GetWindowSurface" getWindowSurface' :: Window -> IO (Ptr Surface) foreign import ccall "SDL.h SDL_GetWindowTitle" getWindowTitle' :: Window -> IO CString foreign import ccall "SDL.h SDL_HideWindow" hideWindow' :: Window -> IO () foreign import ccall "SDL.h SDL_IsScreenSaverEnabled" isScreenSaverEnabled' :: IO Bool foreign import ccall "SDL.h SDL_MaximizeWindow" maximizeWindow' :: Window -> IO () foreign import ccall "SDL.h SDL_MinimizeWindow" minimizeWindow' :: Window -> IO () foreign import ccall "SDL.h SDL_RaiseWindow" raiseWindow' :: Window -> IO () foreign import ccall "SDL.h SDL_RestoreWindow" restoreWindow' :: Window -> IO () foreign import ccall "SDL.h SDL_SetWindowBordered" setWindowBordered' :: Window -> Bool -> IO () foreign import ccall "SDL.h SDL_SetWindowBrightness" setWindowBrightness' :: Window -> CFloat -> IO CInt foreign import ccall "SDL.h SDL_SetWindowData" setWindowData' :: Window -> CString -> Ptr () -> IO (Ptr ()) foreign import ccall "SDL.h SDL_SetWindowDisplayMode" setWindowDisplayMode' :: Window -> Ptr DisplayMode -> IO CInt foreign import ccall "SDL.h SDL_SetWindowFullscreen" setWindowFullscreen' :: Window -> Word32 -> IO CInt foreign import ccall "SDL.h SDL_SetWindowGammaRamp" setWindowGammaRamp' :: Window -> Ptr Word16 -> Ptr Word16 -> Ptr Word16 -> IO CInt foreign import ccall "SDL.h SDL_SetWindowGrab" setWindowGrab' :: Window -> Bool -> IO () foreign import ccall "SDL.h SDL_SetWindowIcon" setWindowIcon' :: Window -> Ptr Surface -> IO () foreign import ccall "SDL.h SDL_SetWindowMaximumSize" setWindowMaximumSize' :: Window -> CInt -> CInt -> IO () foreign import ccall "SDL.h SDL_SetWindowMinimumSize" setWindowMinimumSize' :: Window -> CInt -> CInt -> IO () foreign import ccall "SDL.h SDL_SetWindowPosition" setWindowPosition' :: Window -> CInt -> CInt -> IO () foreign import ccall "SDL.h SDL_SetWindowSize" setWindowSize' :: Window -> CInt -> CInt -> IO () foreign import ccall "SDL.h SDL_SetWindowTitle" setWindowTitle' :: Window -> CString -> IO () foreign import ccall "SDL.h SDL_ShowMessageBox" showMessageBox' :: Ptr MessageBoxData -> Ptr CInt -> IO CInt foreign import ccall "SDL.h SDL_ShowSimpleMessageBox" showSimpleMessageBox' :: Word32 -> CString -> CString -> Window -> IO CInt foreign import ccall "SDL.h SDL_ShowWindow" showWindow' :: Window -> IO () foreign import ccall "SDL.h SDL_UpdateWindowSurface" updateWindowSurface' :: Window -> IO CInt foreign import ccall "SDL.h SDL_UpdateWindowSurfaceRects" updateWindowSurfaceRects' :: Window -> Ptr Rect -> CInt -> IO CInt foreign import ccall "SDL.h SDL_VideoInit" videoInit' :: CString -> IO CInt foreign import ccall "SDL.h SDL_VideoQuit" videoQuit' :: IO () foreign import ccall "SDL.h SDL_CreateRenderer" createRenderer' :: Window -> CInt -> Word32 -> IO Renderer foreign import ccall "SDL.h SDL_CreateSoftwareRenderer" createSoftwareRenderer' :: Ptr Surface -> IO Renderer foreign import ccall "SDL.h SDL_CreateTexture" createTexture' :: Renderer -> Word32 -> CInt -> CInt -> CInt -> IO Texture foreign import ccall "SDL.h SDL_CreateTextureFromSurface" createTextureFromSurface' :: Renderer -> Ptr Surface -> IO Texture foreign import ccall "SDL.h SDL_DestroyRenderer" destroyRenderer' :: Renderer -> IO () foreign import ccall "SDL.h SDL_DestroyTexture" destroyTexture' :: Texture -> IO () foreign import ccall "SDL.h SDL_GetNumRenderDrivers" getNumRenderDrivers' :: IO CInt foreign import ccall "SDL.h SDL_GetRenderDrawBlendMode" getRenderDrawBlendMode' :: Renderer -> Ptr BlendMode -> IO Int foreign import ccall "SDL.h SDL_GetRenderDrawColor" getRenderDrawColor' :: Renderer -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO CInt foreign import ccall "SDL.h SDL_GetRenderDriverInfo" getRenderDriverInfo' :: CInt -> Ptr RendererInfo -> IO CInt foreign import ccall "SDL.h SDL_GetRenderTarget" getRenderTarget' :: Renderer -> IO Texture foreign import ccall "SDL.h SDL_GetRenderer" getRenderer' :: Window -> IO Renderer foreign import ccall "SDL.h SDL_GetRendererInfo" getRendererInfo' :: Renderer -> Ptr RendererInfo -> IO CInt foreign import ccall "SDL.h SDL_GetRendererOutputSize" getRendererOutputSize' :: Renderer -> Ptr CInt -> Ptr CInt -> IO CInt foreign import ccall "SDL.h SDL_GetTextureAlphaMod" getTextureAlphaMod' :: Texture -> Ptr Word8 -> IO CInt foreign import ccall "SDL.h SDL_GetTextureBlendMode" getTextureBlendMode' :: Texture -> Ptr BlendMode -> IO CInt foreign import ccall "SDL.h SDL_GetTextureColorMod" getTextureColorMod' :: Texture -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO CInt foreign import ccall "SDL.h SDL_LockTexture" lockTexture' :: Texture -> Ptr Rect -> Ptr (Ptr ()) -> Ptr CInt -> IO CInt foreign import ccall "SDL.h SDL_QueryTexture" queryTexture' :: Texture -> Ptr Word32 -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO CInt foreign import ccall "SDL.h SDL_RenderClear" renderClear' :: Renderer -> IO CInt foreign import ccall "SDL.h SDL_RenderCopy" renderCopy' :: Renderer -> Texture -> Ptr Rect -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_RenderCopyEx" renderCopyEx' :: Renderer -> Texture -> Ptr Rect -> Ptr Rect -> CDouble -> Ptr Point -> RendererFlip -> IO CInt foreign import ccall "SDL.h SDL_RenderDrawLine" renderDrawLine' :: Renderer -> CInt -> CInt -> CInt -> CInt -> IO CInt foreign import ccall "SDL.h SDL_RenderDrawLines" renderDrawLines' :: Renderer -> Ptr Point -> CInt -> IO CInt foreign import ccall "SDL.h SDL_RenderDrawPoint" renderDrawPoint' :: Renderer -> CInt -> CInt -> IO CInt foreign import ccall "SDL.h SDL_RenderDrawPoints" renderDrawPoints' :: Renderer -> Ptr Point -> CInt -> IO CInt foreign import ccall "SDL.h SDL_RenderDrawRect" renderDrawRect' :: Renderer -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_RenderDrawRects" renderDrawRects' :: Renderer -> Ptr Rect -> CInt -> IO CInt foreign import ccall "SDL.h SDL_RenderFillRect" renderFillRect' :: Renderer -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_RenderFillRects" renderFillRects' :: Renderer -> Ptr Rect -> CInt -> IO CInt foreign import ccall "SDL.h SDL_RenderGetClipRect" renderGetClipRect' :: Renderer -> Ptr Rect -> IO () foreign import ccall "SDL.h SDL_RenderGetLogicalSize" renderGetLogicalSize' :: Renderer -> Ptr CInt -> Ptr CInt -> IO () foreign import ccall "SDL.h SDL_RenderGetScale" renderGetScale' :: Renderer -> Ptr CFloat -> Ptr CFloat -> IO () foreign import ccall "SDL.h SDL_RenderGetViewport" renderGetViewport' :: Renderer -> Ptr Rect -> IO () foreign import ccall "SDL.h SDL_RenderPresent" renderPresent' :: Renderer -> IO () foreign import ccall "SDL.h SDL_RenderReadPixels" renderReadPixels' :: Renderer -> Ptr Rect -> Word32 -> Ptr () -> CInt -> IO CInt foreign import ccall "SDL.h SDL_RenderSetClipRect" renderSetClipRect' :: Renderer -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_RenderSetLogicalSize" renderSetLogicalSize' :: Renderer -> CInt -> CInt -> IO CInt foreign import ccall "SDL.h SDL_RenderSetScale" renderSetScale' :: Renderer -> CFloat -> CFloat -> IO CInt foreign import ccall "SDL.h SDL_RenderSetViewport" renderSetViewport' :: Renderer -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_RenderTargetSupported" renderTargetSupported' :: Renderer -> IO Bool foreign import ccall "SDL.h SDL_SetRenderDrawBlendMode" setRenderDrawBlendMode' :: Renderer -> BlendMode -> IO CInt foreign import ccall "SDL.h SDL_SetRenderDrawColor" setRenderDrawColor' :: Renderer -> Word8 -> Word8 -> Word8 -> Word8 -> IO CInt foreign import ccall "SDL.h SDL_SetRenderTarget" setRenderTarget' :: Renderer -> Texture -> IO CInt foreign import ccall "SDL.h SDL_SetTextureAlphaMod" setTextureAlphaMod' :: Texture -> Word8 -> IO CInt foreign import ccall "SDL.h SDL_SetTextureBlendMode" setTextureBlendMode' :: Texture -> BlendMode -> IO CInt foreign import ccall "SDL.h SDL_SetTextureColorMod" setTextureColorMod' :: Texture -> Word8 -> Word8 -> Word8 -> IO CInt foreign import ccall "SDL.h SDL_UnlockTexture" unlockTexture' :: Texture -> IO () foreign import ccall "SDL.h SDL_UpdateTexture" updateTexture' :: Texture -> Ptr Rect -> Ptr () -> CInt -> IO CInt foreign import ccall "SDL.h SDL_UpdateYUVTexture" updateYUVTexture' :: Texture -> Ptr Rect -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> IO CInt foreign import ccall "SDL.h SDL_AllocFormat" allocFormat' :: Word32 -> IO (Ptr PixelFormat) foreign import ccall "SDL.h SDL_AllocPalette" allocPalette' :: CInt -> IO (Ptr Palette) foreign import ccall "SDL.h SDL_CalculateGammaRamp" calculateGammaRamp' :: CFloat -> Ptr Word16 -> IO () foreign import ccall "SDL.h SDL_FreeFormat" freeFormat' :: Ptr PixelFormat -> IO () foreign import ccall "SDL.h SDL_FreePalette" freePalette' :: Ptr Palette -> IO () foreign import ccall "SDL.h SDL_GetPixelFormatName" getPixelFormatName' :: Word32 -> IO CString foreign import ccall "SDL.h SDL_GetRGB" getRGB' :: Word32 -> Ptr PixelFormat -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO () foreign import ccall "SDL.h SDL_GetRGBA" getRGBA' :: Word32 -> Ptr PixelFormat -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO () foreign import ccall "SDL.h SDL_MapRGB" mapRGB' :: Ptr PixelFormat -> Word8 -> Word8 -> Word8 -> IO Word32 foreign import ccall "SDL.h SDL_MapRGBA" mapRGBA' :: Ptr PixelFormat -> Word8 -> Word8 -> Word8 -> Word8 -> IO Word32 foreign import ccall "SDL.h SDL_MasksToPixelFormatEnum" masksToPixelFormatEnum' :: CInt -> Word32 -> Word32 -> Word32 -> Word32 -> IO Word32 foreign import ccall "SDL.h SDL_PixelFormatEnumToMasks" pixelFormatEnumToMasks' :: Word32 -> Ptr CInt -> Ptr Word32 -> Ptr Word32 -> Ptr Word32 -> Ptr Word32 -> IO Bool foreign import ccall "SDL.h SDL_SetPaletteColors" setPaletteColors' :: Ptr Palette -> Ptr Color -> CInt -> CInt -> IO CInt foreign import ccall "SDL.h SDL_SetPixelFormatPalette" setPixelFormatPalette' :: Ptr PixelFormat -> Ptr Palette -> IO CInt foreign import ccall "SDL.h SDL_EnclosePoints" enclosePoints' :: Ptr Point -> CInt -> Ptr Rect -> Ptr Rect -> IO Bool foreign import ccall "SDL.h SDL_HasIntersection" hasIntersection' :: Ptr Rect -> Ptr Rect -> IO Bool foreign import ccall "SDL.h SDL_IntersectRect" intersectRect' :: Ptr Rect -> Ptr Rect -> Ptr Rect -> IO Bool foreign import ccall "SDL.h SDL_IntersectRectAndLine" intersectRectAndLine' :: Ptr Rect -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO Bool foreign import ccall "SDL.h SDL_UnionRect" unionRect' :: Ptr Rect -> Ptr Rect -> Ptr Rect -> IO () foreign import ccall "SDL.h SDL_UpperBlitScaled" blitScaled' :: Ptr Surface -> Ptr Rect -> Ptr Surface -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_UpperBlit" blitSurface' :: Ptr Surface -> Ptr Rect -> Ptr Surface -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_ConvertPixels" convertPixels' :: CInt -> CInt -> Word32 -> Ptr () -> CInt -> Word32 -> Ptr () -> CInt -> IO CInt foreign import ccall "SDL.h SDL_ConvertSurface" convertSurface' :: Ptr Surface -> Ptr PixelFormat -> Word32 -> IO (Ptr Surface) foreign import ccall "SDL.h SDL_ConvertSurfaceFormat" convertSurfaceFormat' :: Ptr Surface -> Word32 -> Word32 -> IO (Ptr Surface) foreign import ccall "SDL.h SDL_CreateRGBSurface" createRGBSurface' :: Word32 -> CInt -> CInt -> CInt -> Word32 -> Word32 -> Word32 -> Word32 -> IO (Ptr Surface) foreign import ccall "SDL.h SDL_CreateRGBSurfaceFrom" createRGBSurfaceFrom' :: Ptr () -> CInt -> CInt -> CInt -> CInt -> Word32 -> Word32 -> Word32 -> Word32 -> IO (Ptr Surface) foreign import ccall "SDL.h SDL_FillRect" fillRect' :: Ptr Surface -> Ptr Rect -> Word32 -> IO CInt foreign import ccall "SDL.h SDL_FillRects" fillRects' :: Ptr Surface -> Ptr Rect -> CInt -> Word32 -> IO CInt foreign import ccall "SDL.h SDL_FreeSurface" freeSurface' :: Ptr Surface -> IO () foreign import ccall "SDL.h SDL_GetClipRect" getClipRect' :: Ptr Surface -> Ptr Rect -> IO () foreign import ccall "SDL.h SDL_GetColorKey" getColorKey' :: Ptr Surface -> Ptr Word32 -> IO CInt foreign import ccall "SDL.h SDL_GetSurfaceAlphaMod" getSurfaceAlphaMod' :: Ptr Surface -> Ptr Word8 -> IO CInt foreign import ccall "SDL.h SDL_GetSurfaceBlendMode" getSurfaceBlendMode' :: Ptr Surface -> Ptr BlendMode -> IO CInt foreign import ccall "SDL.h SDL_GetSurfaceColorMod" getSurfaceColorMod' :: Ptr Surface -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO CInt foreign import ccall "SDL.h SDL_LoadBMP_RW" loadBMP_RW' :: Ptr RWops -> CInt -> IO (Ptr Surface) foreign import ccall "SDL.h SDL_LockSurface" lockSurface' :: Ptr Surface -> IO CInt foreign import ccall "SDL.h SDL_LowerBlit" lowerBlit' :: Ptr Surface -> Ptr Rect -> Ptr Surface -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_LowerBlitScaled" lowerBlitScaled' :: Ptr Surface -> Ptr Rect -> Ptr Surface -> Ptr Rect -> IO CInt foreign import ccall "SDL.h SDL_SaveBMP_RW" saveBMP_RW' :: Ptr Surface -> Ptr RWops -> CInt -> IO CInt foreign import ccall "SDL.h SDL_SetClipRect" setClipRect' :: Ptr Surface -> Ptr Rect -> IO Bool foreign import ccall "SDL.h SDL_SetColorKey" setColorKey' :: Ptr Surface -> CInt -> Word32 -> IO CInt foreign import ccall "SDL.h SDL_SetSurfaceAlphaMod" setSurfaceAlphaMod' :: Ptr Surface -> Word8 -> IO CInt foreign import ccall "SDL.h SDL_SetSurfaceBlendMode" setSurfaceBlendMode' :: Ptr Surface -> BlendMode -> IO CInt foreign import ccall "SDL.h SDL_SetSurfaceColorMod" setSurfaceColorMod' :: Ptr Surface -> Word8 -> Word8 -> Word8 -> IO CInt foreign import ccall "SDL.h SDL_SetSurfacePalette" setSurfacePalette' :: Ptr Surface -> Ptr Palette -> IO CInt foreign import ccall "SDL.h SDL_SetSurfaceRLE" setSurfaceRLE' :: Ptr Surface -> CInt -> IO CInt foreign import ccall "SDL.h SDL_UnlockSurface" unlockSurface' :: Ptr Surface -> IO () foreign import ccall "SDL.h SDL_GetWindowWMInfo" getWindowWMInfo' :: Window -> SysWMinfo -> IO Bool foreign import ccall "SDL.h SDL_GetClipboardText" getClipboardText' :: IO CString foreign import ccall "SDL.h SDL_HasClipboardText" hasClipboardText' :: IO Bool foreign import ccall "SDL.h SDL_SetClipboardText" setClipboardText' :: CString -> IO CInt createWindow :: MonadIO m => CString -> CInt -> CInt -> CInt -> CInt -> Word32 -> m Window createWindow v1 v2 v3 v4 v5 v6 = liftIO $ createWindow' v1 v2 v3 v4 v5 v6 {-# INLINE createWindow #-} createWindowAndRenderer :: MonadIO m => CInt -> CInt -> Word32 -> Ptr Window -> Ptr Renderer -> m CInt createWindowAndRenderer v1 v2 v3 v4 v5 = liftIO $ createWindowAndRenderer' v1 v2 v3 v4 v5 {-# INLINE createWindowAndRenderer #-} createWindowFrom :: MonadIO m => Ptr () -> m Window createWindowFrom v1 = liftIO $ createWindowFrom' v1 {-# INLINE createWindowFrom #-} destroyWindow :: MonadIO m => Window -> m () destroyWindow v1 = liftIO $ destroyWindow' v1 {-# INLINE destroyWindow #-} disableScreenSaver :: MonadIO m => m () disableScreenSaver = liftIO disableScreenSaver' {-# INLINE disableScreenSaver #-} enableScreenSaver :: MonadIO m => m () enableScreenSaver = liftIO enableScreenSaver' {-# INLINE enableScreenSaver #-} glBindTexture :: MonadIO m => Texture -> Ptr CFloat -> Ptr CFloat -> m CInt glBindTexture v1 v2 v3 = liftIO $ glBindTexture' v1 v2 v3 {-# INLINE glBindTexture #-} glCreateContext :: MonadIO m => Window -> m GLContext glCreateContext v1 = liftIO $ glCreateContext' v1 {-# INLINE glCreateContext #-} glDeleteContext :: MonadIO m => GLContext -> m () glDeleteContext v1 = liftIO $ glDeleteContext' v1 {-# INLINE glDeleteContext #-} glExtensionSupported :: MonadIO m => CString -> m Bool glExtensionSupported v1 = liftIO $ glExtensionSupported' v1 {-# INLINE glExtensionSupported #-} glGetAttribute :: MonadIO m => GLattr -> Ptr CInt -> m CInt glGetAttribute v1 v2 = liftIO $ glGetAttribute' v1 v2 {-# INLINE glGetAttribute #-} glGetCurrentContext :: MonadIO m => m GLContext glGetCurrentContext = liftIO glGetCurrentContext' {-# INLINE glGetCurrentContext #-} glGetCurrentWindow :: MonadIO m => m Window glGetCurrentWindow = liftIO glGetCurrentWindow' {-# INLINE glGetCurrentWindow #-} glGetDrawableSize :: MonadIO m => Window -> Ptr CInt -> Ptr CInt -> m () glGetDrawableSize v1 v2 v3 = liftIO $ glGetDrawableSize' v1 v2 v3 {-# INLINE glGetDrawableSize #-} glGetProcAddress :: MonadIO m => CString -> m (Ptr ()) glGetProcAddress v1 = liftIO $ glGetProcAddress' v1 {-# INLINE glGetProcAddress #-} glGetSwapInterval :: MonadIO m => m CInt glGetSwapInterval = liftIO glGetSwapInterval' {-# INLINE glGetSwapInterval #-} glLoadLibrary :: MonadIO m => CString -> m CInt glLoadLibrary v1 = liftIO $ glLoadLibrary' v1 {-# INLINE glLoadLibrary #-} glMakeCurrent :: MonadIO m => Window -> GLContext -> m CInt glMakeCurrent v1 v2 = liftIO $ glMakeCurrent' v1 v2 {-# INLINE glMakeCurrent #-} glResetAttributes :: MonadIO m => m () glResetAttributes = liftIO glResetAttributes' {-# INLINE glResetAttributes #-} glSetAttribute :: MonadIO m => GLattr -> CInt -> m CInt glSetAttribute v1 v2 = liftIO $ glSetAttribute' v1 v2 {-# INLINE glSetAttribute #-} glSetSwapInterval :: MonadIO m => CInt -> m CInt glSetSwapInterval v1 = liftIO $ glSetSwapInterval' v1 {-# INLINE glSetSwapInterval #-} glSwapWindow :: MonadIO m => Window -> m () glSwapWindow v1 = liftIO $ glSwapWindow' v1 {-# INLINE glSwapWindow #-} glUnbindTexture :: MonadIO m => Texture -> m CInt glUnbindTexture v1 = liftIO $ glUnbindTexture' v1 {-# INLINE glUnbindTexture #-} glUnloadLibrary :: MonadIO m => m () glUnloadLibrary = liftIO glUnloadLibrary' {-# INLINE glUnloadLibrary #-} getClosestDisplayMode :: MonadIO m => CInt -> Ptr DisplayMode -> Ptr DisplayMode -> m (Ptr DisplayMode) getClosestDisplayMode v1 v2 v3 = liftIO $ getClosestDisplayMode' v1 v2 v3 {-# INLINE getClosestDisplayMode #-} getCurrentDisplayMode :: MonadIO m => CInt -> Ptr DisplayMode -> m CInt getCurrentDisplayMode v1 v2 = liftIO $ getCurrentDisplayMode' v1 v2 {-# INLINE getCurrentDisplayMode #-} getCurrentVideoDriver :: MonadIO m => m CString getCurrentVideoDriver = liftIO getCurrentVideoDriver' {-# INLINE getCurrentVideoDriver #-} getDesktopDisplayMode :: MonadIO m => CInt -> Ptr DisplayMode -> m CInt getDesktopDisplayMode v1 v2 = liftIO $ getDesktopDisplayMode' v1 v2 {-# INLINE getDesktopDisplayMode #-} getDisplayBounds :: MonadIO m => CInt -> Ptr Rect -> m CInt getDisplayBounds v1 v2 = liftIO $ getDisplayBounds' v1 v2 {-# INLINE getDisplayBounds #-} getDisplayMode :: MonadIO m => CInt -> CInt -> Ptr DisplayMode -> m CInt getDisplayMode v1 v2 v3 = liftIO $ getDisplayMode' v1 v2 v3 {-# INLINE getDisplayMode #-} getDisplayName :: MonadIO m => CInt -> m CString getDisplayName v1 = liftIO $ getDisplayName' v1 {-# INLINE getDisplayName #-} getNumDisplayModes :: MonadIO m => CInt -> m CInt getNumDisplayModes v1 = liftIO $ getNumDisplayModes' v1 {-# INLINE getNumDisplayModes #-} getNumVideoDisplays :: MonadIO m => m CInt getNumVideoDisplays = liftIO getNumVideoDisplays' {-# INLINE getNumVideoDisplays #-} getNumVideoDrivers :: MonadIO m => m CInt getNumVideoDrivers = liftIO getNumVideoDrivers' {-# INLINE getNumVideoDrivers #-} getVideoDriver :: MonadIO m => CInt -> m CString getVideoDriver v1 = liftIO $ getVideoDriver' v1 {-# INLINE getVideoDriver #-} getWindowBrightness :: MonadIO m => Window -> m CFloat getWindowBrightness v1 = liftIO $ getWindowBrightness' v1 {-# INLINE getWindowBrightness #-} getWindowData :: MonadIO m => Window -> CString -> m (Ptr ()) getWindowData v1 v2 = liftIO $ getWindowData' v1 v2 {-# INLINE getWindowData #-} getWindowDisplayIndex :: MonadIO m => Window -> m CInt getWindowDisplayIndex v1 = liftIO $ getWindowDisplayIndex' v1 {-# INLINE getWindowDisplayIndex #-} getWindowDisplayMode :: MonadIO m => Window -> Ptr DisplayMode -> m CInt getWindowDisplayMode v1 v2 = liftIO $ getWindowDisplayMode' v1 v2 {-# INLINE getWindowDisplayMode #-} getWindowFlags :: MonadIO m => Window -> m Word32 getWindowFlags v1 = liftIO $ getWindowFlags' v1 {-# INLINE getWindowFlags #-} getWindowFromID :: MonadIO m => Word32 -> m Window getWindowFromID v1 = liftIO $ getWindowFromID' v1 {-# INLINE getWindowFromID #-} getWindowGammaRamp :: MonadIO m => Window -> Ptr Word16 -> Ptr Word16 -> Ptr Word16 -> m CInt getWindowGammaRamp v1 v2 v3 v4 = liftIO $ getWindowGammaRamp' v1 v2 v3 v4 {-# INLINE getWindowGammaRamp #-} getWindowGrab :: MonadIO m => Window -> m Bool getWindowGrab v1 = liftIO $ getWindowGrab' v1 {-# INLINE getWindowGrab #-} getWindowID :: MonadIO m => Window -> m Word32 getWindowID v1 = liftIO $ getWindowID' v1 {-# INLINE getWindowID #-} getWindowMaximumSize :: MonadIO m => Window -> Ptr CInt -> Ptr CInt -> m () getWindowMaximumSize v1 v2 v3 = liftIO $ getWindowMaximumSize' v1 v2 v3 {-# INLINE getWindowMaximumSize #-} getWindowMinimumSize :: MonadIO m => Window -> Ptr CInt -> Ptr CInt -> m () getWindowMinimumSize v1 v2 v3 = liftIO $ getWindowMinimumSize' v1 v2 v3 {-# INLINE getWindowMinimumSize #-} getWindowPixelFormat :: MonadIO m => Window -> m Word32 getWindowPixelFormat v1 = liftIO $ getWindowPixelFormat' v1 {-# INLINE getWindowPixelFormat #-} getWindowPosition :: MonadIO m => Window -> Ptr CInt -> Ptr CInt -> m () getWindowPosition v1 v2 v3 = liftIO $ getWindowPosition' v1 v2 v3 {-# INLINE getWindowPosition #-} getWindowSize :: MonadIO m => Window -> Ptr CInt -> Ptr CInt -> m () getWindowSize v1 v2 v3 = liftIO $ getWindowSize' v1 v2 v3 {-# INLINE getWindowSize #-} getWindowSurface :: MonadIO m => Window -> m (Ptr Surface) getWindowSurface v1 = liftIO $ getWindowSurface' v1 {-# INLINE getWindowSurface #-} getWindowTitle :: MonadIO m => Window -> m CString getWindowTitle v1 = liftIO $ getWindowTitle' v1 {-# INLINE getWindowTitle #-} hideWindow :: MonadIO m => Window -> m () hideWindow v1 = liftIO $ hideWindow' v1 {-# INLINE hideWindow #-} isScreenSaverEnabled :: MonadIO m => m Bool isScreenSaverEnabled = liftIO isScreenSaverEnabled' {-# INLINE isScreenSaverEnabled #-} maximizeWindow :: MonadIO m => Window -> m () maximizeWindow v1 = liftIO $ maximizeWindow' v1 {-# INLINE maximizeWindow #-} minimizeWindow :: MonadIO m => Window -> m () minimizeWindow v1 = liftIO $ minimizeWindow' v1 {-# INLINE minimizeWindow #-} raiseWindow :: MonadIO m => Window -> m () raiseWindow v1 = liftIO $ raiseWindow' v1 {-# INLINE raiseWindow #-} restoreWindow :: MonadIO m => Window -> m () restoreWindow v1 = liftIO $ restoreWindow' v1 {-# INLINE restoreWindow #-} setWindowBordered :: MonadIO m => Window -> Bool -> m () setWindowBordered v1 v2 = liftIO $ setWindowBordered' v1 v2 {-# INLINE setWindowBordered #-} setWindowBrightness :: MonadIO m => Window -> CFloat -> m CInt setWindowBrightness v1 v2 = liftIO $ setWindowBrightness' v1 v2 {-# INLINE setWindowBrightness #-} setWindowData :: MonadIO m => Window -> CString -> Ptr () -> m (Ptr ()) setWindowData v1 v2 v3 = liftIO $ setWindowData' v1 v2 v3 {-# INLINE setWindowData #-} setWindowDisplayMode :: MonadIO m => Window -> Ptr DisplayMode -> m CInt setWindowDisplayMode v1 v2 = liftIO $ setWindowDisplayMode' v1 v2 {-# INLINE setWindowDisplayMode #-} setWindowFullscreen :: MonadIO m => Window -> Word32 -> m CInt setWindowFullscreen v1 v2 = liftIO $ setWindowFullscreen' v1 v2 {-# INLINE setWindowFullscreen #-} setWindowGammaRamp :: MonadIO m => Window -> Ptr Word16 -> Ptr Word16 -> Ptr Word16 -> m CInt setWindowGammaRamp v1 v2 v3 v4 = liftIO $ setWindowGammaRamp' v1 v2 v3 v4 {-# INLINE setWindowGammaRamp #-} setWindowGrab :: MonadIO m => Window -> Bool -> m () setWindowGrab v1 v2 = liftIO $ setWindowGrab' v1 v2 {-# INLINE setWindowGrab #-} setWindowIcon :: MonadIO m => Window -> Ptr Surface -> m () setWindowIcon v1 v2 = liftIO $ setWindowIcon' v1 v2 {-# INLINE setWindowIcon #-} setWindowMaximumSize :: MonadIO m => Window -> CInt -> CInt -> m () setWindowMaximumSize v1 v2 v3 = liftIO $ setWindowMaximumSize' v1 v2 v3 {-# INLINE setWindowMaximumSize #-} setWindowMinimumSize :: MonadIO m => Window -> CInt -> CInt -> m () setWindowMinimumSize v1 v2 v3 = liftIO $ setWindowMinimumSize' v1 v2 v3 {-# INLINE setWindowMinimumSize #-} setWindowPosition :: MonadIO m => Window -> CInt -> CInt -> m () setWindowPosition v1 v2 v3 = liftIO $ setWindowPosition' v1 v2 v3 {-# INLINE setWindowPosition #-} setWindowSize :: MonadIO m => Window -> CInt -> CInt -> m () setWindowSize v1 v2 v3 = liftIO $ setWindowSize' v1 v2 v3 {-# INLINE setWindowSize #-} setWindowTitle :: MonadIO m => Window -> CString -> m () setWindowTitle v1 v2 = liftIO $ setWindowTitle' v1 v2 {-# INLINE setWindowTitle #-} showMessageBox :: MonadIO m => Ptr MessageBoxData -> Ptr CInt -> m CInt showMessageBox v1 v2 = liftIO $ showMessageBox' v1 v2 {-# INLINE showMessageBox #-} showSimpleMessageBox :: MonadIO m => Word32 -> CString -> CString -> Window -> m CInt showSimpleMessageBox v1 v2 v3 v4 = liftIO $ showSimpleMessageBox' v1 v2 v3 v4 {-# INLINE showSimpleMessageBox #-} showWindow :: MonadIO m => Window -> m () showWindow v1 = liftIO $ showWindow' v1 {-# INLINE showWindow #-} updateWindowSurface :: MonadIO m => Window -> m CInt updateWindowSurface v1 = liftIO $ updateWindowSurface' v1 {-# INLINE updateWindowSurface #-} updateWindowSurfaceRects :: MonadIO m => Window -> Ptr Rect -> CInt -> m CInt updateWindowSurfaceRects v1 v2 v3 = liftIO $ updateWindowSurfaceRects' v1 v2 v3 {-# INLINE updateWindowSurfaceRects #-} videoInit :: MonadIO m => CString -> m CInt videoInit v1 = liftIO $ videoInit' v1 {-# INLINE videoInit #-} videoQuit :: MonadIO m => m () videoQuit = liftIO videoQuit' {-# INLINE videoQuit #-} createRenderer :: MonadIO m => Window -> CInt -> Word32 -> m Renderer createRenderer v1 v2 v3 = liftIO $ createRenderer' v1 v2 v3 {-# INLINE createRenderer #-} createSoftwareRenderer :: MonadIO m => Ptr Surface -> m Renderer createSoftwareRenderer v1 = liftIO $ createSoftwareRenderer' v1 {-# INLINE createSoftwareRenderer #-} createTexture :: MonadIO m => Renderer -> Word32 -> CInt -> CInt -> CInt -> m Texture createTexture v1 v2 v3 v4 v5 = liftIO $ createTexture' v1 v2 v3 v4 v5 {-# INLINE createTexture #-} createTextureFromSurface :: MonadIO m => Renderer -> Ptr Surface -> m Texture createTextureFromSurface v1 v2 = liftIO $ createTextureFromSurface' v1 v2 {-# INLINE createTextureFromSurface #-} destroyRenderer :: MonadIO m => Renderer -> m () destroyRenderer v1 = liftIO $ destroyRenderer' v1 {-# INLINE destroyRenderer #-} destroyTexture :: MonadIO m => Texture -> m () destroyTexture v1 = liftIO $ destroyTexture' v1 {-# INLINE destroyTexture #-} getNumRenderDrivers :: MonadIO m => m CInt getNumRenderDrivers = liftIO getNumRenderDrivers' {-# INLINE getNumRenderDrivers #-} getRenderDrawBlendMode :: MonadIO m => Renderer -> Ptr BlendMode -> m Int getRenderDrawBlendMode v1 v2 = liftIO $ getRenderDrawBlendMode' v1 v2 {-# INLINE getRenderDrawBlendMode #-} getRenderDrawColor :: MonadIO m => Renderer -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> m CInt getRenderDrawColor v1 v2 v3 v4 v5 = liftIO $ getRenderDrawColor' v1 v2 v3 v4 v5 {-# INLINE getRenderDrawColor #-} getRenderDriverInfo :: MonadIO m => CInt -> Ptr RendererInfo -> m CInt getRenderDriverInfo v1 v2 = liftIO $ getRenderDriverInfo' v1 v2 {-# INLINE getRenderDriverInfo #-} getRenderTarget :: MonadIO m => Renderer -> m Texture getRenderTarget v1 = liftIO $ getRenderTarget' v1 {-# INLINE getRenderTarget #-} getRenderer :: MonadIO m => Window -> m Renderer getRenderer v1 = liftIO $ getRenderer' v1 {-# INLINE getRenderer #-} getRendererInfo :: MonadIO m => Renderer -> Ptr RendererInfo -> m CInt getRendererInfo v1 v2 = liftIO $ getRendererInfo' v1 v2 {-# INLINE getRendererInfo #-} getRendererOutputSize :: MonadIO m => Renderer -> Ptr CInt -> Ptr CInt -> m CInt getRendererOutputSize v1 v2 v3 = liftIO $ getRendererOutputSize' v1 v2 v3 {-# INLINE getRendererOutputSize #-} getTextureAlphaMod :: MonadIO m => Texture -> Ptr Word8 -> m CInt getTextureAlphaMod v1 v2 = liftIO $ getTextureAlphaMod' v1 v2 {-# INLINE getTextureAlphaMod #-} getTextureBlendMode :: MonadIO m => Texture -> Ptr BlendMode -> m CInt getTextureBlendMode v1 v2 = liftIO $ getTextureBlendMode' v1 v2 {-# INLINE getTextureBlendMode #-} getTextureColorMod :: MonadIO m => Texture -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> m CInt getTextureColorMod v1 v2 v3 v4 = liftIO $ getTextureColorMod' v1 v2 v3 v4 {-# INLINE getTextureColorMod #-} lockTexture :: MonadIO m => Texture -> Ptr Rect -> Ptr (Ptr ()) -> Ptr CInt -> m CInt lockTexture v1 v2 v3 v4 = liftIO $ lockTexture' v1 v2 v3 v4 {-# INLINE lockTexture #-} queryTexture :: MonadIO m => Texture -> Ptr Word32 -> Ptr CInt -> Ptr CInt -> Ptr CInt -> m CInt queryTexture v1 v2 v3 v4 v5 = liftIO $ queryTexture' v1 v2 v3 v4 v5 {-# INLINE queryTexture #-} renderClear :: MonadIO m => Renderer -> m CInt renderClear v1 = liftIO $ renderClear' v1 {-# INLINE renderClear #-} renderCopy :: MonadIO m => Renderer -> Texture -> Ptr Rect -> Ptr Rect -> m CInt renderCopy v1 v2 v3 v4 = liftIO $ renderCopy' v1 v2 v3 v4 {-# INLINE renderCopy #-} renderCopyEx :: MonadIO m => Renderer -> Texture -> Ptr Rect -> Ptr Rect -> CDouble -> Ptr Point -> RendererFlip -> m CInt renderCopyEx v1 v2 v3 v4 v5 v6 v7 = liftIO $ renderCopyEx' v1 v2 v3 v4 v5 v6 v7 {-# INLINE renderCopyEx #-} renderDrawLine :: MonadIO m => Renderer -> CInt -> CInt -> CInt -> CInt -> m CInt renderDrawLine v1 v2 v3 v4 v5 = liftIO $ renderDrawLine' v1 v2 v3 v4 v5 {-# INLINE renderDrawLine #-} renderDrawLines :: MonadIO m => Renderer -> Ptr Point -> CInt -> m CInt renderDrawLines v1 v2 v3 = liftIO $ renderDrawLines' v1 v2 v3 {-# INLINE renderDrawLines #-} renderDrawPoint :: MonadIO m => Renderer -> CInt -> CInt -> m CInt renderDrawPoint v1 v2 v3 = liftIO $ renderDrawPoint' v1 v2 v3 {-# INLINE renderDrawPoint #-} renderDrawPoints :: MonadIO m => Renderer -> Ptr Point -> CInt -> m CInt renderDrawPoints v1 v2 v3 = liftIO $ renderDrawPoints' v1 v2 v3 {-# INLINE renderDrawPoints #-} renderDrawRect :: MonadIO m => Renderer -> Ptr Rect -> m CInt renderDrawRect v1 v2 = liftIO $ renderDrawRect' v1 v2 {-# INLINE renderDrawRect #-} renderDrawRects :: MonadIO m => Renderer -> Ptr Rect -> CInt -> m CInt renderDrawRects v1 v2 v3 = liftIO $ renderDrawRects' v1 v2 v3 {-# INLINE renderDrawRects #-} renderFillRect :: MonadIO m => Renderer -> Ptr Rect -> m CInt renderFillRect v1 v2 = liftIO $ renderFillRect' v1 v2 {-# INLINE renderFillRect #-} renderFillRects :: MonadIO m => Renderer -> Ptr Rect -> CInt -> m CInt renderFillRects v1 v2 v3 = liftIO $ renderFillRects' v1 v2 v3 {-# INLINE renderFillRects #-} renderGetClipRect :: MonadIO m => Renderer -> Ptr Rect -> m () renderGetClipRect v1 v2 = liftIO $ renderGetClipRect' v1 v2 {-# INLINE renderGetClipRect #-} renderGetLogicalSize :: MonadIO m => Renderer -> Ptr CInt -> Ptr CInt -> m () renderGetLogicalSize v1 v2 v3 = liftIO $ renderGetLogicalSize' v1 v2 v3 {-# INLINE renderGetLogicalSize #-} renderGetScale :: MonadIO m => Renderer -> Ptr CFloat -> Ptr CFloat -> m () renderGetScale v1 v2 v3 = liftIO $ renderGetScale' v1 v2 v3 {-# INLINE renderGetScale #-} renderGetViewport :: MonadIO m => Renderer -> Ptr Rect -> m () renderGetViewport v1 v2 = liftIO $ renderGetViewport' v1 v2 {-# INLINE renderGetViewport #-} renderPresent :: MonadIO m => Renderer -> m () renderPresent v1 = liftIO $ renderPresent' v1 {-# INLINE renderPresent #-} renderReadPixels :: MonadIO m => Renderer -> Ptr Rect -> Word32 -> Ptr () -> CInt -> m CInt renderReadPixels v1 v2 v3 v4 v5 = liftIO $ renderReadPixels' v1 v2 v3 v4 v5 {-# INLINE renderReadPixels #-} renderSetClipRect :: MonadIO m => Renderer -> Ptr Rect -> m CInt renderSetClipRect v1 v2 = liftIO $ renderSetClipRect' v1 v2 {-# INLINE renderSetClipRect #-} renderSetLogicalSize :: MonadIO m => Renderer -> CInt -> CInt -> m CInt renderSetLogicalSize v1 v2 v3 = liftIO $ renderSetLogicalSize' v1 v2 v3 {-# INLINE renderSetLogicalSize #-} renderSetScale :: MonadIO m => Renderer -> CFloat -> CFloat -> m CInt renderSetScale v1 v2 v3 = liftIO $ renderSetScale' v1 v2 v3 {-# INLINE renderSetScale #-} renderSetViewport :: MonadIO m => Renderer -> Ptr Rect -> m CInt renderSetViewport v1 v2 = liftIO $ renderSetViewport' v1 v2 {-# INLINE renderSetViewport #-} renderTargetSupported :: MonadIO m => Renderer -> m Bool renderTargetSupported v1 = liftIO $ renderTargetSupported' v1 {-# INLINE renderTargetSupported #-} setRenderDrawBlendMode :: MonadIO m => Renderer -> BlendMode -> m CInt setRenderDrawBlendMode v1 v2 = liftIO $ setRenderDrawBlendMode' v1 v2 {-# INLINE setRenderDrawBlendMode #-} setRenderDrawColor :: MonadIO m => Renderer -> Word8 -> Word8 -> Word8 -> Word8 -> m CInt setRenderDrawColor v1 v2 v3 v4 v5 = liftIO $ setRenderDrawColor' v1 v2 v3 v4 v5 {-# INLINE setRenderDrawColor #-} setRenderTarget :: MonadIO m => Renderer -> Texture -> m CInt setRenderTarget v1 v2 = liftIO $ setRenderTarget' v1 v2 {-# INLINE setRenderTarget #-} setTextureAlphaMod :: MonadIO m => Texture -> Word8 -> m CInt setTextureAlphaMod v1 v2 = liftIO $ setTextureAlphaMod' v1 v2 {-# INLINE setTextureAlphaMod #-} setTextureBlendMode :: MonadIO m => Texture -> BlendMode -> m CInt setTextureBlendMode v1 v2 = liftIO $ setTextureBlendMode' v1 v2 {-# INLINE setTextureBlendMode #-} setTextureColorMod :: MonadIO m => Texture -> Word8 -> Word8 -> Word8 -> m CInt setTextureColorMod v1 v2 v3 v4 = liftIO $ setTextureColorMod' v1 v2 v3 v4 {-# INLINE setTextureColorMod #-} unlockTexture :: MonadIO m => Texture -> m () unlockTexture v1 = liftIO $ unlockTexture' v1 {-# INLINE unlockTexture #-} updateTexture :: MonadIO m => Texture -> Ptr Rect -> Ptr () -> CInt -> m CInt updateTexture v1 v2 v3 v4 = liftIO $ updateTexture' v1 v2 v3 v4 {-# INLINE updateTexture #-} updateYUVTexture :: MonadIO m => Texture -> Ptr Rect -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> Ptr Word8 -> CInt -> m CInt updateYUVTexture v1 v2 v3 v4 v5 v6 v7 v8 = liftIO $ updateYUVTexture' v1 v2 v3 v4 v5 v6 v7 v8 {-# INLINE updateYUVTexture #-} allocFormat :: MonadIO m => Word32 -> m (Ptr PixelFormat) allocFormat v1 = liftIO $ allocFormat' v1 {-# INLINE allocFormat #-} allocPalette :: MonadIO m => CInt -> m (Ptr Palette) allocPalette v1 = liftIO $ allocPalette' v1 {-# INLINE allocPalette #-} calculateGammaRamp :: MonadIO m => CFloat -> Ptr Word16 -> m () calculateGammaRamp v1 v2 = liftIO $ calculateGammaRamp' v1 v2 {-# INLINE calculateGammaRamp #-} freeFormat :: MonadIO m => Ptr PixelFormat -> m () freeFormat v1 = liftIO $ freeFormat' v1 {-# INLINE freeFormat #-} freePalette :: MonadIO m => Ptr Palette -> m () freePalette v1 = liftIO $ freePalette' v1 {-# INLINE freePalette #-} getPixelFormatName :: MonadIO m => Word32 -> m CString getPixelFormatName v1 = liftIO $ getPixelFormatName' v1 {-# INLINE getPixelFormatName #-} getRGB :: MonadIO m => Word32 -> Ptr PixelFormat -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> m () getRGB v1 v2 v3 v4 v5 = liftIO $ getRGB' v1 v2 v3 v4 v5 {-# INLINE getRGB #-} getRGBA :: MonadIO m => Word32 -> Ptr PixelFormat -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> m () getRGBA v1 v2 v3 v4 v5 v6 = liftIO $ getRGBA' v1 v2 v3 v4 v5 v6 {-# INLINE getRGBA #-} mapRGB :: MonadIO m => Ptr PixelFormat -> Word8 -> Word8 -> Word8 -> m Word32 mapRGB v1 v2 v3 v4 = liftIO $ mapRGB' v1 v2 v3 v4 {-# INLINE mapRGB #-} mapRGBA :: MonadIO m => Ptr PixelFormat -> Word8 -> Word8 -> Word8 -> Word8 -> m Word32 mapRGBA v1 v2 v3 v4 v5 = liftIO $ mapRGBA' v1 v2 v3 v4 v5 {-# INLINE mapRGBA #-} masksToPixelFormatEnum :: MonadIO m => CInt -> Word32 -> Word32 -> Word32 -> Word32 -> m Word32 masksToPixelFormatEnum v1 v2 v3 v4 v5 = liftIO $ masksToPixelFormatEnum' v1 v2 v3 v4 v5 {-# INLINE masksToPixelFormatEnum #-} pixelFormatEnumToMasks :: MonadIO m => Word32 -> Ptr CInt -> Ptr Word32 -> Ptr Word32 -> Ptr Word32 -> Ptr Word32 -> m Bool pixelFormatEnumToMasks v1 v2 v3 v4 v5 v6 = liftIO $ pixelFormatEnumToMasks' v1 v2 v3 v4 v5 v6 {-# INLINE pixelFormatEnumToMasks #-} setPaletteColors :: MonadIO m => Ptr Palette -> Ptr Color -> CInt -> CInt -> m CInt setPaletteColors v1 v2 v3 v4 = liftIO $ setPaletteColors' v1 v2 v3 v4 {-# INLINE setPaletteColors #-} setPixelFormatPalette :: MonadIO m => Ptr PixelFormat -> Ptr Palette -> m CInt setPixelFormatPalette v1 v2 = liftIO $ setPixelFormatPalette' v1 v2 {-# INLINE setPixelFormatPalette #-} enclosePoints :: MonadIO m => Ptr Point -> CInt -> Ptr Rect -> Ptr Rect -> m Bool enclosePoints v1 v2 v3 v4 = liftIO $ enclosePoints' v1 v2 v3 v4 {-# INLINE enclosePoints #-} hasIntersection :: MonadIO m => Ptr Rect -> Ptr Rect -> m Bool hasIntersection v1 v2 = liftIO $ hasIntersection' v1 v2 {-# INLINE hasIntersection #-} intersectRect :: MonadIO m => Ptr Rect -> Ptr Rect -> Ptr Rect -> m Bool intersectRect v1 v2 v3 = liftIO $ intersectRect' v1 v2 v3 {-# INLINE intersectRect #-} intersectRectAndLine :: MonadIO m => Ptr Rect -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> m Bool intersectRectAndLine v1 v2 v3 v4 v5 = liftIO $ intersectRectAndLine' v1 v2 v3 v4 v5 {-# INLINE intersectRectAndLine #-} unionRect :: MonadIO m => Ptr Rect -> Ptr Rect -> Ptr Rect -> m () unionRect v1 v2 v3 = liftIO $ unionRect' v1 v2 v3 {-# INLINE unionRect #-} blitScaled :: MonadIO m => Ptr Surface -> Ptr Rect -> Ptr Surface -> Ptr Rect -> m CInt blitScaled v1 v2 v3 v4 = liftIO $ blitScaled' v1 v2 v3 v4 {-# INLINE blitScaled #-} blitSurface :: MonadIO m => Ptr Surface -> Ptr Rect -> Ptr Surface -> Ptr Rect -> m CInt blitSurface v1 v2 v3 v4 = liftIO $ blitSurface' v1 v2 v3 v4 {-# INLINE blitSurface #-} convertPixels :: MonadIO m => CInt -> CInt -> Word32 -> Ptr () -> CInt -> Word32 -> Ptr () -> CInt -> m CInt convertPixels v1 v2 v3 v4 v5 v6 v7 v8 = liftIO $ convertPixels' v1 v2 v3 v4 v5 v6 v7 v8 {-# INLINE convertPixels #-} convertSurface :: MonadIO m => Ptr Surface -> Ptr PixelFormat -> Word32 -> m (Ptr Surface) convertSurface v1 v2 v3 = liftIO $ convertSurface' v1 v2 v3 {-# INLINE convertSurface #-} convertSurfaceFormat :: MonadIO m => Ptr Surface -> Word32 -> Word32 -> m (Ptr Surface) convertSurfaceFormat v1 v2 v3 = liftIO $ convertSurfaceFormat' v1 v2 v3 {-# INLINE convertSurfaceFormat #-} createRGBSurface :: MonadIO m => Word32 -> CInt -> CInt -> CInt -> Word32 -> Word32 -> Word32 -> Word32 -> m (Ptr Surface) createRGBSurface v1 v2 v3 v4 v5 v6 v7 v8 = liftIO $ createRGBSurface' v1 v2 v3 v4 v5 v6 v7 v8 {-# INLINE createRGBSurface #-} createRGBSurfaceFrom :: MonadIO m => Ptr () -> CInt -> CInt -> CInt -> CInt -> Word32 -> Word32 -> Word32 -> Word32 -> m (Ptr Surface) createRGBSurfaceFrom v1 v2 v3 v4 v5 v6 v7 v8 v9 = liftIO $ createRGBSurfaceFrom' v1 v2 v3 v4 v5 v6 v7 v8 v9 {-# INLINE createRGBSurfaceFrom #-} fillRect :: MonadIO m => Ptr Surface -> Ptr Rect -> Word32 -> m CInt fillRect v1 v2 v3 = liftIO $ fillRect' v1 v2 v3 {-# INLINE fillRect #-} fillRects :: MonadIO m => Ptr Surface -> Ptr Rect -> CInt -> Word32 -> m CInt fillRects v1 v2 v3 v4 = liftIO $ fillRects' v1 v2 v3 v4 {-# INLINE fillRects #-} freeSurface :: MonadIO m => Ptr Surface -> m () freeSurface v1 = liftIO $ freeSurface' v1 {-# INLINE freeSurface #-} getClipRect :: MonadIO m => Ptr Surface -> Ptr Rect -> m () getClipRect v1 v2 = liftIO $ getClipRect' v1 v2 {-# INLINE getClipRect #-} getColorKey :: MonadIO m => Ptr Surface -> Ptr Word32 -> m CInt getColorKey v1 v2 = liftIO $ getColorKey' v1 v2 {-# INLINE getColorKey #-} getSurfaceAlphaMod :: MonadIO m => Ptr Surface -> Ptr Word8 -> m CInt getSurfaceAlphaMod v1 v2 = liftIO $ getSurfaceAlphaMod' v1 v2 {-# INLINE getSurfaceAlphaMod #-} getSurfaceBlendMode :: MonadIO m => Ptr Surface -> Ptr BlendMode -> m CInt getSurfaceBlendMode v1 v2 = liftIO $ getSurfaceBlendMode' v1 v2 {-# INLINE getSurfaceBlendMode #-} getSurfaceColorMod :: MonadIO m => Ptr Surface -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> m CInt getSurfaceColorMod v1 v2 v3 v4 = liftIO $ getSurfaceColorMod' v1 v2 v3 v4 {-# INLINE getSurfaceColorMod #-} loadBMP :: MonadIO m => CString -> m (Ptr Surface) loadBMP file = liftIO $ do rw <- withCString "rb" $ rwFromFile file loadBMP_RW rw 1 {-# INLINE loadBMP #-} loadBMP_RW :: MonadIO m => Ptr RWops -> CInt -> m (Ptr Surface) loadBMP_RW v1 v2 = liftIO $ loadBMP_RW' v1 v2 {-# INLINE loadBMP_RW #-} lockSurface :: MonadIO m => Ptr Surface -> m CInt lockSurface v1 = liftIO $ lockSurface' v1 {-# INLINE lockSurface #-} lowerBlit :: MonadIO m => Ptr Surface -> Ptr Rect -> Ptr Surface -> Ptr Rect -> m CInt lowerBlit v1 v2 v3 v4 = liftIO $ lowerBlit' v1 v2 v3 v4 {-# INLINE lowerBlit #-} lowerBlitScaled :: MonadIO m => Ptr Surface -> Ptr Rect -> Ptr Surface -> Ptr Rect -> m CInt lowerBlitScaled v1 v2 v3 v4 = liftIO $ lowerBlitScaled' v1 v2 v3 v4 {-# INLINE lowerBlitScaled #-} saveBMP :: MonadIO m => Ptr Surface -> CString -> m CInt saveBMP surface file = liftIO $ do rw <- withCString "wb" $ rwFromFile file saveBMP_RW surface rw 1 {-# INLINE saveBMP #-} saveBMP_RW :: MonadIO m => Ptr Surface -> Ptr RWops -> CInt -> m CInt saveBMP_RW v1 v2 v3 = liftIO $ saveBMP_RW' v1 v2 v3 {-# INLINE saveBMP_RW #-} setClipRect :: MonadIO m => Ptr Surface -> Ptr Rect -> m Bool setClipRect v1 v2 = liftIO $ setClipRect' v1 v2 {-# INLINE setClipRect #-} setColorKey :: MonadIO m => Ptr Surface -> CInt -> Word32 -> m CInt setColorKey v1 v2 v3 = liftIO $ setColorKey' v1 v2 v3 {-# INLINE setColorKey #-} setSurfaceAlphaMod :: MonadIO m => Ptr Surface -> Word8 -> m CInt setSurfaceAlphaMod v1 v2 = liftIO $ setSurfaceAlphaMod' v1 v2 {-# INLINE setSurfaceAlphaMod #-} setSurfaceBlendMode :: MonadIO m => Ptr Surface -> BlendMode -> m CInt setSurfaceBlendMode v1 v2 = liftIO $ setSurfaceBlendMode' v1 v2 {-# INLINE setSurfaceBlendMode #-} setSurfaceColorMod :: MonadIO m => Ptr Surface -> Word8 -> Word8 -> Word8 -> m CInt setSurfaceColorMod v1 v2 v3 v4 = liftIO $ setSurfaceColorMod' v1 v2 v3 v4 {-# INLINE setSurfaceColorMod #-} setSurfacePalette :: MonadIO m => Ptr Surface -> Ptr Palette -> m CInt setSurfacePalette v1 v2 = liftIO $ setSurfacePalette' v1 v2 {-# INLINE setSurfacePalette #-} setSurfaceRLE :: MonadIO m => Ptr Surface -> CInt -> m CInt setSurfaceRLE v1 v2 = liftIO $ setSurfaceRLE' v1 v2 {-# INLINE setSurfaceRLE #-} unlockSurface :: MonadIO m => Ptr Surface -> m () unlockSurface v1 = liftIO $ unlockSurface' v1 {-# INLINE unlockSurface #-} getWindowWMInfo :: MonadIO m => Window -> SysWMinfo -> m Bool getWindowWMInfo v1 v2 = liftIO $ getWindowWMInfo' v1 v2 {-# INLINE getWindowWMInfo #-} getClipboardText :: MonadIO m => m CString getClipboardText = liftIO getClipboardText' {-# INLINE getClipboardText #-} hasClipboardText :: MonadIO m => m Bool hasClipboardText = liftIO hasClipboardText' {-# INLINE hasClipboardText #-} setClipboardText :: MonadIO m => CString -> m CInt setClipboardText v1 = liftIO $ setClipboardText' v1 {-# INLINE setClipboardText #-}
bj4rtmar/sdl2
src/SDL/Raw/Video.hs
bsd-3-clause
51,340
0
17
8,220
14,655
7,255
7,400
911
1
{-# LANGUAGE TypeFamilies #-} module Simple15 where (<$) :: p -> (p -> q) -> q x <$ f = f x type family Def p def :: Def p -> p def = undefined data EQU a b = EQU equ_refl :: EQU a a equ_refl = EQU data FOO = FOO type instance Def FOO = EQU () () foo :: FOO foo = equ_refl <$ def -- This works: -- foo = def $ equ_refl
ryantm/ghc
testsuite/tests/indexed-types/should_compile/Simple15.hs
bsd-3-clause
328
0
8
87
130
74
56
14
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fprof-auto-top #-} -- -- Copyright (c) 2010, João Dias, Simon Marlow, Simon Peyton Jones, -- and Norman Ramsey -- -- Modifications copyright (c) The University of Glasgow 2012 -- -- This module is a specialised and optimised version of -- Compiler.Hoopl.Dataflow in the hoopl package. In particular it is -- specialised to the UniqSM monad. -- module Hoopl.Dataflow ( DataflowLattice(..), OldFact(..), NewFact(..), Fact, mkFactBase , ChangeFlag(..) , FwdPass(..), FwdTransfer, mkFTransfer, mkFTransfer3, getFTransfer3 -- * Respecting Fuel -- $fuel , FwdRewrite, mkFRewrite, mkFRewrite3, getFRewrite3, noFwdRewrite , wrapFR, wrapFR2 , BwdPass(..), BwdTransfer, mkBTransfer, mkBTransfer3, getBTransfer3 , wrapBR, wrapBR2 , BwdRewrite, mkBRewrite, mkBRewrite3, getBRewrite3, noBwdRewrite , analyzeAndRewriteFwd, analyzeAndRewriteBwd , analyzeFwd, analyzeFwdBlocks, analyzeBwd ) where import UniqSupply import Data.Maybe import Data.Array import Compiler.Hoopl hiding ( mkBRewrite3, mkFRewrite3, noFwdRewrite, noBwdRewrite , analyzeAndRewriteBwd, analyzeAndRewriteFwd ) import Compiler.Hoopl.Internals ( wrapFR, wrapFR2 , wrapBR, wrapBR2 , splice ) -- ----------------------------------------------------------------------------- noRewrite :: a -> b -> UniqSM (Maybe c) noRewrite _ _ = return Nothing noFwdRewrite :: FwdRewrite UniqSM n f noFwdRewrite = FwdRewrite3 (noRewrite, noRewrite, noRewrite) -- | Functions passed to 'mkFRewrite3' should not be aware of the fuel supply. -- The result returned by 'mkFRewrite3' respects fuel. mkFRewrite3 :: forall n f. (n C O -> f -> UniqSM (Maybe (Graph n C O))) -> (n O O -> f -> UniqSM (Maybe (Graph n O O))) -> (n O C -> f -> UniqSM (Maybe (Graph n O C))) -> FwdRewrite UniqSM n f mkFRewrite3 f m l = FwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> UniqSM (Maybe a)) -> t -> t1 -> UniqSM (Maybe (a, FwdRewrite UniqSM n f)) {-# INLINE lift #-} lift rw node fact = do a <- rw node fact case a of Nothing -> return Nothing Just a -> return (Just (a,noFwdRewrite)) noBwdRewrite :: BwdRewrite UniqSM n f noBwdRewrite = BwdRewrite3 (noRewrite, noRewrite, noRewrite) mkBRewrite3 :: forall n f. (n C O -> f -> UniqSM (Maybe (Graph n C O))) -> (n O O -> f -> UniqSM (Maybe (Graph n O O))) -> (n O C -> FactBase f -> UniqSM (Maybe (Graph n O C))) -> BwdRewrite UniqSM n f mkBRewrite3 f m l = BwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> UniqSM (Maybe a)) -> t -> t1 -> UniqSM (Maybe (a, BwdRewrite UniqSM n f)) {-# INLINE lift #-} lift rw node fact = do a <- rw node fact case a of Nothing -> return Nothing Just a -> return (Just (a,noBwdRewrite)) ----------------------------------------------------------------------------- -- Analyze and rewrite forward: the interface ----------------------------------------------------------------------------- -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeAndRewriteFwd :: forall n f e x . NonLocal n => FwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e x -> Fact e f -> UniqSM (Graph n e x, FactBase f, MaybeO x f) analyzeAndRewriteFwd pass entries g f = do (rg, fout) <- arfGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedExitFact g' fout) distinguishedExitFact :: forall n e x f . Graph n e x -> Fact x f -> MaybeO x f distinguishedExitFact g f = maybe g where maybe :: Graph n e x -> MaybeO x f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany _ _ x) = case x of NothingO -> NothingO JustO _ -> JustO f ---------------------------------------------------------------- -- Forward Implementation ---------------------------------------------------------------- type Entries e = MaybeC e [Label] arfGraph :: forall n f e x . NonLocal n => FwdPass UniqSM n f -> Entries e -> Graph n e x -> Fact e f -> UniqSM (DG f n e x, Fact x f) arfGraph pass@FwdPass { fp_lattice = lattice, fp_transfer = transfer, fp_rewrite = rewrite } entries g in_fact = graph g in_fact where {- nested type synonyms would be so lovely here type ARF thing = forall e x . thing e x -> f -> m (DG f n e x, Fact x f) type ARFX thing = forall e x . thing e x -> Fact e f -> m (DG f n e x, Fact x f) -} graph :: Graph n e x -> Fact e f -> UniqSM (DG f n e x, Fact x f) block :: forall e x . Block n e x -> f -> UniqSM (DG f n e x, Fact x f) body :: [Label] -> LabelMap (Block n C C) -> Fact C f -> UniqSM (DG f n C C, Fact C f) -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' cat :: forall e a x f1 f2 f3. (f1 -> UniqSM (DG f n e a, f2)) -> (f2 -> UniqSM (DG f n a x, f3)) -> (f1 -> UniqSM (DG f n e x, f3)) graph GNil f = return (dgnil, f) graph (GUnit blk) f = block blk f graph (GMany e bdy x) f = ((e `ebcat` bdy) `cat` exit x) f where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact e f -> UniqSM (DG f n e C, Fact C f) exit :: MaybeO x (Block n C O) -> Fact C f -> UniqSM (DG f n C x, Fact x f) exit (JustO blk) f = arfx block blk f exit NothingO f = return (dgnilC, f) ebcat entry bdy f = c entries entry f where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact e f -> UniqSM (DG f n e C, Fact C f) c NothingC (JustO entry) f = (block entry `cat` body (successors entry) bdy) f c (JustC entries) NothingO f = body entries bdy f c _ _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks block BNil f = return (dgnil, f) block (BlockCO n b) f = (node n `cat` block b) f block (BlockCC l b n) f = (node l `cat` block b `cat` node n) f block (BlockOC b n) f = (block b `cat` node n) f block (BMiddle n) f = node n f block (BCat b1 b2) f = (block b1 `cat` block b2) f block (BSnoc h n) f = (block h `cat` node n) f block (BCons n t) f = (node n `cat` block t) f {-# INLINE node #-} node :: forall e x . (ShapeLifter e x) => n e x -> f -> UniqSM (DG f n e x, Fact x f) node n f = do { grw <- frewrite rewrite n f ; case grw of Nothing -> return ( singletonDG f n , ftransfer transfer n f ) Just (g, rw) -> let pass' = pass { fp_rewrite = rw } f' = fwdEntryFact n f in arfGraph pass' (fwdEntryLabel n) g f' } -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} cat ft1 ft2 f = do { (g1,f1) <- ft1 f ; (g2,f2) <- ft2 f1 ; let !g = g1 `dgSplice` g2 ; return (g, f2) } arfx :: forall x . (Block n C x -> f -> UniqSM (DG f n C x, Fact x f)) -> (Block n C x -> Fact C f -> UniqSM (DG f n C x, Fact x f)) arfx arf thing fb = arf thing $ fromJust $ lookupFact (entryLabel thing) $ joinInFacts lattice fb -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' body entries blockmap init_fbase = fixpoint Fwd lattice do_block entries blockmap init_fbase where lattice = fp_lattice pass do_block :: forall x . Block n C x -> FactBase f -> UniqSM (DG f n C x, Fact x f) do_block b fb = block b entryFact where entryFact = getFact lattice (entryLabel b) fb -- Join all the incoming facts with bottom. -- We know the results _shouldn't change_, but the transfer -- functions might, for example, generate some debugging traces. joinInFacts :: DataflowLattice f -> FactBase f -> FactBase f joinInFacts (lattice @ DataflowLattice {fact_bot = bot, fact_join = fj}) fb = mkFactBase lattice $ map botJoin $ mapToList fb where botJoin (l, f) = (l, snd $ fj l (OldFact bot) (NewFact f)) forwardBlockList :: (NonLocal n) => [Label] -> Body n -> [Block n C C] -- This produces a list of blocks in order suitable for forward analysis, -- along with the list of Labels it may depend on for facts. forwardBlockList entries blks = postorder_dfs_from blks entries ---------------------------------------------------------------- -- Forward Analysis only ---------------------------------------------------------------- -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeFwd :: forall n f e . NonLocal n => FwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e C -> Fact e f -> FactBase f analyzeFwd FwdPass { fp_lattice = lattice, fp_transfer = FwdTransfer3 (ftr, mtr, ltr) } entries g in_fact = graph g in_fact where graph :: Graph n e C -> Fact e f -> FactBase f graph (GMany entry blockmap NothingO) = case (entries, entry) of (NothingC, JustO entry) -> block entry `cat` body (successors entry) (JustC entries, NothingO) -> body entries _ -> error "bogus GADT pattern match failure" where body :: [Label] -> Fact C f -> Fact C f body entries f = fixpointAnal Fwd lattice do_block entries blockmap f where do_block :: forall x . Block n C x -> FactBase f -> Fact x f do_block b fb = block b entryFact where entryFact = getFact lattice (entryLabel b) fb -- NB. eta-expand block, GHC can't do this by itself. See #5809. block :: forall e x . Block n e x -> f -> Fact x f block BNil f = f block (BlockCO n b) f = (ftr n `cat` block b) f block (BlockCC l b n) f = (ftr l `cat` (block b `cat` ltr n)) f block (BlockOC b n) f = (block b `cat` ltr n) f block (BMiddle n) f = mtr n f block (BCat b1 b2) f = (block b1 `cat` block b2) f block (BSnoc h n) f = (block h `cat` mtr n) f block (BCons n t) f = (mtr n `cat` block t) f {-# INLINE cat #-} cat :: forall f1 f2 f3 . (f1 -> f2) -> (f2 -> f3) -> (f1 -> f3) cat ft1 ft2 = \f -> ft2 $! ft1 f -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeFwdBlocks :: forall n f e . NonLocal n => FwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e C -> Fact e f -> FactBase f analyzeFwdBlocks FwdPass { fp_lattice = lattice, fp_transfer = FwdTransfer3 (ftr, _, ltr) } entries g in_fact = graph g in_fact where graph :: Graph n e C -> Fact e f -> FactBase f graph (GMany entry blockmap NothingO) = case (entries, entry) of (NothingC, JustO entry) -> block entry `cat` body (successors entry) (JustC entries, NothingO) -> body entries _ -> error "bogus GADT pattern match failure" where body :: [Label] -> Fact C f -> Fact C f body entries f = fixpointAnal Fwd lattice do_block entries blockmap f where do_block :: forall x . Block n C x -> FactBase f -> Fact x f do_block b fb = block b entryFact where entryFact = getFact lattice (entryLabel b) fb -- NB. eta-expand block, GHC can't do this by itself. See #5809. block :: forall e x . Block n e x -> f -> Fact x f block BNil f = f block (BlockCO n _) f = ftr n f block (BlockCC l _ n) f = (ftr l `cat` ltr n) f block (BlockOC _ n) f = ltr n f block _ _ = error "analyzeFwdBlocks" {-# INLINE cat #-} cat :: forall f1 f2 f3 . (f1 -> f2) -> (f2 -> f3) -> (f1 -> f3) cat ft1 ft2 = \f -> ft2 $! ft1 f ---------------------------------------------------------------- -- Backward Analysis only ---------------------------------------------------------------- -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeBwd :: forall n f e . NonLocal n => BwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e C -> Fact C f -> FactBase f analyzeBwd BwdPass { bp_lattice = lattice, bp_transfer = BwdTransfer3 (ftr, mtr, ltr) } entries g in_fact = graph g in_fact where graph :: Graph n e C -> Fact C f -> FactBase f graph (GMany entry blockmap NothingO) = case (entries, entry) of (NothingC, JustO entry) -> body (successors entry) (JustC entries, NothingO) -> body entries _ -> error "bogus GADT pattern match failure" where body :: [Label] -> Fact C f -> Fact C f body entries f = fixpointAnal Bwd lattice do_block entries blockmap f where do_block :: forall x . Block n C x -> Fact x f -> FactBase f do_block b fb = mapSingleton (entryLabel b) (block b fb) -- NB. eta-expand block, GHC can't do this by itself. See #5809. block :: forall e x . Block n e x -> Fact x f -> f block BNil f = f block (BlockCO n b) f = (ftr n `cat` block b) f block (BlockCC l b n) f = ((ftr l `cat` block b) `cat` ltr n) f block (BlockOC b n) f = (block b `cat` ltr n) f block (BMiddle n) f = mtr n f block (BCat b1 b2) f = (block b1 `cat` block b2) f block (BSnoc h n) f = (block h `cat` mtr n) f block (BCons n t) f = (mtr n `cat` block t) f {-# INLINE cat #-} cat :: forall f1 f2 f3 . (f2 -> f3) -> (f1 -> f2) -> (f1 -> f3) cat ft1 ft2 = \f -> ft1 $! ft2 f ----------------------------------------------------------------------------- -- Backward analysis and rewriting: the interface ----------------------------------------------------------------------------- -- | if the graph being analyzed is open at the exit, I don't -- quite understand the implications of possible other exits analyzeAndRewriteBwd :: NonLocal n => BwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e x -> Fact x f -> UniqSM (Graph n e x, FactBase f, MaybeO e f) analyzeAndRewriteBwd pass entries g f = do (rg, fout) <- arbGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedEntryFact g' fout) distinguishedEntryFact :: forall n e x f . Graph n e x -> Fact e f -> MaybeO e f distinguishedEntryFact g f = maybe g where maybe :: Graph n e x -> MaybeO e f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany e _ _) = case e of NothingO -> NothingO JustO _ -> JustO f ----------------------------------------------------------------------------- -- Backward implementation ----------------------------------------------------------------------------- arbGraph :: forall n f e x . NonLocal n => BwdPass UniqSM n f -> Entries e -> Graph n e x -> Fact x f -> UniqSM (DG f n e x, Fact e f) arbGraph pass@BwdPass { bp_lattice = lattice, bp_transfer = transfer, bp_rewrite = rewrite } entries g in_fact = graph g in_fact where {- nested type synonyms would be so lovely here type ARB thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, f) type ARBX thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, Fact e f) -} graph :: Graph n e x -> Fact x f -> UniqSM (DG f n e x, Fact e f) block :: forall e x . Block n e x -> Fact x f -> UniqSM (DG f n e x, f) body :: [Label] -> Body n -> Fact C f -> UniqSM (DG f n C C, Fact C f) node :: forall e x . (ShapeLifter e x) => n e x -> Fact x f -> UniqSM (DG f n e x, f) cat :: forall e a x info info' info''. (info' -> UniqSM (DG f n e a, info'')) -> (info -> UniqSM (DG f n a x, info')) -> (info -> UniqSM (DG f n e x, info'')) graph GNil f = return (dgnil, f) graph (GUnit blk) f = block blk f graph (GMany e bdy x) f = ((e `ebcat` bdy) `cat` exit x) f where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact C f -> UniqSM (DG f n e C, Fact e f) exit :: MaybeO x (Block n C O) -> Fact x f -> UniqSM (DG f n C x, Fact C f) exit (JustO blk) f = arbx block blk f exit NothingO f = return (dgnilC, f) ebcat entry bdy f = c entries entry f where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact C f -> UniqSM (DG f n e C, Fact e f) c NothingC (JustO entry) f = (block entry `cat` body (successors entry) bdy) f c (JustC entries) NothingO f = body entries bdy f c _ _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks block BNil f = return (dgnil, f) block (BlockCO n b) f = (node n `cat` block b) f block (BlockCC l b n) f = (node l `cat` block b `cat` node n) f block (BlockOC b n) f = (block b `cat` node n) f block (BMiddle n) f = node n f block (BCat b1 b2) f = (block b1 `cat` block b2) f block (BSnoc h n) f = (block h `cat` node n) f block (BCons n t) f = (node n `cat` block t) f {-# INLINE node #-} node n f = do { bwdres <- brewrite rewrite n f ; case bwdres of Nothing -> return (singletonDG entry_f n, entry_f) where entry_f = btransfer transfer n f Just (g, rw) -> do { let pass' = pass { bp_rewrite = rw } ; (g, f) <- arbGraph pass' (fwdEntryLabel n) g f ; return (g, bwdEntryFact lattice n f)} } -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} cat ft1 ft2 f = do { (g2,f2) <- ft2 f ; (g1,f1) <- ft1 f2 ; let !g = g1 `dgSplice` g2 ; return (g, f1) } arbx :: forall x . (Block n C x -> Fact x f -> UniqSM (DG f n C x, f)) -> (Block n C x -> Fact x f -> UniqSM (DG f n C x, Fact C f)) arbx arb thing f = do { (rg, f) <- arb thing f ; let fb = joinInFacts (bp_lattice pass) $ mapSingleton (entryLabel thing) f ; return (rg, fb) } -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' body entries blockmap init_fbase = fixpoint Bwd (bp_lattice pass) do_block entries blockmap init_fbase where do_block :: forall x. Block n C x -> Fact x f -> UniqSM (DG f n C x, LabelMap f) do_block b f = do (g, f) <- block b f return (g, mapSingleton (entryLabel b) f) {- The forward and backward cases are not dual. In the forward case, the entry points are known, and one simply traverses the body blocks from those points. In the backward case, something is known about the exit points, but this information is essentially useless, because we don't actually have a dual graph (that is, one with edges reversed) to compute with. (Even if we did have a dual graph, it would not avail us---a backward analysis must include reachable blocks that don't reach the exit, as in a procedure that loops forever and has side effects.) -} ----------------------------------------------------------------------------- -- fixpoint ----------------------------------------------------------------------------- data Direction = Fwd | Bwd -- | fixpointing for analysis-only -- fixpointAnal :: forall n f. NonLocal n => Direction -> DataflowLattice f -> (Block n C C -> Fact C f -> Fact C f) -> [Label] -> LabelMap (Block n C C) -> Fact C f -> FactBase f fixpointAnal direction DataflowLattice{ fact_bot = _, fact_join = join } do_block entries blockmap init_fbase = loop start init_fbase where blocks = sortBlocks direction entries blockmap n = length blocks block_arr = {-# SCC "block_arr" #-} listArray (0,n-1) blocks start = {-# SCC "start" #-} [0..n-1] dep_blocks = {-# SCC "dep_blocks" #-} mkDepBlocks direction blocks loop :: IntHeap -- blocks still to analyse -> FactBase f -- current factbase (increases monotonically) -> FactBase f loop [] fbase = fbase loop (ix:todo) fbase = let blk = block_arr ! ix out_facts = {-# SCC "do_block" #-} do_block blk fbase !(todo', fbase') = {-# SCC "mapFoldWithKey" #-} mapFoldWithKey (updateFact join dep_blocks) (todo,fbase) out_facts in -- trace ("analysing: " ++ show (entryLabel blk)) $ -- trace ("fbase': " ++ show (mapKeys fbase')) $ return () -- trace ("changed: " ++ show changed) $ return () -- trace ("to analyse: " ++ show to_analyse) $ return () loop todo' fbase' -- | fixpointing for combined analysis/rewriting -- fixpoint :: forall n f. NonLocal n => Direction -> DataflowLattice f -> (Block n C C -> Fact C f -> UniqSM (DG f n C C, Fact C f)) -> [Label] -> LabelMap (Block n C C) -> (Fact C f -> UniqSM (DG f n C C, Fact C f)) fixpoint direction DataflowLattice{ fact_bot = _, fact_join = join } do_block entries blockmap init_fbase = do -- trace ("fixpoint: " ++ show (case direction of Fwd -> True; Bwd -> False) ++ " " ++ show (mapKeys blockmap) ++ show entries ++ " " ++ show (mapKeys init_fbase)) $ return() (fbase, newblocks) <- loop start init_fbase mapEmpty -- trace ("fixpoint DONE: " ++ show (mapKeys fbase) ++ show (mapKeys newblocks)) $ return() return (GMany NothingO newblocks NothingO, mapDeleteList (mapKeys blockmap) fbase) -- The successors of the Graph are the the Labels -- for which we have facts and which are *not* in -- the blocks of the graph where blocks = sortBlocks direction entries blockmap n = length blocks block_arr = {-# SCC "block_arr" #-} listArray (0,n-1) blocks start = {-# SCC "start" #-} [0..n-1] dep_blocks = {-# SCC "dep_blocks" #-} mkDepBlocks direction blocks loop :: IntHeap -> FactBase f -- current factbase (increases monotonically) -> LabelMap (DBlock f n C C) -- transformed graph -> UniqSM (FactBase f, LabelMap (DBlock f n C C)) loop [] fbase newblocks = return (fbase, newblocks) loop (ix:todo) fbase !newblocks = do let blk = block_arr ! ix -- trace ("analysing: " ++ show (entryLabel blk)) $ return () (rg, out_facts) <- do_block blk fbase let !(todo', fbase') = mapFoldWithKey (updateFact join dep_blocks) (todo,fbase) out_facts -- trace ("fbase': " ++ show (mapKeys fbase')) $ return () -- trace ("changed: " ++ show changed) $ return () -- trace ("to analyse: " ++ show to_analyse) $ return () let newblocks' = case rg of GMany _ blks _ -> mapUnion blks newblocks loop todo' fbase' newblocks' {- Note [TxFactBase invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The TxFactBase is used only during a fixpoint iteration (or "sweep"), and accumulates facts (and the transformed code) during the fixpoint iteration. * tfb_fbase increases monotonically, across all sweeps * At the beginning of each sweep tfb_cha = NoChange tfb_lbls = {} * During each sweep we process each block in turn. Processing a block is done thus: 1. Read from tfb_fbase the facts for its entry label (forward) or successors labels (backward) 2. Transform those facts into new facts for its successors (forward) or entry label (backward) 3. Augment tfb_fbase with that info We call the labels read in step (1) the "in-labels" of the sweep * The field tfb_lbls is the set of in-labels of all blocks that have been processed so far this sweep, including the block that is currently being processed. tfb_lbls is initialised to {}. It is a subset of the Labels of the *original* (not transformed) blocks. * The tfb_cha field is set to SomeChange iff we decide we need to perform another iteration of the fixpoint loop. It is initialsed to NoChange. Specifically, we set tfb_cha to SomeChange in step (3) iff (a) The fact in tfb_fbase for a block L changes (b) L is in tfb_lbls Reason: until a label enters the in-labels its accumuated fact in tfb_fbase has not been read, hence cannot affect the outcome Note [Unreachable blocks] ~~~~~~~~~~~~~~~~~~~~~~~~~ A block that is not in the domain of tfb_fbase is "currently unreachable". A currently-unreachable block is not even analyzed. Reason: consider constant prop and this graph, with entry point L1: L1: x:=3; goto L4 L2: x:=4; goto L4 L4: if x>3 goto L2 else goto L5 Here L2 is actually unreachable, but if we process it with bottom input fact, we'll propagate (x=4) to L4, and nuke the otherwise-good rewriting of L4. * If a currently-unreachable block is not analyzed, then its rewritten graph will not be accumulated in tfb_rg. And that is good: unreachable blocks simply do not appear in the output. * Note that clients must be careful to provide a fact (even if bottom) for each entry point. Otherwise useful blocks may be garbage collected. * Note that updateFact must set the change-flag if a label goes from not-in-fbase to in-fbase, even if its fact is bottom. In effect the real fact lattice is UNR bottom the points above bottom * Even if the fact is going from UNR to bottom, we still call the client's fact_join function because it might give the client some useful debugging information. * All of this only applies for *forward* ixpoints. For the backward case we must treat every block as reachable; it might finish with a 'return', and therefore have no successors, for example. -} ----------------------------------------------------------------------------- -- Pieces that are shared by fixpoint and fixpoint_anal ----------------------------------------------------------------------------- -- | Sort the blocks into the right order for analysis. sortBlocks :: NonLocal n => Direction -> [Label] -> LabelMap (Block n C C) -> [Block n C C] sortBlocks direction entries blockmap = case direction of Fwd -> fwd Bwd -> reverse fwd where fwd = forwardBlockList entries blockmap -- | construct a mapping from L -> block indices. If the fact for L -- changes, re-analyse the given blocks. mkDepBlocks :: NonLocal n => Direction -> [Block n C C] -> LabelMap [Int] mkDepBlocks Fwd blocks = go blocks 0 mapEmpty where go [] !_ m = m go (b:bs) !n m = go bs (n+1) $! mapInsert (entryLabel b) [n] m mkDepBlocks Bwd blocks = go blocks 0 mapEmpty where go [] !_ m = m go (b:bs) !n m = go bs (n+1) $! go' (successors b) m where go' [] m = m go' (l:ls) m = go' ls (mapInsertWith (++) l [n] m) -- | After some new facts have been generated by analysing a block, we -- fold this function over them to generate (a) a list of block -- indices to (re-)analyse, and (b) the new FactBase. -- updateFact :: JoinFun f -> LabelMap [Int] -> Label -> f -- out fact -> (IntHeap, FactBase f) -> (IntHeap, FactBase f) updateFact fact_join dep_blocks lbl new_fact (todo, fbase) = case lookupFact lbl fbase of Nothing -> let !z = mapInsert lbl new_fact fbase in (changed, z) -- Note [no old fact] Just old_fact -> case fact_join lbl (OldFact old_fact) (NewFact new_fact) of (NoChange, _) -> (todo, fbase) (_, f) -> let !z = mapInsert lbl f fbase in (changed, z) where changed = foldr insertIntHeap todo $ mapFindWithDefault [] lbl dep_blocks {- Note [no old fact] We know that the new_fact is >= _|_, so we don't need to join. However, if the new fact is also _|_, and we have already analysed its block, we don't need to record a change. So there's a tradeoff here. It turns out that always recording a change is faster. -} ----------------------------------------------------------------------------- -- DG: an internal data type for 'decorated graphs' -- TOTALLY internal to Hoopl; each block is decorated with a fact ----------------------------------------------------------------------------- type DG f = Graph' (DBlock f) data DBlock f n e x = DBlock f (Block n e x) -- ^ block decorated with fact instance NonLocal n => NonLocal (DBlock f n) where entryLabel (DBlock _ b) = entryLabel b successors (DBlock _ b) = successors b --- constructors dgnil :: DG f n O O dgnilC :: DG f n C C dgSplice :: NonLocal n => DG f n e a -> DG f n a x -> DG f n e x ---- observers normalizeGraph :: forall n f e x . NonLocal n => DG f n e x -> (Graph n e x, FactBase f) -- A Graph together with the facts for that graph -- The domains of the two maps should be identical normalizeGraph g = (mapGraphBlocks dropFact g, facts g) where dropFact :: DBlock t t1 t2 t3 -> Block t1 t2 t3 dropFact (DBlock _ b) = b facts :: DG f n e x -> FactBase f facts GNil = noFacts facts (GUnit _) = noFacts facts (GMany _ body exit) = bodyFacts body `mapUnion` exitFacts exit exitFacts :: MaybeO x (DBlock f n C O) -> FactBase f exitFacts NothingO = noFacts exitFacts (JustO (DBlock f b)) = mapSingleton (entryLabel b) f bodyFacts :: LabelMap (DBlock f n C C) -> FactBase f bodyFacts body = mapFoldWithKey f noFacts body where f :: forall t a x. Label -> DBlock a t C x -> LabelMap a -> LabelMap a f lbl (DBlock f _) fb = mapInsert lbl f fb --- implementation of the constructors (boring) dgnil = GNil dgnilC = GMany NothingO emptyBody NothingO dgSplice = splice fzCat where fzCat :: DBlock f n e O -> DBlock t n O x -> DBlock f n e x fzCat (DBlock f b1) (DBlock _ b2) = DBlock f $! b1 `blockAppend` b2 -- NB. strictness, this function is hammered. ---------------------------------------------------------------- -- Utilities ---------------------------------------------------------------- -- Lifting based on shape: -- - from nodes to blocks -- - from facts to fact-like things -- Lowering back: -- - from fact-like things to facts -- Note that the latter two functions depend only on the entry shape. class ShapeLifter e x where singletonDG :: f -> n e x -> DG f n e x fwdEntryFact :: NonLocal n => n e x -> f -> Fact e f fwdEntryLabel :: NonLocal n => n e x -> MaybeC e [Label] ftransfer :: FwdTransfer n f -> n e x -> f -> Fact x f frewrite :: FwdRewrite m n f -> n e x -> f -> m (Maybe (Graph n e x, FwdRewrite m n f)) -- @ end node.tex bwdEntryFact :: NonLocal n => DataflowLattice f -> n e x -> Fact e f -> f btransfer :: BwdTransfer n f -> n e x -> Fact x f -> f brewrite :: BwdRewrite m n f -> n e x -> Fact x f -> m (Maybe (Graph n e x, BwdRewrite m n f)) instance ShapeLifter C O where singletonDG f n = gUnitCO (DBlock f (BlockCO n BNil)) fwdEntryFact n f = mapSingleton (entryLabel n) f bwdEntryFact lat n fb = getFact lat (entryLabel n) fb ftransfer (FwdTransfer3 (ft, _, _)) n f = ft n f btransfer (BwdTransfer3 (bt, _, _)) n f = bt n f frewrite (FwdRewrite3 (fr, _, _)) n f = fr n f brewrite (BwdRewrite3 (br, _, _)) n f = br n f fwdEntryLabel n = JustC [entryLabel n] instance ShapeLifter O O where singletonDG f = gUnitOO . DBlock f . BMiddle fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdTransfer3 (_, ft, _)) n f = ft n f btransfer (BwdTransfer3 (_, bt, _)) n f = bt n f frewrite (FwdRewrite3 (_, fr, _)) n f = fr n f brewrite (BwdRewrite3 (_, br, _)) n f = br n f fwdEntryLabel _ = NothingC instance ShapeLifter O C where singletonDG f n = gUnitOC (DBlock f (BlockOC BNil n)) fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdTransfer3 (_, _, ft)) n f = ft n f btransfer (BwdTransfer3 (_, _, bt)) n f = bt n f frewrite (FwdRewrite3 (_, _, fr)) n f = fr n f brewrite (BwdRewrite3 (_, _, br)) n f = br n f fwdEntryLabel _ = NothingC {- class ShapeLifter e x where singletonDG :: f -> n e x -> DG f n e x instance ShapeLifter C O where singletonDG f n = gUnitCO (DBlock f (BlockCO n BNil)) instance ShapeLifter O O where singletonDG f = gUnitOO . DBlock f . BMiddle instance ShapeLifter O C where singletonDG f n = gUnitOC (DBlock f (BlockOC BNil n)) -} -- Fact lookup: the fact `orelse` bottom getFact :: DataflowLattice f -> Label -> FactBase f -> f getFact lat l fb = case lookupFact l fb of Just f -> f Nothing -> fact_bot lat {- Note [Respects fuel] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -} -- $fuel -- A value of type 'FwdRewrite' or 'BwdRewrite' /respects fuel/ if -- any function contained within the value satisfies the following properties: -- -- * When fuel is exhausted, it always returns 'Nothing'. -- -- * When it returns @Just g rw@, it consumes /exactly/ one unit -- of fuel, and new rewrite 'rw' also respects fuel. -- -- Provided that functions passed to 'mkFRewrite', 'mkFRewrite3', -- 'mkBRewrite', and 'mkBRewrite3' are not aware of the fuel supply, -- the results respect fuel. -- -- It is an /unchecked/ run-time error for the argument passed to 'wrapFR', -- 'wrapFR2', 'wrapBR', or 'warpBR2' to return a function that does not respect fuel. -- ----------------------------------------------------------------------------- -- a Heap of Int -- We should really use a proper Heap here, but my attempts to make -- one have not succeeded in beating the simple ordered list. Another -- alternative is IntSet (using deleteFindMin), but that was also -- slower than the ordered list in my experiments --SDM 25/1/2012 type IntHeap = [Int] -- ordered insertIntHeap :: Int -> [Int] -> [Int] insertIntHeap x [] = [x] insertIntHeap x (y:ys) | x < y = x : y : ys | x == y = x : ys | otherwise = y : insertIntHeap x ys
urbanslug/ghc
compiler/cmm/Hoopl/Dataflow.hs
bsd-3-clause
35,943
252
64
10,765
9,838
5,112
4,726
495
14
{-# LANGUAGE PolyKinds, GADTs, KindSignatures, DataKinds, FlexibleInstances #-} module T7438 where import T7438a go Nil acc = acc
urbanslug/ghc
testsuite/tests/polykinds/T7438.hs
bsd-3-clause
132
0
5
20
18
11
7
4
1
--fixIt1.hs module Sing where fstString :: [Char] -> [Char] fstString x = x ++ " in the rain" sndString :: [Char] -> [Char] sndString x = x ++ " over the rainbow" sing = if (x > y) then fstString x else sndString y where x = "Singin" y = "Somewhere"
deciduously/Haskell-First-Principles-Exercises
2-Defining and combining/5-Types/code/fixIt1.hs
mit
275
0
7
76
97
55
42
8
2
--- simple list defenition in haskel -- List a data List a = Nil | Const a (List a) deriving Show -- similar to: -- data [] a = [] | a : ([] a) -- infixr 5 : -- or: -- data [] a = [] | a : [a] len :: List a -> Int len Nil = 0 len (Const _ xs) = 1 + len xs len' :: [a] -> Int len' [] = 0 len' (x: xs) = 1 + len' xs head' :: [a] -> a head' (x:_) = x head' [] = error "head error: empty list" myList = Const 1 (Const 2 (Const 3 Nil)) myAnotherList = 'a': ('b': ('c': [])) -- also due to "infixr 5" right associativity we can write it myAnotherList' = 'a': 'b': 'c': []
djleonskennedy/learning-haskell
src/basics/lists.hs
mit
671
0
10
242
230
124
106
13
1
module Checker where import Data.List (find) import AST -------------------------------------------------------------------------- data Type = T_Unknown | T_IntChar | T_Bool | T_Void | T_Comparable | T_Arrow [Type] Type deriving (Show, Eq) data Initialised = Yes | No | Maybe deriving (Show, Eq) type IsParam = Bool type ScopeLevel = Int type VariableDef = (Type, Name, ScopeLevel, Initialised, IsParam) type BinaryOpDef = (Type, BinOp) type FunctionDef = (Type, Name) type Environment = ([VariableDef], [BinaryOpDef], [FunctionDef]) initialEnv = ([], [ (T_Arrow [T_Comparable, T_Comparable] T_Bool, Eq), (T_Arrow [T_Comparable, T_Comparable] T_Bool, NotEq), (T_Arrow [T_Bool, T_Comparable] T_Bool, Or), (T_Arrow [T_Bool, T_Comparable] T_Bool, And), (T_Arrow [T_Comparable, T_Comparable] T_Bool, AST.LT), (T_Arrow [T_Comparable, T_Comparable] T_Bool, AST.GT), (T_Arrow [T_Comparable, T_Comparable] T_Bool, LTE), (T_Arrow [T_Comparable, T_Comparable] T_Bool, GTE), (T_Arrow [T_IntChar, T_IntChar] T_IntChar, Plus), (T_Arrow [T_IntChar, T_IntChar] T_IntChar, Minus), (T_Arrow [T_IntChar, T_IntChar] T_IntChar, Mult), (T_Arrow [T_IntChar, T_IntChar] T_IntChar, Div), (T_Arrow [T_IntChar, T_IntChar] T_IntChar, Mod) ], [ (T_Arrow [] T_Void, "exit"), (T_Arrow [T_IntChar] T_Void, "printc"), (T_Arrow [T_IntChar] T_Void, "printi") ]) --This function is there incase the types are ever siginificantly extended --to include things like strings and pointers, in which case it would not --be as trivial subtypeOf :: Type -> Type -> Bool subtypeOf _ T_Comparable = True subtypeOf _ _ = False -------------------------------------------------------------------------- type ErrorMessage = String data TC a = TC ([ErrorMessage] -> Environment -> Name -> (a, [ErrorMessage], Environment, Name)) instance Monad TC where return x = TC (\es en fn -> (x,es,en,fn)) st >>= f = TC (\es en fn -> let (x,es',en',fn') = apply st es en fn in apply (f x) es' en' fn') apply :: TC a -> [ErrorMessage] -> Environment -> Name -> (a, [ErrorMessage], Environment, Name) apply (TC f) = f emitError :: ErrorMessage -> TC () emitError e = TC (\es en fn -> ((), es ++ [e], en, fn)) getEnv :: TC Environment getEnv = TC (\es en fn -> (en, es, en, fn)) updateEnv :: Environment -> TC () updateEnv en' = TC (\es en fn -> ((), es, en', fn)) addVarToEnv :: Type -> Name -> ScopeLevel -> Initialised -> IsParam -> TC () addVarToEnv t n s i p = TC (\es (vs,bs,fs) fn -> ((), es, ((t,n,s,i,p):vs,bs,fs), fn)) addFuncToEnv :: Type -> Name -> TC () addFuncToEnv t n = TC (\es (vs,bs,fs) fn -> ((), es, (vs,bs,(t,n):fs), fn)) varAlreadyExists :: ScopeLevel -> Name -> TC Bool varAlreadyExists s n = TC (\es en fn -> (f en, es, en, fn)) where getVarType (vs,_,_) s n = do (t,_,_,_,_) <- find (\(_,n',s',_,_)-> n == n' && s == s') vs return t f en = case getVarType en s n of Nothing -> False; Just _ -> True getVarType :: Name -> TC (Maybe Type) getVarType n = TC (\es en fn -> (getVarType en n, es, en, fn)) where getVarType (vs,_,_) n = do (t,_,_,_,_) <- find (\(_,n',_,_,_)-> n == n') vs return t funcAlreadyExists :: Name -> TC Bool funcAlreadyExists n = TC (\es en fn -> (f en, es, en, fn)) where getFuncType (_,_,fs) n = do (t,_) <- find (\(_,n')-> n == n') fs return t f en = case getFuncType en n of Nothing -> False; Just _ -> True getFuncType :: Name -> TC (Maybe Type) getFuncType n = TC (\es en fn -> (getVarType en n, es, en, fn)) where getVarType (_,_,fs) n = do (t,_) <- find (\(_,n')-> n == n') fs return t isInitialised :: Name -> TC Initialised isInitialised n = TC (\es en fn -> (isInitialised' en n, es, en, fn)) isParameter :: Name -> TC Bool isParameter n = TC (\es en fn -> (isParameter' en n, es, en, fn)) getBinOpType :: BinOp -> TC (Maybe Type) getBinOpType o = TC (\es en fn -> (getBinOpType' en o, es, en, fn)) initialise :: Name -> TC () initialise n' = TC (\es (vs,bs,fs) fn -> ((), es, (remake vs,bs,fs), fn)) where remake :: [VariableDef] -> [VariableDef] remake ((t,n,s,i,p):vs) | n == n' = (t,n,s,Yes,p):vs | otherwise = (t,n,s,i,p) : (remake vs) removeVarsAtScope :: ScopeLevel -> TC () removeVarsAtScope s = TC (\es (vs,bs,fs) fn -> ((), es, (filter f vs,bs,fs), fn)) where f (_,_,s',_,_) = s /= s' mergeEnvs :: Environment -> Environment -> TC () mergeEnvs (vs1,_,_) (vs2,_,_) = TC (\es (vs,bs,fs) fn -> ((), es, (compareVarEnvs vs1 vs2,bs,fs), fn)) setCurrentFunctionName :: Name -> TC () setCurrentFunctionName n = TC (\es en fn -> ((), es, en, n)) getCurrentFunctionName :: TC Name getCurrentFunctionName = TC (\es en fn -> (fn, es, en, fn)) -------------------------------------------------------------------------- isInitialised' :: Environment -> Name -> Initialised isInitialised' (vs,_,_) n = case find (\(_,n',_,_,_)-> n == n') vs of Nothing -> No Just (_,_,_,i,_) -> i isParameter' :: Environment -> Name -> Bool isParameter' (vs,_,_) n = case find (\(_,n',_,_,_)-> n == n') vs of Nothing -> False Just (_,_,_,_,p) -> p getBinOpType' :: Environment -> BinOp -> Maybe Type getBinOpType' (_,bs,_) b = do (t,_) <- find (\(_,b')-> b == b') bs return t compareVarEnvs :: [VariableDef] -> [VariableDef] -> [VariableDef] compareVarEnvs [] [] = [] compareVarEnvs ((t,n,s,i,p):vs1) ((_,_,_,i',_):vs2) | i /= i' = (t,n,s,Maybe,p) : (compareVarEnvs vs1 vs2) | i == i = (t,n,s,i,p) : (compareVarEnvs vs1 vs2) -------------------------------------------------------------------------- checkStms :: ScopeLevel -> [Statement] -> TC () checkStms sl [] = return () checkStms sl (s:ss) = do checkStm sl s checkStms sl ss checkStm :: ScopeLevel -> Statement -> TC () checkStm sl StmCompound { scDecls = decls, scStms = ss } = do checkVarDefs (sl+1) decls checkStms (sl+1) ss removeVarsAtScope (sl+1) checkStm sl StmIf { siCond = e, siThen = s1, siElse = ms2} = do t <- checkExp sl e if (t /= T_Bool) then do fn <- getCurrentFunctionName emitError $ "Type Error: If Statement conditional expression in function '" ++ fn ++ "' must evaluate to type T_Bool" else return () case ms2 of Nothing -> do en1 <- getEnv checkStm sl s1 en2 <- getEnv mergeEnvs en1 en2 Just s2 -> do originalEnv <- getEnv checkStm sl s2 en1 <- getEnv updateEnv originalEnv checkStm sl s1 en2 <- getEnv mergeEnvs en1 en2 checkStm sl StmWhile { swExp = e, swStm = s } = do t <- checkExp sl e if (t /= T_Bool) then do fn <- getCurrentFunctionName emitError $ "Type Error: While loop conditional expression in function '" ++ fn ++ "' must evaluate to type T_Bool" else return () en1 <- getEnv checkStm sl s en2 <- getEnv mergeEnvs en1 en2 checkStm sl StmExpression { seExp = e } = case e of Nothing -> return () Just e' -> do _ <- checkExp sl e' return () checkStm sl StmReturn { srExp = me } = do fn <- getCurrentFunctionName mt <- getFuncType fn case mt of Nothing -> do emitError $ "Implementation Error: The Function: '" ++ fn ++ "' does not have an associated type" --Should never be called return () Just (T_Arrow _ tr) -> do case me of Nothing -> if (tr == T_Void) then return () else emitError $ "Error: The function '" ++ fn ++ "' is of type 'T_Void' so \ \you cannot return a value from it" Just e -> do te <- checkExp sl e if (te == tr) then return () else emitError $ "Error: This function '" ++ fn ++ "' expects a return type of '" ++ (show tr) ++ "' but you tried to return a value of type '" ++ (show te) ++ "'" checkExp :: ScopeLevel -> Expression -> TC Type checkExp s ExpId { eiVal = n } = do mt <- getVarType n case mt of Nothing -> do emitError $ "Scope Error: The Variable '" ++ n ++ "' is not in scope \ \or does not exist" return T_Unknown Just T_Unknown -> return T_Unknown Just t -> do init <- isInitialised n case init of Yes -> return () No -> emitError $ "Error: The variable " ++ n ++ " is not initialised" Maybe -> emitError $ "Error: The variable '" ++ n ++ "' may not be initialised" return t checkExp s ExpIntLit {} = return T_IntChar checkExp s ExpCharLit {} = return T_IntChar checkExp s ExpBoolLit {} = return T_Bool checkExp s ExpAssign {saId = n, saExp = e} = do t <- checkExp s e mt <- getVarType n case mt of Nothing -> do emitError $ "Scope Error: The Variable '" ++ n ++ "' is not in scope \ \or does not exist" return T_Unknown Just t' -> if t == t' || t == T_Unknown then do initialise n return t else do initialise n emitError $ "Type Error: The type of the variable '" ++ n ++ "' is '" ++ (show t') ++ "' which does not match the type being assigned: " ++ (show t) return T_Unknown checkExp s ExpBinOpApp {arg1 = a1, arg2 = a2, op = o} = do mt <- getBinOpType o case mt of Nothing -> do emitError $ "Implementation Error: The Binary Operator: '" ++ (show o) ++ "' does not have an associated type" --Should never be called return T_Unknown Just ta@(T_Arrow tps tr) -> do t1 <- checkExp s a1 t2 <- checkExp s a2 if (t1 == t2) then do t <- checkArrow (show o) ta [t1, t2] return t else if (t1 /= T_Unknown && t2 /= T_Unknown) then do emitError $ "Type Error: The Binary Operator '" ++ (show o) ++ "' requires arguments of the following types: " ++ (show tps) return T_Unknown else return T_Unknown checkExp 0 ExpCall {ecId = (ExpId {eiVal = n})} = do emitError $ "Error: You have attempted to call a function '" ++ n ++ "' to assign a value to a global variable, this is not permitted" return T_Unknown checkExp s ExpCall {ecId = (ExpId {eiVal = n}), ecArgs = es} = do mt <- getFuncType n case mt of Nothing -> do emitError $ "Error: The function '" ++ n ++ "' does not exist" return T_Unknown Just (T_Arrow pts rt) -> do if length pts == length es then checkParams n 1 s pts es else emitError $ "Error: The function '" ++ n ++ "' expects " ++ (show $ length pts) ++ " arguments, but you have supplied " ++ (show $ length es) return rt checkExp s ExpCall {ecId = _} = do emitError $ "Error: Cannot call an expression like a function" return T_Unknown checkParams :: Name -> Int -> ScopeLevel -> [Type] -> [Expression] -> TC () checkParams _ _ _ [] [] = return () checkParams n i sl (t:ts) (e:es) = do te <- checkExp sl e if te == t then return () else emitError $ "Error: The " ++ (createStNdRdTh i) ++ " parameter in for the function '" ++ n ++ "' expects a value of type '" ++ (show t) ++ "' but you have supplied a value of type '" ++ (show te) ++ "'" checkDecls :: ScopeLevel -> DataType -> [(Name, Maybe Expression)] -> TC () checkDecls sl dt [] = return () checkDecls sl dt ((n, e):decls) = do funcName <- getCurrentFunctionName let typeAndLoc = (if sl == 0 then "Global Variable" else "Local Variable in " ++ funcName) in do b <- varAlreadyExists sl n if b then return () else do case e of Nothing -> addVarToEnv (mapType dt) n sl No False Just e -> do t <- checkExp sl e if t /= (mapType dt) && t /= T_Unknown then emitError $ "Type Error: " ++ typeAndLoc ++ " '" ++ n ++ "' was expecting \ \a value of type: '" ++ (show $ mapType dt) ++ "' but its \ \initialisation expression evaluates to type: '" ++ (show t) ++ "'" else return () addVarToEnv (mapType dt) n sl Yes False checkDecls sl dt decls checkVarDefs :: ScopeLevel -> [Definition] -> TC () checkVarDefs sl [] = return () checkVarDefs sl ((DefDeclaration {ddType = dt, ddDeclarations = decls}):ds) = do checkDecls sl dt decls checkVarDefs sl ds processParams :: [(DataType, Name)] -> TC [Type] processParams [] = return [] processParams ((dt,n):ps) = do addVarToEnv (mapType dt) n 1 Yes True ts <- processParams ps return $ (mapType dt):ts checkFuncDecl :: DataType -> Declarator -> TC () checkFuncDecl dt DeclFunction {dfId = n, dfParams = ps} = do setCurrentFunctionName n b <- funcAlreadyExists n if b then emitError $ "Error: The function name '" ++ n ++ "' has already been used" else return () rs <- processParams ps addFuncToEnv (T_Arrow rs (mapType dt)) n checkFunctions :: [Definition] -> TC () checkFunctions [] = return () checkFunctions ((DefFunction {dfType = dt, dfDeclarator = decl, dfStatement = s}):ds) = do checkFuncDecl dt decl checkStm 1 s removeVarsAtScope 1 checkFunctions ds checkAll :: [Definition] -> TC () checkAll ds = do case find matchMain ds of Nothing -> emitError "Structural Error: There is no main() function" Just (DefFunction {dfType = dt, dfDeclarator = DeclFunction {dfParams = ps}}) | dt /= VoidType || length ps > 0 -> emitError "Structural Error: 'main()' should have type void and \ \should have no parameters" | otherwise -> return () checkVarDefs 0 $ filter onlyDecls ds checkFunctions $ filter onlyFuncs ds check :: AST -> IO [ErrorMessage] check (AST ds) = return . sndFromQuad $ apply (checkAll ds) [] initialEnv "" -------------------------------------------------------------------------- checkArrow :: Name -> Type -> [Type] -> TC Type checkArrow n (T_Arrow ta tr) t = do b <- checkTypes ta t if b then return tr else do emitError $ "Type Error: '" ++ n ++ "' was expected parameters of type: '" ++ (show ta) ++ "' but instead it was passed parameters of type: '" ++ (show t) ++ "'" return T_Unknown checkTypes :: [Type] -> [Type] -> TC Bool checkTypes t1s t2s | length t1s == length t2s = return $ and [t2 `subtypeOf` t1 || t1 == t2 | t1 <- t1s, t2 <- t2s] | otherwise = return False -------------------------------------------------------------------------- sndFromQuad :: (a,b,c,d) -> b sndFromQuad (_,b,_,_) = b mapType :: DataType -> Type mapType VoidType = T_Void mapType CharType = T_IntChar mapType IntType = T_IntChar mapType BoolType = T_Bool createStNdRdTh :: Int -> String createStNdRdTh i = case i `mod` 10 of 1 -> (show i) ++ "st" 2 -> (show i) ++ "nd" 3 -> (show i) ++ "rd" _ -> (show i) ++ "th"
tombusby/dissertation
src/Checker.hs
mit
14,102
92
28
3,080
5,997
3,136
2,861
353
12
import System.Environment sieve :: Integer -> [Integer] sieve n = takeWhile lessThan (till n) where lessThan x = x<=n till n = removeUntil (intSqrt n) [2..] intSqrt x | x <=0 = 0 | otherwise = maximum $ takeWhile square [1..x] where square y = y*y <= x removeUntil num list = tailremoveUntil num [] list tailremoveUntil num header rest@(x:xs) | num >= x = tailremoveUntil num (x:header) (removeMults x xs) | otherwise = (reverse header) ++ rest removeMults x xs = filter (notMultipleOf x) xs notMultipleOf x = \y -> (y `mod` x) /= 0 main = do args <- getArgs let n = (read $ head args) :: Integer mapM putStrLn (map show (sieve n))
Bolt64/my_code
haskell/sieve.hs
mit
797
0
12
282
327
162
165
19
1
module Tree where import Control.Monad import Test.QuickCheck import MonadLaws data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving (Eq, Show) instance Arbitrary a => Arbitrary (Tree a) where arbitrary = frequency [(2,liftM Leaf arbitrary), (1,liftM2 Branch arbitrary arbitrary)] shrink (Branch l r) = [l,r]++map (Branch l) (shrink r)++map (`Branch`r) (shrink l) shrink (Leaf a) = map Leaf (shrink a) --- instance Functor Tree where fmap f (Leaf x) = Leaf $ f x fmap f (Branch x1 x2) = Branch (f <$> x1) (f <$> x2) instance Applicative Tree where (Leaf f) <*> (Leaf x) = Leaf $ f x (Branch f1 f2) <*> (Branch x1 x2) = Branch (f1 <*> x1) (f2 <*> x2) pure x = Leaf x instance Monad Tree where (Leaf x) >>= k = k x (Branch x y) >>= k = Branch (x >>= k) (y >>= k) --- prop_TreeLeftUnit = prop_LeftUnit :: PropLeftUnit Tree prop_TreeRightUnit = prop_RightUnit :: PropRightUnit Tree prop_TreeAssoc = prop_Assoc :: PropAssoc Tree
NickAger/LearningHaskell
Monads and all that/Tree Monad.hsproj/Tree.hs
mit
1,005
0
10
245
469
242
227
25
1
reverse' :: [a] -> [a] reverse' [] = [] reverse' (x:xs) = reverse' xs ++ [x] main = do -- print $ reverse' [1..10000] print $ reverse [1..1000000]
shigemk2/haskell_abc
reverse.hs
mit
152
0
9
33
74
39
35
5
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} module Web.Markury.Model.DB where import Database.Persist.TH import Data.Text ( Text ) import Data.Time ( UTCTime ) share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Bookmark title Text description Text url Text created UTCTime modified UTCTime User email Text password Text created UTCTime modified UTCTime UniqueEmail email Tag title Text created UTCTime modified UTCTime BookmarkTag bookmarkId BookmarkId tagId TagId UniqueBookmarkTag bookmarkId tagId Session spockSessionId Text userEmail Text UniqueSpockSessionId spockSessionId |]
y-taka-23/markury
src/Web/Markury/Model/DB.hs
mit
836
0
7
168
64
41
23
11
0
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE GADTs #-} module DB0 where import Prelude hiding (readFile, putStrLn) import System.Console.Haskeline hiding (catch) import Control.Applicative import Data.String import Control.Monad import Control.Monad.Writer import Database.SQLite.Simple import System.Process import Database.SQLite.Simple.FromRow import System.Random import Data.Typeable import Control.Exception import Control.Monad.Error import Text.Read hiding (lift, get) import Data.Text.Lazy.IO (readFile,putStrLn) import Data.Text.Lazy (Text,replace,pack) import qualified Data.Text as S (pack) import Network.Mail.Client.Gmail import Network.Mail.Mime (Address (..)) import Database.SQLite.Simple.FromField import Database.SQLite.Simple.ToField import Database.SQLite.Simple.Ok type Mail = String type Login = String type UserId = Integer type ConvId = Integer type MessageId = Integer data DBError = UnknownKeyUser | AlreadyBooted | UnknownIdConversation | UnknownIdMessage | NotRespondable | NotBranchable | UnknownUser | NotAttachable | NotDisposable | IsPassage | NotClosed | IsClosed | NotOpen | UserInvitedBySomeoneElse | NotRetractable | NotOpponent | NotProponent | Proponent | Opponent | AlreadyVoted | AlreadyStored | NotStored | DatabaseError String deriving Show data Mailer = Reminding Login | Invitation Mail Login | LogginOut Login | Migration Mail Login | Booting Login deriving Show data Event = EvSendMail Mail Mailer String | EvNewMessage MessageId deriving Show instance Error DBError where strMsg = DatabaseError type ConnectionMonad = ErrorT DBError (WriterT [Event] IO) data Env = Env { equery :: (ToRow q, FromRow r) => Query -> q -> ConnectionMonad [r], eexecute :: ToRow q => Query -> q -> ConnectionMonad (), eexecute_ :: Query -> ConnectionMonad (), etransaction :: forall a. ConnectionMonad a -> ConnectionMonad a } catchDBException :: IO a -> ConnectionMonad a catchDBException f = do r <- liftIO $ catch (Right <$> f) (\(e :: SomeException) -> return (Left e)) case r of Left e -> throwError $ DatabaseError (show e) Right x -> return x mkEnv :: Connection -> Env mkEnv conn = Env (\q r -> catchDBException $ query conn q r) (\q r -> catchDBException $ execute conn q r) (\q -> catchDBException $ execute_ conn q) $ \c -> do liftIO $ execute_ conn "begin transaction" r <- lift $ runErrorT c case r of Left e -> do liftIO $ execute_ conn "rollback" throwError e Right x -> do liftIO $ execute_ conn "commit transaction" return x data CheckLogin = CheckLogin UserId Mail (Maybe UserId) instance FromRow CheckLogin where fromRow = CheckLogin <$> field <*> field <*> field -- | wrap an action in a check of the login presence checkingLogin :: Env -> Login -> (CheckLogin -> ConnectionMonad a) -> ConnectionMonad a checkingLogin e l f = do r <- equery e "select id,email,inviter from users where login=?" (Only l) case (r :: [CheckLogin]) of [i] -> f i _ -> throwError UnknownKeyUser transactOnLogin :: Env -> Login -> (UserId -> ConnectionMonad a) -> ConnectionMonad a transactOnLogin e l f = etransaction e $ checkingLogin e l $ \(CheckLogin ui _ _) -> f ui data MessageType = Passage | Open | Closed | Passed deriving (Eq,Show) data ParseException = ParseException deriving Show instance Exception ParseException instance FromField MessageType where fromField (fieldData -> SQLInteger 0) = Ok Passage fromField (fieldData -> SQLInteger 1) = Ok Open fromField (fieldData -> SQLInteger 2) = Ok Closed fromField (fieldData -> SQLInteger 3) = Ok Passed fromField _ = Errors [SomeException ParseException] instance ToField MessageType where toField Passage = SQLInteger 0 toField Open = SQLInteger 1 toField Closed = SQLInteger 2 toField Passed = SQLInteger 3 data MessageRow = MessageRow { mid :: MessageId, mtext :: String, muser :: UserId, mtype :: MessageType, mparent :: Maybe MessageId, mconversation ::ConvId, mvote :: Integer, mdata :: String } deriving Show instance FromRow MessageRow where fromRow = MessageRow <$> field <*> field <*> field <*> field <*> field <*> field <*> field <*> field checkingMessage :: Env -> MessageId -> (MessageRow -> ConnectionMonad a) -> ConnectionMonad a checkingMessage e mi f = do r <- equery e "select * from messages where id=?" (Only mi) case r :: [MessageRow] of [] -> throwError UnknownIdMessage [x] -> f x _ -> throwError $ DatabaseError "multiple message id inconsistence" pastMessages :: Env -> MessageId -> ConnectionMonad [MessageRow] pastMessages e mi = do checkingMessage e mi $ \_ -> return () equery e "with recursive ex(id,parent,message,vote,type,user,conversation,data) as (select id,parent,message,vote,type,user,conversation,data from messages where messages.id=? union all select messages.id,messages.parent,messages.message,messages.vote,messages.type,messages.user,messages.conversation,messages.data from messages,ex where messages.id=ex.parent) select id,message,user,type,parent,conversation,vote,data from ex" (Only mi) futureMessages :: Env -> Maybe MessageId -> ConnectionMonad [MessageRow] futureMessages e (Just mi) = equery e "select id,message,user,type,parent,conversation,vote,data from messages where parent=?" (Only mi) futureMessages e Nothing = equery e "select id,message,user,type,parent,conversation,vote,data from messages where parent isnull" () personalMessages :: Env -> UserId -> ConnectionMonad [MessageRow] personalMessages e ui = equery e ("select m1.id,m1.message,m1.user,m1.type,m1.parent,m1.conversation,m1.vote,m1.data from messages as m1 join messages as m2 on m1.parent = m2.id where m1.type=? and m2.user=?") (Closed,ui) ownedMessages :: Env -> UserId -> ConnectionMonad [MessageRow] ownedMessages e ui = equery e "select m1.id,m1.message,m1.user,m1.type,m1.parent,m1.conversation,m1.vote,m1.data from messages as m1 where m1.type<>? and m1.user=?" (Passage,ui) openConversations :: Env -> UserId -> ConnectionMonad [MessageRow] openConversations e ui = equery e "select m1.id,m1.message,m1.user,m1.type,m1.parent,m1.conversation,m1.vote,m1.data from messages as m1 where m1.type=? and m1.user<>?" (Open,ui) -- run :: (Env -> ConnectionMonad a) -> IO (a,[Event]) run f = do conn <- open "mootzoo.db" r <- runWriterT $ do r <- runErrorT $ f (mkEnv conn) case r of Left e -> liftIO $ print e Right x -> liftIO $ print x print r close conn --return r lastRow :: Env -> ConnectionMonad Integer lastRow e = do r <- equery e "select last_insert_rowid()" () case (r :: [Only Integer]) of [Only x] -> return x _ -> throwError $ DatabaseError "last rowid lost" newConversation :: Env -> MessageId -> ConnectionMonad ConvId newConversation e t = do eexecute e "insert into conversations values (null,?,?,?)" (t,t,1::Integer) lastRow e
paolino/mootzoo
DB0.hs
mit
8,062
2
16
2,255
1,941
1,022
919
179
3
-- ------------------------------------------------------ -- Types classify Values -- Primitive types -- "a string" :: String -- 12 :: Int -- instances of higher-order, parametrized types -- Just 10 :: Maybe Int -- Left 10 :: Either Int b -- functions are first class values -- (* 2) :: Num a => a -> a -- type-constructors are functions -- Just :: a -> Maybe a -- Left :: a -> Either a b -- ------------------------------------------------------ -- Kinds classify types -- For monomorphic types the kind signature is just the placeholder, "*": -- TYPE KIND -- [Char] :: * -- Maybe Int :: * -- Parametric types express higher-order kinds, e.g -- Maybe :: * -> * -- a -> Maybe a -- Either * -> * -> * -- a -> b -> Either a b -- Kinds can distinguish only lifted types (of kind *), -- Type Constructors (e.g. * -> * -> *) and "raw" unboxed types. -- ------------------------------------------------------ -- Typeclasses and higher-kinded polymorphism -- class Show a :: * -> * -- a -> Show a -- instance (Show a) => Show (Maybe a) where ... -- the typeclass parameters in the kind signatures need to be aligned: we use -- Maybe' b :: * instead of Maybe :: (* -> *) in order to match the kind of a :: *. -- class Monad m :: (* -> *) -> * -- m -> Monad m -- instance Monad Maybe where ... -- vs -- instance (Show a) => Show (Maybe a) where ...
uroboros/haskell_design_patterns
chapter7/1_higher_order_kinds.hs
mit
1,521
0
2
438
40
39
1
1
0
----------------------------------------------------------------------------- -- -- Module : Language.PureScript.CaseDeclarations -- Copyright : (c) Phil Freeman 2013 -- License : MIT -- -- Maintainer : Phil Freeman <paf31@cantab.net> -- Stability : experimental -- Portability : -- -- | -- This module implements the desugaring pass which replaces top-level binders with -- case expressions. -- ----------------------------------------------------------------------------- module Language.PureScript.Sugar.CaseDeclarations ( desugarCases, desugarCasesModule ) where import Data.Monoid ((<>)) import Data.List (groupBy) import Control.Applicative import Control.Monad ((<=<), forM, join, unless, replicateM) import Control.Monad.Error.Class import Language.PureScript.Names import Language.PureScript.Declarations import Language.PureScript.Environment import Language.PureScript.Errors import Language.PureScript.Supply -- | -- Replace all top-level binders in a module with case expressions. -- desugarCasesModule :: [Module] -> SupplyT (Either ErrorStack) [Module] desugarCasesModule ms = forM ms $ \(Module name ds exps) -> rethrow (strMsg ("Error in module " ++ show name) <>) $ Module name <$> (desugarCases <=< desugarAbs $ ds) <*> pure exps desugarAbs :: [Declaration] -> SupplyT (Either ErrorStack) [Declaration] desugarAbs = mapM f where (f, _, _) = everywhereOnValuesM return replace return replace :: Value -> SupplyT (Either ErrorStack) Value replace (Abs (Right binder) val) = do ident <- Ident <$> freshName return $ Abs (Left ident) $ Case [Var (Qualified Nothing ident)] [CaseAlternative [binder] Nothing val] replace other = return other -- | -- Replace all top-level binders with case expressions. -- desugarCases :: [Declaration] -> SupplyT (Either ErrorStack) [Declaration] desugarCases = desugarRest <=< fmap join . mapM toDecls . groupBy inSameGroup where desugarRest :: [Declaration] -> SupplyT (Either ErrorStack) [Declaration] desugarRest (TypeInstanceDeclaration name constraints className tys ds : rest) = (:) <$> (TypeInstanceDeclaration name constraints className tys <$> desugarCases ds) <*> desugarRest rest desugarRest (ValueDeclaration name nameKind bs g val : rest) = let (_, f, _) = everywhereOnValuesTopDownM return go return in (:) <$> (ValueDeclaration name nameKind bs g <$> f val) <*> desugarRest rest where go (Let ds val') = Let <$> desugarCases ds <*> pure val' go other = return other desugarRest (PositionedDeclaration pos d : ds) = do (d' : ds') <- desugarRest (d : ds) return (PositionedDeclaration pos d' : ds') desugarRest (d : ds) = (:) d <$> desugarRest ds desugarRest [] = pure [] inSameGroup :: Declaration -> Declaration -> Bool inSameGroup (ValueDeclaration ident1 _ _ _ _) (ValueDeclaration ident2 _ _ _ _) = ident1 == ident2 inSameGroup (PositionedDeclaration _ d1) d2 = inSameGroup d1 d2 inSameGroup d1 (PositionedDeclaration _ d2) = inSameGroup d1 d2 inSameGroup _ _ = False toDecls :: [Declaration] -> SupplyT (Either ErrorStack) [Declaration] toDecls [ValueDeclaration ident nameKind bs Nothing val] | all isVarBinder bs = do let args = map (\(VarBinder arg) -> arg) bs body = foldr (Abs . Left) val args return [ValueDeclaration ident nameKind [] Nothing body] toDecls ds@(ValueDeclaration ident _ bs _ _ : _) = do let tuples = map toTuple ds unless (all ((== length bs) . length . fst) tuples) $ throwError $ mkErrorStack ("Argument list lengths differ in declaration " ++ show ident) Nothing caseDecl <- makeCaseDeclaration ident tuples return [caseDecl] toDecls (PositionedDeclaration pos d : ds) = do (d' : ds') <- rethrowWithPosition pos $ toDecls (d : ds) return (PositionedDeclaration pos d' : ds') toDecls ds = return ds isVarBinder :: Binder -> Bool isVarBinder (VarBinder _) = True isVarBinder _ = False toTuple :: Declaration -> ([Binder], (Maybe Guard, Value)) toTuple (ValueDeclaration _ _ bs g val) = (bs, (g, val)) toTuple (PositionedDeclaration _ d) = toTuple d toTuple _ = error "Not a value declaration" makeCaseDeclaration :: Ident -> [([Binder], (Maybe Guard, Value))] -> SupplyT (Either ErrorStack) Declaration makeCaseDeclaration ident alternatives = do let argPattern = length . fst . head $ alternatives args <- map Ident <$> replicateM argPattern freshName let vars = map (Var . Qualified Nothing) args binders = [ CaseAlternative bs g val | (bs, (g, val)) <- alternatives ] value = foldr (Abs . Left) (Case vars binders) args return $ ValueDeclaration ident Value [] Nothing value
bergmark/purescript
src/Language/PureScript/Sugar/CaseDeclarations.hs
mit
4,657
0
16
835
1,536
794
742
-1
-1
module Main( main ) where import qualified FixedTest main = FixedTest.main
nzok/decimal
Main.hs
mit
81
0
5
17
20
13
7
4
1
{-# LANGUAGE CPP #-} module Cabal ( getPackageGhcOpts , findCabalFile, findFile ) where import Stack import Control.Exception (IOException, catch) import Control.Monad (when) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State (execStateT, modify) import Data.Char (isSpace) import Data.List (foldl', nub, sort, find, isPrefixOf, isSuffixOf) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative ((<$>)) import Data.Monoid (Monoid(..)) #endif import Distribution.Package (PackageIdentifier(..), PackageName) import Distribution.PackageDescription (PackageDescription(..), Executable(..), TestSuite(..), Benchmark(..), emptyHookedBuildInfo, buildable, libBuildInfo) import Distribution.PackageDescription.Parse (readPackageDescription) import Distribution.Simple.Configure (configure) import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..), ComponentLocalBuildInfo(..), Component(..), ComponentName(..), #if !MIN_VERSION_Cabal(1,18,0) allComponentsBy, #endif componentBuildInfo, foldComponent) import Distribution.Simple.Compiler (PackageDB(..)) import Distribution.Simple.Command (CommandParse(..), commandParseArgs) import Distribution.Simple.GHC (componentGhcOptions) import Distribution.Simple.Program (defaultProgramConfiguration) import Distribution.Simple.Program.Db (lookupProgram) import Distribution.Simple.Program.Types (ConfiguredProgram(programVersion), simpleProgram) import Distribution.Simple.Program.GHC (GhcOptions(..), renderGhcOptions) import Distribution.Simple.Setup (ConfigFlags(..), defaultConfigFlags, configureCommand, toFlag) #if MIN_VERSION_Cabal(1,21,1) import Distribution.Utils.NubList #endif import qualified Distribution.Simple.GHC as GHC(configure) import Distribution.Verbosity (silent) import Distribution.Version (Version(..)) import System.IO.Error (ioeGetErrorString) import System.Directory (doesFileExist, doesDirectoryExist, getDirectoryContents) import System.FilePath (takeDirectory, splitFileName, (</>)) componentName :: Component -> ComponentName componentName = foldComponent (const CLibName) (CExeName . exeName) (CTestName . testName) (CBenchName . benchmarkName) getComponentLocalBuildInfo :: LocalBuildInfo -> ComponentName -> ComponentLocalBuildInfo #if MIN_VERSION_Cabal(1,18,0) getComponentLocalBuildInfo lbi cname = getLocalBuildInfo cname $ componentsConfigs lbi where getLocalBuildInfo cname' ((cname'', clbi, _):cfgs) = if cname' == cname'' then clbi else getLocalBuildInfo cname' cfgs getLocalBuildInfo _ [] = error $ "internal error: missing config" #else getComponentLocalBuildInfo lbi CLibName = case libraryConfig lbi of Nothing -> error $ "internal error: missing library config" Just clbi -> clbi getComponentLocalBuildInfo lbi (CExeName name) = case lookup name (executableConfigs lbi) of Nothing -> error $ "internal error: missing config for executable " ++ name Just clbi -> clbi getComponentLocalBuildInfo lbi (CTestName name) = case lookup name (testSuiteConfigs lbi) of Nothing -> error $ "internal error: missing config for test suite " ++ name Just clbi -> clbi getComponentLocalBuildInfo lbi (CBenchName name) = case lookup name (testSuiteConfigs lbi) of Nothing -> error $ "internal error: missing config for benchmark " ++ name Just clbi -> clbi #endif #if MIN_VERSION_Cabal(1,18,0) -- TODO: Fix callsites so we don't need `allComponentsBy`. It was taken from -- http://hackage.haskell.org/package/Cabal-1.16.0.3/docs/src/Distribution-Simple-LocalBuildInfo.html#allComponentsBy -- since it doesn't exist in Cabal 1.18.* -- -- | Obtains all components (libs, exes, or test suites), transformed by the -- given function. Useful for gathering dependencies with component context. allComponentsBy :: PackageDescription -> (Component -> a) -> [a] allComponentsBy pkg_descr f = [ f (CLib lib) | Just lib <- [library pkg_descr] , buildable (libBuildInfo lib) ] ++ [ f (CExe exe) | exe <- executables pkg_descr , buildable (buildInfo exe) ] ++ [ f (CTest tst) | tst <- testSuites pkg_descr , buildable (testBuildInfo tst) , testEnabled tst ] ++ [ f (CBench bm) | bm <- benchmarks pkg_descr , buildable (benchmarkBuildInfo bm) , benchmarkEnabled bm ] #endif stackifyFlags :: ConfigFlags -> Maybe StackConfig -> ConfigFlags stackifyFlags cfg Nothing = cfg stackifyFlags cfg (Just si) = cfg { configHcPath = toFlag ghc , configHcPkg = toFlag ghcPkg , configDistPref = toFlag dist , configPackageDBs = pdbs } where pdbs = [Nothing, Just GlobalPackageDB] ++ pdbs' pdbs' = Just . SpecificPackageDB <$> stackDbs si dist = stackDist si ghc = stackGhcBinDir si </> "ghc" ghcPkg = stackGhcBinDir si </> "ghc-pkg" -- via: https://groups.google.com/d/msg/haskell-stack/8HJ6DHAinU0/J68U6AXTsasJ -- cabal configure --package-db=clear --package-db=global --package-db=$(stack path --snapshot-pkg-db) --package-db=$(stack path --local-pkg-db) getPackageGhcOpts :: FilePath -> Maybe StackConfig -> [String] -> IO (Either String [String]) getPackageGhcOpts path mbStack opts = do getPackageGhcOpts' `catch` (\e -> do return $ Left $ "Cabal error: " ++ (ioeGetErrorString (e :: IOException))) where getPackageGhcOpts' :: IO (Either String [String]) getPackageGhcOpts' = do genPkgDescr <- readPackageDescription silent path distDir <- getDistDir let programCfg = defaultProgramConfiguration let initCfgFlags = (defaultConfigFlags programCfg) { configDistPref = toFlag distDir -- TODO: figure out how to find out this flag , configUserInstall = toFlag True -- configure with --enable-tests to include test dependencies/modules , configTests = toFlag True -- configure with --enable-benchmarks to include benchmark dependencies/modules , configBenchmarks = toFlag True } let initCfgFlags' = stackifyFlags initCfgFlags mbStack cfgFlags <- flip execStateT initCfgFlags' $ do let sandboxConfig = takeDirectory path </> "cabal.sandbox.config" exists <- lift $ doesFileExist sandboxConfig when (exists) $ do sandboxPackageDb <- lift $ getSandboxPackageDB sandboxConfig modify $ \x -> x { configPackageDBs = [Just sandboxPackageDb] } let cmdUI = configureCommand programCfg case commandParseArgs cmdUI True opts of CommandReadyToGo (modFlags, _) -> modify modFlags CommandErrors (e:_) -> error e _ -> return () localBuildInfo <- configure (genPkgDescr, emptyHookedBuildInfo) cfgFlags let pkgDescr = localPkgDescr localBuildInfo let baseDir = fst . splitFileName $ path case getGhcVersion localBuildInfo of Nothing -> return $ Left "GHC is not configured" Just ghcVersion -> do let mbLibName = pkgLibName pkgDescr let ghcOpts' = foldl' mappend mempty . map (getComponentGhcOptions localBuildInfo) . flip allComponentsBy (\c -> c) . localPkgDescr $ localBuildInfo -- FIX bug in GhcOptions' `mappend` #if MIN_VERSION_Cabal(1,21,1) -- API Change: -- Distribution.Simple.Program.GHC.GhcOptions now uses NubListR's -- GhcOptions { .. ghcOptPackages :: NubListR (InstalledPackageId, PackageId, ModuleRemaining) .. } ghcOpts = ghcOpts' { ghcOptExtra = overNubListR (filter (/= "-Werror")) $ ghcOptExtra ghcOpts' #if __GLASGOW_HASKELL__ >= 709 , ghcOptPackageDBs = sort $ nub (ghcOptPackageDBs ghcOpts') #endif , ghcOptPackages = overNubListR (filter (\(_, pkgId, _) -> Just (pkgName pkgId) /= mbLibName)) $ (ghcOptPackages ghcOpts') , ghcOptSourcePath = overNubListR (map (baseDir </>)) (ghcOptSourcePath ghcOpts') } #else -- GhcOptions { .. ghcOptPackages :: [(InstalledPackageId, PackageId)] .. } let ghcOpts = ghcOpts' { ghcOptExtra = filter (/= "-Werror") $ nub $ ghcOptExtra ghcOpts' , ghcOptPackages = filter (\(_, pkgId) -> Just (pkgName pkgId) /= mbLibName) $ nub (ghcOptPackages ghcOpts') , ghcOptSourcePath = map (baseDir </>) (ghcOptSourcePath ghcOpts') } #endif #if MIN_VERSION_Cabal(1,18,0) -- API Change: -- Distribution.Simple.GHC.configure now returns (Compiler, Maybe Platform, ProgramConfiguration) -- It used to just return (Compiler, ProgramConfiguration) -- GHC.configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramConfiguration -- -> IO (Compiler, Maybe Platform, ProgramConfiguration) (ghcInfo, mbPlatform, _) <- GHC.configure silent Nothing Nothing defaultProgramConfiguration #else -- configure :: Verbosity -> Maybe FilePath -> Maybe FilePath -> ProgramConfiguration -- -> IO (Compiler, ProgramConfiguration) (ghcInfo, _) <- GHC.configure silent Nothing Nothing defaultProgramConfiguration -- let mbPlatform = Just (hostPlatform localBuildInfo) :: Maybe Platform #endif putStrLn $ "Configured GHC " ++ show ghcVersion #if MIN_VERSION_Cabal(1,18,0) ++ " " ++ show mbPlatform #endif #if MIN_VERSION_Cabal(1,23,2) -- API Change: -- Distribution.Simple.Program.GHC.renderGhcOptions now takes Platform argument -- renderGhcOptions :: Compiler -> Platform -> GhcOptions -> [String] return $ case mbPlatform of Just platform -> Right $ renderGhcOptions ghcInfo platform ghcOpts Nothing -> Left "GHC.configure did not return platform" #else #if MIN_VERSION_Cabal(1,20,0) -- renderGhcOptions :: Compiler -> GhcOptions -> [String] return $ Right $ renderGhcOptions ghcInfo ghcOpts #else -- renderGhcOptions :: Version -> GhcOptions -> [String] return $ Right $ renderGhcOptions ghcVersion ghcOpts #endif #endif -- returns the right 'dist' directory in the case of a sandbox getDistDir = do let dir = takeDirectory path </> "dist" exists <- doesDirectoryExist dir if not exists then return dir else do contents <- getDirectoryContents dir return . maybe dir (dir </>) $ find ("dist-sandbox-" `isPrefixOf`) contents pkgLibName :: PackageDescription -> Maybe PackageName pkgLibName pkgDescr = if hasLibrary pkgDescr then Just $ pkgName . package $ pkgDescr else Nothing hasLibrary :: PackageDescription -> Bool hasLibrary = maybe False (\_ -> True) . library getComponentGhcOptions :: LocalBuildInfo -> Component -> GhcOptions getComponentGhcOptions lbi comp = componentGhcOptions silent lbi bi clbi (buildDir lbi) where bi = componentBuildInfo comp clbi = getComponentLocalBuildInfo lbi (componentName comp) getGhcVersion :: LocalBuildInfo -> Maybe Version getGhcVersion lbi = let db = withPrograms lbi in do ghc <- lookupProgram (simpleProgram "ghc") db programVersion ghc getSandboxPackageDB :: FilePath -> IO PackageDB getSandboxPackageDB sandboxPath = do contents <- readFile sandboxPath return $ SpecificPackageDB $ extractValue . parse $ contents where pkgDbKey = "package-db:" parse = head . filter (pkgDbKey `isPrefixOf`) . lines extractValue = fst . break (`elem` "\n\r") . dropWhile isSpace . drop (length pkgDbKey) -- | looks for file matching a predicate starting from dir and going up until root findFile :: (FilePath -> Bool) -> FilePath -> IO (Maybe FilePath) findFile p dir = do allFiles <- getDirectoryContents dir case find p allFiles of Just cabalFile -> return $ Just $ dir </> cabalFile Nothing -> let parentDir = takeDirectory dir in if parentDir == dir then return Nothing else findFile p parentDir findCabalFile :: FilePath -> IO (Maybe FilePath) findCabalFile = findFile isCabalFile where isCabalFile :: FilePath -> Bool isCabalFile path = ".cabal" `isSuffixOf` path && length path > length ".cabal"
pacak/hdevtools
src/Cabal.hs
mit
12,991
0
28
3,345
2,370
1,280
1,090
153
5
{-# LANGUAGE TypeSynonymInstances #-} module Parse where import Lang import Control.Applicative import Control.Monad import Data.Char import Data.List {- Note: Much of this is taken from UCSD cse230 lecture notes. Some of it I figured out on my own, but a lot of it is thanks to those notes. https://cseweb.ucsd.edu/classes/wi12/cse230-a/lectures/parsers.html-} newtype Parser a = P (String -> [(a,String)]) parse :: Parser a -> String -> [(a,String)] parse (P p) s = p s {- takes two parsers, does one after the other-} pairP :: Parser a -> Parser b -> Parser (a,b) pairP (P p1) (P p2) = P (\cs -> [((x,y),cs'') | (x,cs') <- (p1 cs), (y,cs'') <- (p2 cs')]) {- Return is the "identity parser"-} identP :: a -> Parser a identP x = P (\cs -> [(x,cs)]) {- so, we need to suck the a values out of the first parser and invoke the second parser with them on the remaining part of the string. -} {- That makes sense... -} composeP :: Parser a -> (a -> Parser b) -> Parser b composeP pa f = P (\cs -> [(y,cs'') | (x,cs') <- parse pa cs, (y,cs'') <- parse (f x) cs']) fmapP :: (a -> b) -> Parser a -> Parser b fmapP f p = P (\cs -> [(f x, cs')| (x,cs') <- parse p cs]) seqP :: Parser (a -> b) -> Parser a -> Parser b seqP pf pa = P (\cs -> [(y,cs'') | (x,cs') <- parse pf cs, (y,cs'') <- parse (fmapP x pa) cs']) instance Functor Parser where fmap = fmapP instance Applicative Parser where pure = identP (<*>) = seqP {- do means return a parser that does these things -} instance Monad Parser where (>>=) = composeP return = identP failToParse :: Parser a failToParse = P (\s -> []) altParse :: Parser a -> Parser a -> Parser a altParse p1 p2 = P (\cs -> let v = parse p1 cs in if null v then parse p2 cs else v) instance Alternative Parser where (<|>) = altParse empty = failToParse instance MonadPlus Parser where mplus = altParse mzero = failToParse singleChar :: Parser Char singleChar = P (\s -> case s of [] -> [] c : cs -> [(c,cs)]) parseIf :: (a -> Bool) -> Parser a -> Parser a parseIf pred pa = P (\cs -> [(x,cs') | (x,cs') <- filter (pred . fst) $ parse pa cs]) digAsChar :: Parser Char digAsChar = parseIf isDigit singleChar tryBothParse :: Parser a -> Parser a -> Parser a tryBothParse p1 p2 = P (\cs -> (parse p1 cs) ++ (parse p2 cs)) zeroOrOne :: Parser a -> a -> Parser a zeroOrOne p base = tryBothParse p $ P (\cs -> [(base,cs)]) parseWord :: String -> Parser String parseWord str = P (\cs -> if (Data.List.isPrefixOf str cs) then [(str,drop (length str) cs)] else []) nat :: Parser Int nat = do cs <- some digAsChar return $ read cs letter :: Parser Char letter = parseIf (\c -> any (==c) $ ['a'..'z'] ++ ['A'..'Z']) singleChar parseChar :: Char -> Parser Char parseChar c = parseIf (==c) singleChar space :: Parser Char space = parseChar ' ' nonSpace :: Parser Char nonSpace = parseIf (/=' ') singleChar openParen :: Parser Char openParen = parseChar '(' closeParen :: Parser Char closeParen = parseChar ')' equal :: Parser Char equal = parseChar '=' neg :: Parser Char neg = parseChar '-' notParse :: Parser Char notParse = parseChar '!' {- Zero or more -} possible :: Parser a -> Parser [a] possible = many binOp :: Parser BOp binOp = do op <- some nonSpace return $ bopRead op monOp :: Parser MOp monOp = do op <- neg <|> notParse return $ mopRead $ return op validIdentChars :: [Char] validIdentChars = ['a'..'z'] ++ ['A'..'Z'] ++ ['_','\''] identChar :: Parser Char identChar = parseIf (\c -> any (==c) validIdentChars) singleChar invalidIdents :: [String] invalidIdents = ["if","let","susp","force"] isValidIdent :: String -> Bool isValidIdent x = not $ any (==x) invalidIdents ident :: Parser Expr ident = do ide <- some identChar guard $ isValidIdent ide return $ Ident ide booleanValue :: Parser String booleanValue = parseIf (\s -> s == "True" || s == "False") (some letter) bool :: Parser Lit bool = do b <- booleanValue return $ litRead b int :: Parser Lit int = do x <- zeroOrOne neg '∅' i <- nat return $ LInt $ if (x == '∅') then i else -i lit :: Parser Lit lit = int <|> bool litExpr :: Parser Expr litExpr = do _ <- many space l <- lit _ <- many space return $ Lit l force :: Parser Expr force = do many space parseWord "force" openParen many space e <- parseExpr many space closeParen many space return $ Force e susp :: Parser Expr susp = do many space parseWord "susp" openParen many space e <- parseExpr many space closeParen many space return $ Susp e lam :: Parser Expr lam = do many space openParen many space parseWord "\\" (Ident x) <- ident space parseWord "->" space e <- parseExpr many space closeParen many space return $ Lam x e app :: Parser Expr app = do many space openParen e <- parseExpr many space e' <- parseExpr closeParen many space return $ App e e' bopExpr :: Parser Expr bopExpr = do many space openParen many space e0 <- parseExpr many space b <- binOp many space e1 <- parseExpr many space closeParen many space return $ BinOp b e0 e1 mopExpr :: Parser Expr mopExpr = do many space m <- monOp e <- parseExpr many space return $ MonOp m e letExpr :: Parser Expr letExpr = do many space parseWord "let" many space (Ident x) <- ident many space equal many space e <- parseExpr many space parseWord "in" many space e' <- parseExpr many space return $ Let (Bind x e) e' ifExpr :: Parser Expr ifExpr = do many space parseWord "if" many space c <- parseExpr many space parseWord "then" many space et <- parseExpr many space parseWord "else" many space ef <- parseExpr many space return $ If c et ef parseExpr :: Parser Expr parseExpr = do e <- ident <|> litExpr <|> susp <|> force <|> lam <|> app <|> bopExpr <|> mopExpr <|> letExpr <|> ifExpr return e
jdublu10/toy_lang
src/Parse.hs
mit
6,905
0
16
2,368
2,505
1,233
1,272
240
2
module NewtypeDeriving.Reification where import BasePrelude import Language.Haskell.TH data Newtype = Newtype { newtypeTypeName :: Name, newtypeConstructorName :: Name, newtypeInnerType :: Type } deriving (Show) reifyNewtype :: Name -> Q (Either String Newtype) reifyNewtype = fmap parseInfo . reify where parseInfo = \case TyConI (NewtypeD _ typeName _ con derivations) -> do (conName, innerType) <- case con of NormalC n [(_, t)] -> Right (n, t) RecC n [(_, _, t)] -> Right (n, t) _ -> Left $ "Invalid constructor: " <> show con return $ Newtype typeName conName innerType i -> Left $ "Invalid type of a name" -- | -- Given a kind @* -> *@ type, -- peel off a kind @(* -> *) -> (* -> *)@ type (the monad-transformer) -- and another @* -> *@ type (the inner monad). peelTransformer :: Type -> Maybe (Type, Type) peelTransformer = \case AppT t m -> Just (t, m) _ -> Nothing
nikita-volkov/newtype-deriving
library/NewtypeDeriving/Reification.hs
mit
1,024
0
18
304
287
156
131
-1
-1
module CIO ( CIO, runCIO, runCIO', MonadCIO(..), mapMConcurrently, mapMConcurrently', mapMConcurrently_, forMConcurrently, forMConcurrently', forMConcurrently_, distributeConcurrently, distributeConcurrently_, ) where import CIO.Prelude import qualified Control.Concurrent.ParallelIO.Local as ParallelIO -- | Concurrent IO. A composable monad of IO actions executable in a shared pool of threads. newtype CIO r = CIO (ReaderT (ParallelIO.Pool, Int) IO r) deriving (Functor, Applicative, Monad) instance MonadIO CIO where liftIO io = CIO $ lift io instance MonadSTM CIO where liftSTM = CIO . liftSTM -- | Run with a pool of the specified size. runCIO :: Int -> CIO r -> IO r runCIO numCapabilities (CIO t) = ParallelIO.withPool numCapabilities $ \pool -> runReaderT t (pool, numCapabilities) -- | Run with a pool the size of the amount of available processors. runCIO' :: CIO r -> IO r runCIO' cio = do numCapabilities <- getNumCapabilities runCIO numCapabilities cio class (Monad m) => MonadCIO m where -- | Get the maximum number of available threads, which is set in 'runCIO'. getPoolNumCapabilities :: m Int -- | Same as @Control.Monad.'Control.Monad.sequence'@, but performs concurrently. sequenceConcurrently :: [m a] -> m [a] -- | Same as 'sequenceConcurrently' with a difference that -- it does not maintain the order of results, -- which allows it to execute a bit more efficiently. sequenceConcurrently' :: [m a] -> m [a] -- | Same as @Control.Monad.'Control.Monad.sequence_'@, but performs concurrently. -- Blocks the calling thread until all actions are finished. sequenceConcurrently_ :: [m a] -> m () instance MonadCIO CIO where getPoolNumCapabilities = CIO $ do (_, z) <- ask return z sequenceConcurrently actions = CIO $ do env@(pool, _) <- ask lift $ ParallelIO.parallel pool $ map (envToCIOToIO env) actions where envToCIOToIO env (CIO t) = runReaderT t env sequenceConcurrently' actions = CIO $ do env@(pool, _) <- ask lift $ ParallelIO.parallelInterleaved pool $ map (envToCIOToIO env) actions where envToCIOToIO env (CIO t) = runReaderT t env sequenceConcurrently_ actions = CIO $ do env@(pool, _) <- ask lift $ ParallelIO.parallel_ pool $ map (envToCIOToIO env) actions where envToCIOToIO env (CIO t) = runReaderT t env instance (MonadCIO m) => MonadCIO (ReaderT r m) where getPoolNumCapabilities = lift getPoolNumCapabilities sequenceConcurrently actions = do env <- ask let cioActions = map (flip runReaderT env) actions lift $ sequenceConcurrently cioActions sequenceConcurrently' actions = do env <- ask let cioActions = map (flip runReaderT env) actions lift $ sequenceConcurrently' cioActions sequenceConcurrently_ actions = do env <- ask let cioActions = map (flip runReaderT env) actions lift $ sequenceConcurrently_ cioActions instance (MonadCIO m, Monoid w) => MonadCIO (WriterT w m) where getPoolNumCapabilities = lift getPoolNumCapabilities sequenceConcurrently actions = do let cioActions = map runWriterT actions WriterT $ do (as, ws) <- return . unzip =<< sequenceConcurrently cioActions return (as, mconcat ws) sequenceConcurrently' actions = do let cioActions = map runWriterT actions WriterT $ do (as, ws) <- return . unzip =<< sequenceConcurrently' cioActions return (as, mconcat ws) sequenceConcurrently_ actions = do let cioActions = map execWriterT actions WriterT $ do ws <- sequenceConcurrently' cioActions return ((), mconcat ws) mapMConcurrently :: (MonadCIO m) => (a -> m b) -> [a] -> m [b] mapMConcurrently f = sequenceConcurrently . map f mapMConcurrently' :: (MonadCIO m) => (a -> m b) -> [a] -> m [b] mapMConcurrently' f = sequenceConcurrently' . map f mapMConcurrently_ :: (MonadCIO m) => (a -> m b) -> [a] -> m () mapMConcurrently_ f = sequenceConcurrently_ . map f forMConcurrently :: (MonadCIO m) => [a] -> (a -> m b) -> m [b] forMConcurrently = flip mapMConcurrently forMConcurrently' :: (MonadCIO m) => [a] -> (a -> m b) -> m [b] forMConcurrently' = flip mapMConcurrently' forMConcurrently_ :: (MonadCIO m) => [a] -> (a -> m b) -> m () forMConcurrently_ = flip mapMConcurrently_ replicateMConcurrently :: (MonadCIO m) => Int -> m a -> m [a] replicateMConcurrently n = sequenceConcurrently . replicate n replicateMConcurrently' :: (MonadCIO m) => Int -> m a -> m [a] replicateMConcurrently' n = sequenceConcurrently' . replicate n replicateMConcurrently_ :: (MonadCIO m) => Int -> m a -> m () replicateMConcurrently_ n = sequenceConcurrently_ . replicate n -- | -- Run the provided side-effecting action on all available threads and -- collect the results. The order of results may vary from run to run. distributeConcurrently :: (MonadCIO m) => m a -> m [a] distributeConcurrently action = do n <- getPoolNumCapabilities replicateMConcurrently' n action -- | -- Run the provided side-effecting action on all available threads. distributeConcurrently_ :: (MonadCIO m) => m a -> m () distributeConcurrently_ action = do n <- getPoolNumCapabilities replicateMConcurrently_ n action
nikita-volkov/cio
src/CIO.hs
mit
5,282
0
13
1,094
1,569
793
776
111
1
-- | -- Module : Strp.Modules -- Copyright : 2014 Joe Jevnik -- License : GPL v3 -- -- Maintainer : Joe Jevnik -- Stability : experimental -- Portability : requires xclip -- -- Default modules for strp. {-# LANGUAGE CPP,QuasiQuotes #-} module Strp.Modules ( module Strp.Data , urlModule -- :: StrpModule , filePathModule -- :: StrpModule , searchEngineModule -- :: StrpModule ) where import Strp.Data import Control.Monad (void,when) import System.Directory (doesDirectoryExist,doesFileExist) import System.Process (createProcess,CreateProcess(..),StdStream(..),proc) import Text.RawString.QQ (r) import Text.Regex.PCRE ((=~)) -- | A 'StrpModule' for handling url data. urlModule :: StrpModule urlModule = StrpModule { strpMatch = (=~ [r|(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%]\ )|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|job\ s|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|\ as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|c\ c|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee\ |eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|\ gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|k\ g|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh\ |mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|\ nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|s\ d|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk\ |tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|\ yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]\ +?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?\ «»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aer\ o|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|a\ d|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm\ |bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|\ cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|g\ e|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in\ |io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|\ ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|m\ z|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw\ |py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|\ sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|u\ z|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))|]) -- " , strpFunction = \cs -> void $ createProcess (proc "firefox" [cs]) { std_err = CreatePipe } } -- | The module to handle local filepaths. filePathModule :: StrpModule filePathModule = StrpModule { strpMatch = (=~ [r|^['"]?(?:/[^/]+)*['"]?$|]) , strpFunction = filePathModFunc } -- | The function to handle local filepaths. filePathModFunc :: String -> IO () filePathModFunc cs = doesDirectoryExist cs >>= \b -> when b (runFunc cs) >> doesFileExist cs >>= \b -> when b (runFunc (f cs)) where runFunc cs = void $ createProcess (proc "xterm" []) { cwd = Just cs } f cs = reverse $ dropWhile (/= '/') $ reverse cs -- | The module to search for a string in a search engine. -- CATCH-ALL searchEngineModule :: StrpModule searchEngineModule = StrpModule { strpMatch = const True , strpFunction = \cs -> void $ createProcess (proc "firefox" [mkSearch cs]) { std_err = CreatePipe } } where mkSearch cs = "www.google.com/#q=" ++ map (\c -> if c == ' ' then '+' else c) cs ++ "&safe=off"
llllllllll/strp
Strp/Modules.hs
gpl-2.0
4,312
0
14
836
466
276
190
37
2